Использование Microsoft Print To PDF в VB.NET, в результате чего 0 КБ «PDF» - PullRequest
0 голосов
/ 21 марта 2019

У меня возникают проблемы при печати в 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 байтами.

Я работаю на виртуальной машине (Hyper V) в среде Windows 10.

Заранее спасибо, Стефан

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...