Convert HTML to PDF file in WPF

13 Jan 20232 minutes to read

The Syncfusion HTML to PDF converter is a .NET library used to convert HTML or web pages to PDF document in WPF application.

Steps to convert Html to PDF document in WPF

Step 1: Create a new WPF application project.
Convert HTMLToPDF WPF Step1
In project configuration window, name your project and select Create.
Convert HTMLToPDF WPF Step2

Step 2: Install the Syncfusion.HtmlToPdfConverter.WPF NuGet package as a reference to your WPF application
Convert HTMLToPDF WPF Step3

Step 3: Include the following namespaces in the MainWindow.xaml.cs file.

  • C#
  • using System;
    using System.IO;
    using System.Windows;
    using Syncfusion.Pdf;
    using Syncfusion.HtmlConverter;

    Step 4: Add a new button in MainWindow.xaml to convert HTML to PDF document as follows.

  • C#
  • <Grid HorizontalAlignment="Left" Margin="0,0,0,-0.333" Width="793">
    <Button Content="Convert Html to PDF" HorizontalAlignment="Left" Margin="318,210,0,0" VerticalAlignment="Top" Width="166" Click=" btnCreate_Click " Height="19"/>
    <TextBlock HorizontalAlignment="Left" Margin="222,177,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Height="17"/>
    <TextBlock HorizontalAlignment="Left" Margin="291,175,0,0" TextWrapping="Wrap" Text="Click the button to convert Html to PDF." VerticalAlignment="Top"/>

    Step 5: Add the following code in btnCreate_Click to convert HTML to PDF document using Convert method in HtmlToPdfConverter class. The HTML content will be scaled based on the given ViewPortSize property of BlinkConverterSettings class.

  • C#
  • //Initialize HTML to PDF converter.
    HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter();
    BlinkConverterSettings blinkConverterSettings = new BlinkConverterSettings();
    //Set Blink viewport size.
    blinkConverterSettings.ViewPortSize = new System.Drawing.Size(1280, 0);
    //Assign Blink converter settings to HTML converter.
    htmlConverter.ConverterSettings = blinkConverterSettings;
    //Convert URL to PDF document.
    PdfDocument document = htmlConverter.Convert("");
    //Create file stream.
    FileStream stream = new FileStream("HTML-to-PDF.pdf", FileMode.CreateNew);
    //Save the document into stream.
    //If the position is not set to '0' then the PDF will be empty.
    stream.Position = 0;
    //Close the document.

    By executing the program, you will get the PDF document as follows.
    Convert HTMLToPDF WPF output

    A complete working sample can be downloaded from Github.