Convert HTML to PDF file in Linux
6 Dec 20243 minutes to read
The Syncfusion® HTML to PDF converter is a .NET library that converts HTML or web pages to PDF document in Linux.
Pre-requisites
The following Linux dependencies should be installed where the conversion takes place.
$ sudo apt-get update
$ sudo apt-get install libasound2 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 libnss3 libgbm1
Steps to convert HTML to PDF in .NET Core application on Linux
Step 1: Execute the following command in the Linux terminal to create a new .NET Core Console application.
dotnet new console
Step 2: Install the Syncfusion.HtmlToPdfConverter.Net.Linux NuGet package as a reference to your project from NuGet.org by executing the following command.
dotnet add package Syncfusion.HtmlToPdfConverter.Net.Linux -v xx.x.x.xx -s https://www.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.
using Syncfusion.HtmlConverter;
using Syncfusion.Pdf;
using System.IO;
Step 4: Add code samples in Program.cs file to convert HTML to PDF document using Convert method in HtmlToPdfConverter class.
//Initialize HTML to PDF converter.
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter();
BlinkConverterSettings settings = new BlinkConverterSettings();
//Set command line arguments to run without the sandbox.
settings.CommandLineArguments.Add("--no-sandbox");
settings.CommandLineArguments.Add("--disable-setuid-sandbox");
//Assign Blink settings to the HTML converter.
htmlConverter.ConverterSettings = settings;
//Convert URL to PDF document.
PdfDocument document = htmlConverter.Convert("https://www.syncfusion.com");
FileStream fileStream = new FileStream("HTML-to-PDF.pdf", FileMode.CreateNew, FileAccess.ReadWrite);
//Save and close a PDF document.
document.Save(fileStream);
document.Close(true);
Step 5: Execute the following command to restore the NuGet packages.
dotnet restore
Step 6: Execute the following command in the terminal to run the application.
dotnet run
By executing the program, you will get the PDF document as follows. The output will be saved in parallel to the program.cs file.
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.