简体   繁体   中英

Trying to save a pdf file of a screenshot of the form, given a specified location from the user's input

I am trying to save a created, PDF file to a location specified by the user. I'm using Visual Studio Community 2019. Essentially, I am taking a screenshot of this form:

在此处输入图片说明

And by using the PdfSharp external library, I create a PDF file and then save that PDF to some file location specified by the user. Here is the UI for the user to select their preferred file location:

在此处输入图片说明

The issue arises once the program tries to save the PDF file to the location given by the user. Here is the error I get from Visual Studio:

System.NotSupportedException: 'No data is available for encoding 1252. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.'

I looked online for this specific error, but I don't really understand it nor what to do with it, it's very confusing. I'm still a bit of beginner when it comes to working with Visual Basic. Here's the code that tries to do it:

    Dim fileLocation As String

    fileLocation = folderBrowseBox.Text

    GetFormImage(True).Save(fileLocation & "\" & RemoveWhitespace(filename) & "_" & RemoveWhitespace(collectionPeriod) & ".jpg", ImageFormat.Jpeg)

    ' Create new pdf document and page
    Dim doc As New PdfDocument()
    Dim oPage As New PdfPage()

    ' Add the page to the pdf document and add the captured image to it
    doc.Pages.Add(oPage)
    Dim img As XImage = XImage.FromFile(fileLocation & "\" & RemoveWhitespace(filename) & "_" & RemoveWhitespace(collectionPeriod) & ".jpg")

    'Create XImage object from file.
    Using xImg = PdfSharp.Drawing.XImage.FromFile(fileLocation & "\" & RemoveWhitespace(filename) & "_" & RemoveWhitespace(collectionPeriod) & ".jpg")
        'Resize page Width and Height to fit image size.
        oPage.Width = xImg.PixelWidth * 72 / xImg.HorizontalResolution
        oPage.Height = xImg.PixelHeight * 72 / xImg.HorizontalResolution

        'Draw current image file to page.
        Dim xgr = PdfSharp.Drawing.XGraphics.FromPdfPage(oPage)
        xgr.DrawImage(xImg, 0, 0, oPage.Width, oPage.Height)
    End Using

    doc.Save(fileLocation & "\" & RemoveWhitespace(filename) & "_" & RemoveWhitespace(collectionPeriod))

    img.Dispose()

The second to last line of code (" doc.Save(fileLocation & ...) ") is where the error occurs. The folderBrowseBox.Text (very first line of code) comes from the textbox you see from my second screenshot. Any help/advice will be greatly appreciated!

Try adding this line before writing the PDF file

System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance)

Got the idea from here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM