-2

Please can someone provide me with a simple example of converting a file from HTML to PDF in VB? I can find Java and C# examples but nothing using VB.

Tu deschizi eu inchid
  • 4,117
  • 3
  • 13
  • 24
  • 2
    Unless the C# is doing something interesting, it should translate directly to VB. I'd suggest that you try translating a C# example and update your question with any details that cause problems. – Craig Sep 21 '22 at 16:32

1 Answers1

0

The following shows how to use NuGet packages iText7 and itext7.pdfhtml to convert HTML to a PDF file.

VS 2022:

  • Open Visual Studio 2022
  • Click enter image description here
  • Click File
  • Select New
  • Select Project
  • For filter, select: enter image description here
  • enter image description here
  • Click Next
  • Enter desired project name (ex: ConvertHtmlToPdfTest)
  • Select desired .NET Framework (ex: .NET Framework 4.8)
  • Click Create

Open Toolbox:

  • In VS menu, click View
  • Select Toolbox

Open Solution Explorer:

  • In VS menu, click View
  • Select Solution Explorer

Open Properties Window

  • In VS menu, click View
  • Select Properties Window

Set Default package management format (optional)

  • In VS menu, click Tools
  • Select Options...
  • Expand NuGet Package Manager
  • Select General
  • Under "Package Management", set Default package management format to PackageReference
  • Click OK

Download/install NuGet package (iText7):

  • In Solution Explorer, right-click <project name> (ex: ConvertHtmlToPdfTest)
  • Select Manage NuGet Packages...
  • Click Browse tab
  • In the search box type: iText7
  • Select iText7
  • Select desired version (ex: 7.2.3)
  • Click Install
  • If a MessageBox appears, click OK

Download/install NuGet package (iText7.pdfhtml):

  • In Solution Explorer, right-click <project name> (ex: ConvertHtmlToPdfTest)
  • Select Manage NuGet Packages...
  • Click Browse tab
  • In the search box type: iText7.pdfhtml
  • Select iText7.pdfhtml
  • Select desired version (ex: 4.0.3)
  • Click Install
  • If a MessageBox appears, click OK

Add a module: (name: HelperiText7.vb)

  • In VS menu, click Project
  • Select Add New Item...
  • Select Module (name: HelperiText7.vb)
  • Click Add

HelperiText7.vb:

Imports System.IO
Imports iText.Html2pdf

Module HelperiText7
    Public Sub CreatePdf(htmlFilename As String, pdfFilename As String, Optional baseUri As String = Nothing)
        Dim pdfData As Byte() = Nothing

        If Not File.Exists(htmlFilename) Then
            Throw New Exception($"Error: '{htmlFilename}' doesn't exist.")
        End If

        Using fs As FileStream = New FileStream(htmlFilename, FileMode.Open, FileAccess.Read)
            Using ms As MemoryStream = New MemoryStream()
                'when specifying HTML as a string And the HTML includes
                'a resource that uses relative paths,
                'it's necessary to specify the baseUri (path)

                'create new instance
                Dim properties As ConverterProperties = New ConverterProperties()

                If Not String.IsNullOrEmpty(baseUri) Then
                    'set value
                    properties.SetBaseUri(baseUri)
                Else
                    'get folder name that HTML file exists in
                    Dim folderName As String = Path.GetDirectoryName(htmlFilename)

                    'set value
                    properties.SetBaseUri(folderName)
                End If

                'Debug.WriteLine($"BaseURI: {properties.GetBaseUri()}")

                'convert HTML to PDF
                HtmlConverter.ConvertToPdf(fs, ms, properties)

                'save to Byte()
                pdfData = ms.ToArray()
            End Using

            'save to PDF file
            File.WriteAllBytes(pdfFilename, pdfData)
        End Using
    End Sub

    Public Sub CreatePdfFromHtmlString(htmlString As String, pdfFilename As String, baseUri As String)
        Dim pdfData As Byte() = Nothing

        Using ms As MemoryStream = New MemoryStream()
            'when specifying HTML as a string And the HTML includes
            'a resource that uses relative paths,
            'it's necessary to specify the baseUri (path)

            'create new instance
            Dim properties As ConverterProperties = New ConverterProperties()

            'set value
            properties.SetBaseUri(baseUri)

            'convert HTML to PDF
            HtmlConverter.ConvertToPdf(htmlString, ms, properties)

            'save to Byte()
            pdfData = ms.ToArray()
        End Using

        'save to PDF file
        File.WriteAllBytes(pdfFilename, pdfData)
    End Sub
End Module

For testing, I used the following:

test.html

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <h2>HTML Test</h2>

    <div>
        <IMG src="./images/strawberry.jpg" ALT="strawberry">
    </div>

    <p>
        <div>
            This is a test message
        </div>
</body>
</html>

Note: In the HTML above, the image uses a relative path.

File/Folder structure:

FileAndFolderStructure

images\strawberry.jpg: strawberry.jpg


The following demonstrates converting test.html to a PDF file.

Using ofd As OpenFileDialog = New OpenFileDialog()
    ofd.Filter = "HTML File (*.html)|*.html"
    ofd.Title = "Select HTML Filename"

    If ofd.ShowDialog() = DialogResult.OK Then
        Using sfd As SaveFileDialog = New SaveFileDialog()
            sfd.Filter = "PDF File (*.pdf)|*.pdf"
            sfd.Title = "Select PDF Filename To Save As"
            If sfd.ShowDialog() = DialogResult.OK Then
                'the image in the HTML uses a relative path
                'set baseUri = to the folder that contains the HTML file
                Dim baseUri As String = Path.GetDirectoryName(ofd.FileName)
                Debug.WriteLine($"baseUri: {baseUri}")

                'convert HTML to PDF
                HelperiText7.CreatePdf(ofd.FileName, sfd.FileName, baseUri)
            End If
        End Using
    End If
End Using

Resources:

Additional Resources:

Tu deschizi eu inchid
  • 4,117
  • 3
  • 13
  • 24