How to preprocess PrintDocument to calculate the total number of pages before printing?

In answer to this question ...

Print x of y page in .Net

The accepted answer included this expression ...

You do not need to print twice, you just need to simulate printing for the first time.

So, how can you go through a document once at first without output to a printer or screen?

+6
source share
1 answer

You will need to create a printer device context and display your pages using this device context as a reference DC, keeping track of the number of pages you viewed. This should be done outside of the .NET Printing infrastructure.

  • Get DC Link Printer
  • Create a bitmap based on a standard DC printer
  • Create a graphic object for drawing on a bitmap
  • Display page for bitmap using graphic object (pages are listed here)
  • Additional data for printing? Go to 4

Here the screenshot in step 1 assumes that you are working in winforms ...

Private Function GetHighResolutionGraphics() As Graphics Try Dim HighestResolution As Printing.PrinterResolution = Nothing Dim HighestResolutionPrinter As String = "" Dim XResolution As Integer = Integer.MinValue Using dlg As New PrintDialog For Each Printer As String In Printing.PrinterSettings.InstalledPrinters dlg.PrinterSettings.PrinterName = Printer For Each Resolution As Printing.PrinterResolution In dlg.PrinterSettings.PrinterResolutions Using gr As Graphics = dlg.PrinterSettings.CreateMeasurementGraphics() If gr.DpiX > XResolution Then HighestResolution = Resolution HighestResolutionPrinter = Printer XResolution = gr.DpiX End If End Using Next Next dlg.PrinterSettings.PrinterName = HighestResolutionPrinter dlg.PrinterSettings.DefaultPageSettings.PrinterResolution = HighestResolution Return dlg.PrinterSettings.CreateMeasurementGraphics() End Using Catch ex As Exception ' handle or ignore .NET AccessViolation for certain network printers that are turned off, etc... End Try Return Me.CreateGraphics() End Function 

Step 2 is β€œsimple”, using the returned Graphics Object with the PagePrint event code already implemented to display the pages in the corresponding bitmap, keeping track of the number of pages you are viewing. Remember to reorganize your PagePrint event into a separate procedure that accepts a Graphics object, so you can use it to print, preview, and paginate. Remember to remove the Graphics and Bitmap object

 using gfxReference as Graphics = GetHighResolutionGraphics() using bmpPage as new Bitmap(gfxReference.DpiX * 8.5, gfxReference.DpiY * 11) using gfxRender as Graphics = Graphics.FromImage(bmpPage) gfxRender.Clear(Color.White) // Existing PagePrint event logic goes here (uses gfxRender) // Track Number of pages printed end using end using end using 
+3
source

Source: https://habr.com/ru/post/895382/


All Articles