PrintPreview / Print differences

InertiaM

Well-known member
Joined
Nov 3, 2007
Messages
663
Location
Kent, UK
Programming Experience
10+
When I run the following code, the PrintPreview looks fine. If I then click the print button from within the Preview window, the page prints but is not in the same place as the print preview - it's all shifted about 5mm to the right and about 5mm down.

VB.NET:
Option Explicit On
Option Strict On

Imports System.Drawing.Printing

Public Class Form1

    Public WithEvents pdPrinter As PrintDocument
    Public ppvwPrinter As PrintPreviewDialog

    Private shtPageNumber As Int16 = 0
    Private shtTotalPages As Int16 = 0


    Private Sub TestPrintPreview(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click
        pdPrinter = New PrintDocument
        ppvwPrinter = New PrintPreviewDialog
        ppvwPrinter.Document = pdPrinter
        ppvwPrinter.Width = Screen.PrimaryScreen.Bounds.Width
        ppvwPrinter.Height = Screen.PrimaryScreen.Bounds.Height
        ppvwPrinter.PrintPreviewControl.Zoom = 0.66
        ppvwPrinter.ShowDialog()
        pdPrinter.Dispose()
        ppvwPrinter.Dispose()
    End Sub

    Private Sub Begin_Printing(ByVal sender As System.Object, _
    ByVal e As System.Drawing.Printing.PrintEventArgs) _
     Handles pdPrinter.BeginPrint
        pdPrinter.DocumentName = "Test Document"
        pdPrinter.PrintController = New Printing.StandardPrintController()
        shtTotalPages = 1

        shtPageNumber = 0
    End Sub

    Private fArial18 As New Font("Arial", 18, FontStyle.Bold)

    Private Sub Test_PrintPage(ByVal sender As System.Object, _
    ByVal e As PrintPageEventArgs) Handles pdPrinter.PrintPage
        shtPageNumber += 1S
        With e.Graphics
            .PageUnit = GraphicsUnit.Millimeter

            .DrawString("TEST PAGE " & shtPageNumber.ToString(), fArial18, Brushes.Black, 15, 12 * shtPageNumber)
            '10mm border around an A4 Portrait page
            .DrawRectangle(Pens.Black, 10, 10, 210 - 10 - 10, 297 - 10 - 10)
        End With

        If shtPageNumber < shtTotalPages Then
            e.HasMorePages = True
        Else
            e.HasMorePages = False
        End If
    End Sub

End Class

If I put a TranslateTransform line in, it makes the PrintPreview wrong but the page prints correctly.

I've tried it to three different network printers, all with different printer drivers but still A4 Portrait as default, and the results are always the same.

Any ideas :confused:
 
It seems to relate to the HardMargins (see link). This may not be the best way to solve it, but it seems to work :-

VB.NET:
            .PageUnit = GraphicsUnit.Millimeter
            If Not pdPrinter.PrintController.IsPreview Then
                .TranslateTransform(Convert.ToSingle(-((e.PageSettings.HardMarginX / 100) * 25.4)), _
                Convert.ToSingle(-((e.PageSettings.HardMarginY / 100) * 25.4)))
            End If
 
Back
Top