Convert HTML file to PDF and XPS in C#

HTML file is widely used to collect data and for the security reason, we need to convert it to printable documents in PDF and XPS formats. You can easily convert HTML page in URL to PDF in high quality by using Spire.PDF. This article will focus on demonstrate how to convert HTML files into the printable document, both in PDF and XPS by the help of Spire.Doc.

First, check the html file that will be converted to PDF and XPS.

Convert HTML file to PDF and XPS

Secondly, download Spire.Doc and install on your system. The Spire.Doc installation is clean, professional and wrapped up in a MSI installer.

Then adds Spire.Doc.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Doc\Bin\NET4.0\ Spire.Doc.dll".

Now it comes to the steps of how to convert HTML into PDF and XPS.

Step 1: Load a HTML file from the file.

Document document = new Document();
document.LoadFromFile("Good.htm", FileFormat.Html, XHTMLValidationType.None) ;

Step 2: Save HTML to the file format in PDF and XPS.

//Save html to PDF.
document.SaveToFile("Sample.pdf", FileFormat.PDF);

//Save html to XPS.
document.SaveToFile("Sample.xps", FileFormat.XPS);

After debugging, please check the following PDF and XPS file as the result.

Convert HTML file to PDF and XPS

Convert HTML file to PDF and XPS

Full codes:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace HTML2PDFXPS
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            Document document = new Document();
            document.LoadFromFile("Good.htm", FileFormat.Html, XHTMLValidationType.None);

            //Save html to PDF.
            document.SaveToFile("Sample.pdf", FileFormat.PDF);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Document document = new Document();
            document.LoadFromFile("Good.htm", FileFormat.Html, XHTMLValidationType.None);

            //Save html to PDF.
            document.SaveToFile("Sample.xps", FileFormat.XPS);
         }
    }
}