Convert HTML to PDF file in WPF
3 Jul 20242 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.
In project configuration window, name your project and select Create.
Step 2: Install the Syncfusion.HtmlToPdfConverter.WPF NuGet package as a reference to your WPF application NuGet.org.
NOTE
Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, you also have to add “Syncfusion.Licensing” assembly reference and include a license key in your projects. Please refer to this link to know about registering Syncfusion license key in your application to use our components.
Step 3: Include the following namespaces in the MainWindow.xaml.cs file.
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.
<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"/>
</Grid>
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.
//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("https://www.syncfusion.com");
//Create file stream.
FileStream stream = new FileStream("HTML-to-PDF.pdf", FileMode.CreateNew);
//Save the document into stream.
document.Save(stream);
//If the position is not set to '0' then the PDF will be empty.
stream.Position = 0;
//Close the document.
document.Close();
stream.Dispose();
By executing the program, you will get the PDF document as follows.
A complete working sample can be downloaded from Github.
Click here to explore the rich set of Syncfusion HTML to PDF converter library features.
An online sample link to convert HTML to PDF document in ASP.NET Core.