在VB.NET中使用Microsoft Print To PDF产生0 KB“ PDF”

时间:2019-03-21 14:25:55

标签: vb.net pdf

尝试打印为pdf时遇到一些问题。 也许你们中的一些人可以看看我的代码片段?

[...]

Private tmpPDFName As String
Private printPDF As Printing.PrintDocument

''' <summary>
''' Delegate Method "finishPrintingPDF" should be called when finishing Printing 
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub finishPrintingPDF(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintEventArgs)

    Dim targetDir As String

    Try
        targetDir = "C:\Finished\"
        If Not System.IO.Directory.Exists(targetDir) Then System.IO.Directory.CreateDirectory(targetDir)
    Catch ex As Exception
        Throw New Exception(ex.Message)
    End Try

    System.IO.File.Copy(tmpPDFName, targetDir & "123.pdf")
    Application.DoEvents()
    System.IO.File.Delete(tmpPDFName)

End Sub


''' <summary>
''' Using "Microsoft Print To PDF" Printer to print to PDF
''' </summary>
''' <remarks></remarks>
Public Overloads Sub PrintDocumentToPDF()

    Dim tempUserDir As String : tempUserDir = String.Empty
    tempUserDir = My.Computer.FileSystem.SpecialDirectories.CurrentUserApplicationData & "\Temp"

    If Not System.IO.Directory.Exists(tempUserDir) Then
        System.IO.Directory.CreateDirectory(tempUserDir)
    End If

    tmpPDFName = tempUserDir & "\123.pdf"

    If System.IO.File.Exists(tmpPDFName) Then System.IO.File.Delete(tmpPDFName)

    printPDF = New Printing.PrintDocument
    printPDF.DocumentName = "Test"
    printPDF.PrintController = New Printing.StandardPrintController()
    ' CLSDomePrinting performing the printing (no error there, so I ignore this class)
    AddHandler printPDF.PrintPage, AddressOf CLSDoSomePrinting
    ' When finished Printing, the temporary file shall be copied to its final place 
    ' The only problem is: There is no really guarentee, it works
    ' Sometimes PDF is created as expected, but sometimes PDF has a size of 0 Bytes and is empty...
    ' Is there a proofed way to print to pdf using "Microsoft Print to PDF" ?
    AddHandler printPDF.EndPrint, AddressOf finishPrintingPDF

    Dim prnSettings As New Printing.PrinterSettings
    With prnSettings
        .Copies = 1
        .PrinterName = "Microsoft Print To PDF"
        .PrintFileName = tmpPDFName
        .PrintToFile = True
    End With

    printPDF.PrinterSettings = prnSettings
    ' So far, so good
    printPDF.Print()

End Sub

所以,这就是我的方法。我看不出原因,为什么我的代码段不起作用。大多数情况下,它会导致文件的字节数为0。

我正在Windows 10环境中的虚拟机(Hyper V)上工作。

先谢谢您 斯蒂芬

0 个答案:

没有答案