回答这个问题......
接受的答案包括这一陈述......
您不必打印两次,只需模拟打印即可 第一次。
那么,如何在没有任何输出到打印机或屏幕的情况下首次通过文档?
答案 0 :(得分:3)
您需要创建一个打印机设备上下文,并使用该设备上下文作为参考DC渲染您的页面,同时跟踪您渲染的页面数。这必须在.NET Printing infrastructure的范围之外完成。
以下是第1步的镜头,假设您正在使用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
第2步“简单地”使用返回的参考图形对象和已经实现的PagePrint事件代码将页面渲染到适当的位图,同时跟踪您正在渲染的页面数。不要忘记将PagePrint事件重构为接受Graphics对象的单独例程,以便它可用于打印,预览和页码。不要忘记处理Graphics对象和Bitmap
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