C++ Convert HTML to PDF, PDF/A, XPS, and Images

HTML is a common authoring format for reports, contracts, and notice templates, and it is convenient to generate, preview, and modify in a browser. A browser interprets HTML and CSS according to its own rules, so the same file may produce different pagination and line spacing on different devices and with different fonts. When a document is to be archived, printed, or distributed across devices, HTML usually has to be converted to a fixed-layout file. After conversion, the page size, pagination, and font embedding are fixed at conversion time, and later viewing no longer depends on the browser environment.

Spire.Doc for C++ loads HTML as a document object through Document->LoadFromFile(), writes fixed-layout files with Document->SaveToFile() using FileFormat::PDF or FileFormat::XPS, renders pages to image bytes through Document->SaveImageToStreams(), and sets the PDF conformance level through ToPdfParameterList. All processing takes place in the local process, and the document is never uploaded to any service.

This article covers four features:

The example uses the "Spruce Technology Q3 2026 Operating Report" (QuarterlyReport.html). The file contains five sections, two data tables, and one signature row, together with heading, callout, table, and list styles defined in a style block; the body font is Segoe UI. The rendering in a browser is shown below.

The sample HTML file rendered in a browser

Install Spire.Doc for C++

There are two ways to integrate Spire.Doc for C++ into your application. One way is to install it through NuGet; the other is to download the package from our website and copy the libraries into your program. Installing through NuGet is simpler and is the recommended approach.

  • In Visual Studio, open the NuGet Package Manager, search for Spire.Doc.Cpp, and install it.
  • Alternatively, run nuget install Spire.Doc.Cpp in the project directory, and then add the package's include and lib folders to the project.

An integrated project needs to reference the corresponding import library and to ensure that dependency files such as SpireDocCpp.dll and Spire.Doc.Base.dll are present in the run directory. For detailed configuration instructions, refer to How to Integrate Spire.Doc for C++ in a C++ Application.

Convert HTML to PDF

The second parameter of Document->LoadFromFile() specifies the input format, and the third specifies the XHTML validation level. After loading, the headings, paragraphs, tables, and inline styles in the HTML are parsed into document objects, and page layout is determined by the page setup of the document sections. Calling Document->SaveToFile(..., FileFormat::PDF) writes a PDF with the current layout.

Parameter Meaning
fileName Path to the HTML file
fileFormat Input format, FileFormat::Html here
validationType XHTML validation level, which sets the strength of validation during loading

The detailed steps are as follows.

  • Create a Document object.
  • Call Document->LoadFromFile() to load the HTML file with FileFormat::Html and XHTMLValidationType::None.
  • Call Document->SaveToFile() to save the document as FileFormat::PDF.
  • Call Document->GetPageCount() to obtain the number of pages after conversion.
  • Call Document->Close() to release the document.

The code for converting HTML to PDF is shown below.

#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/XHTMLValidationType.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;

int main() {

    //Specify the input file path
    string inputFile = "Data/QuarterlyReport.html";

    //Specify the output directory and file name
    string outputPath = "Output/";
    string outputFile = outputPath + "QuarterlyReport.pdf";

    //Create a Document object
    intrusive_ptr<Document> document = new Document();

    //Load the file as HTML without validating the XHTML structure
    document->LoadFromFile(inputFile, FileFormat::Html, XHTMLValidationType::None);

    //Save the document as PDF
    document->SaveToFile(outputFile, FileFormat::PDF);

    //Output the number of pages after conversion
    cout << "Pages: " << document->GetPageCount() << endl;

    document->Close();
}

With the default page setup, the sample HTML converts to 2 pages. The first page contains the title, overall performance, the key metrics table, and key project progress; the second page contains the risk table, the next-quarter plan, and the signature row. The heading, callout, and table styles are all retained:

The 2-page PDF document converted from HTML

Parsing HTML and the validation level

XHTMLValidationType has three values, which control the strength of conformance validation when HTML is loaded.

Value Meaning
None Does not validate the XHTML structure and parses in a fault-tolerant way
Transitional Validates against the Transitional XHTML specification
Strict Validates against the Strict XHTML specification

For HTML generated by web editors or template systems, tag closure and attribute syntax do not always conform to the XHTML specification, so None is normally used. The validation level affects only the loading stage: once validation passes, the document objects produced by all three values go through the same layout and save process. The sample file contains an HTML5 meta charset declaration and loads correctly with None.

Set page size and margins before saving

An HTML file does not define paper. After loading, the default page of a document section is A4 (595.35 × 841.95 points), and the top, bottom, left, and right margins are all 72 points (2.54 cm). Even if the HTML declares a margin in @page, the margins of the output page do not change accordingly. To adjust the layout, set PageSetup before the first save or render:

//In addition to the headers above, include Section.h, PageSetup.h, SectionCollection.h, PageSize.h, and MarginsF.h
intrusive_ptr<Section> section = document->GetSections()->GetItem(0);
section->GetPageSetup()->SetPageSize(PageSize::Letter());
section->GetPageSetup()->GetMargins()->SetAll(54.0f);

The example changes the page to Letter (612 × 792 points) and the margins to 54 points. The page size and margins of the saved PDF change accordingly, and the body text is repaginated at the new text width. Page setup must be completed before SaveToFile() or SaveImageToStreams(); if PageSetup is modified after the document has been laid out, the layout that has already been produced does not update.

Scope of font and CSS handling

The fonts, font sizes, colors, background colors, borders, table styles, and list styles in the example are all defined by the style block and are retained after conversion. The output PDF embeds the fonts used as subsets, so the viewer does not need those fonts installed to preserve the appearance. Conversion runs in the local process; scripts in the HTML are not executed, and dynamic content produced by scripts does not appear in the output. For complex layouts such as flexible box, grid, and floated positioning, the result may differ from the browser, so pagination and line breaks should be checked before production use.

Convert HTML to PDF/A

PDF/A is a subset of PDF for long-term archiving. It requires font embedding and explicit color spaces, and restricts dependencies on external resources. To convert HTML to PDF/A, load the HTML as usual, create a ToPdfParameterList object and call SetPdfConformanceLevel() to specify the conformance level, and then save the document with the SaveToFile() overload that accepts the parameter object.

Conformance level Description
Pdf_A1B PDF/A-1b, the basic conformance level, which guarantees a consistent appearance
Pdf_A1A PDF/A-1a, which additionally requires tagged structure and Unicode mapping on top of 1b
Pdf_A2B PDF/A-2b, based on PDF 1.7, which allows JPEG 2000 compression and transparency
Pdf_A3B PDF/A-3b, which additionally allows files in other formats to be embedded on top of 2b

The detailed steps are as follows.

  • Create a Document object and load the HTML file.
  • Create a ToPdfParameterList object to hold the PDF conversion parameters.
  • Call ToPdfParameterList->SetPdfConformanceLevel() with PdfConformanceLevel::Pdf_A1B.
  • Save the document with the ToPdfParameterList overload of Document->SaveToFile().
  • Call Document->Close() to release the document.

The code for converting HTML to PDF/A is shown below.

#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/XHTMLValidationType.h"
#include "Spire/Doc/ToPdfParameterList.h"
#include "Spire/Doc/PdfConformanceLevel.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;

int main() {

    //Specify the input file path
    string inputFile = "Data/QuarterlyReport.html";

    //Specify the output directory and file name
    string outputPath = "Output/";
    string outputFile = outputPath + "QuarterlyReport_PDFA.pdf";

    //Create a Document object and load the HTML
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile(inputFile, FileFormat::Html, XHTMLValidationType::None);

    //Create the PDF conversion parameter object
    intrusive_ptr<ToPdfParameterList> parameters = new ToPdfParameterList();

    //Set the PDF conformance level to PDF/A-1b
    parameters->SetPdfConformanceLevel(PdfConformanceLevel::Pdf_A1B);

    //Save the document with the overload that accepts the parameters
    document->SaveToFile(outputFile, parameters);

    document->Close();

    cout << "Saved: " << outputFile << endl;
}

The output file has the same page content as an ordinary PDF; the differences lie in the PDF version and the metadata. Reading the properties and XMP metadata of the generated file gives the following results:

Item Result
PDF version 1.4
pdfaid:part 1
pdfaid:conformance B
Pages 2
Fonts Embedded as subsets

The declaration in the XMP metadata is as follows.

<rdf:Description rdf:about="" xmlns:pdfaid="http://www.aiim.org/pdfa/ns/id/">
  <pdfaid:part>1</pdfaid:part>
  <pdfaid:conformance>B</pdfaid:conformance>
</rdf:Description>

Content requirements of PDF/A

PDF/A requires a document to remain fully presentable after leaving its original environment, so fonts must be embedded, color spaces must be explicit, and page content must not depend on external files. Features such as encryption, scripts, audio, and video are restricted at the archival levels and are usually not retained after conversion to PDF/A. The sample HTML contains only text, tables, and rules; after conversion, all content is written into the PDF with embedded fonts, which satisfies the basic requirements of PDF/A-1b.

Choosing a conformance level

Pdf_A1B is the most common choice. It has broad compatibility and suits archiving scenarios such as contracts, reports, and invoices where visual consistency is the goal. When a tagged structure is required for screen readers, choose Pdf_A1A. Pdf_A2B and Pdf_A3B are based on newer PDF versions; the former suits documents with transparency or JPEG 2000 images, and the latter suits scenarios that require the source file to be attached to the PDF. The conformance level should be determined by the recipient's archiving requirements rather than always set to the highest level.

Convert HTML to XPS

XPS is a fixed-layout document format on the Windows platform, and like PDF it fixes the page layout at conversion time. To convert HTML to XPS, only the save format needs to change to FileFormat::XPS; the steps for loading HTML and setting the page size are the same as for PDF conversion.

The detailed steps are as follows.

  • Create a Document object and load the HTML file.
  • Call Document->SaveToFile() to save the document as FileFormat::XPS.
  • Call Document->Close() to release the document.

The code for converting HTML to XPS is shown below.

#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/XHTMLValidationType.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;

int main() {

    //Specify the input file path
    string inputFile = "Data/QuarterlyReport.html";

    //Specify the output directory and file name
    string outputPath = "Output/";
    string outputFile = outputPath + "QuarterlyReport.xps";

    //Create a Document object and load the HTML
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile(inputFile, FileFormat::Html, XHTMLValidationType::None);

    //Save the document as XPS
    document->SaveToFile(outputFile, FileFormat::XPS);

    document->Close();

    cout << "Saved: " << outputFile << endl;
}

The XPS output paginates the same way as the PDF version and also has 2 pages. On the second page, the pagination position, table borders, and text layout are fixed:

The second page of the XPS document converted from HTML

Fixed-layout structure of XPS

An XPS file is a package that follows the Open Packaging Conventions and consists of a fixed document sequence, fixed documents, and fixed pages. The text, rules, and images of each page are recorded in absolute coordinates, and fonts are referenced by glyph index. An XPS page therefore does not need to be laid out again when viewed, and the display matches the conversion result. This structure is close to the fixed-page model of PDF, except that XPS describes page content in XML and organizes the parts in a ZIP package.

Choosing between PDF and XPS

PDF has broader universality and suits external distribution, cross-platform viewing, and long-term archiving. XPS is closely integrated with the viewing and printing systems of Windows and suits circulation and printing within Windows environments. When the sample document is converted to PDF and XPS, the page size and pagination results are the same; the choice of format depends on the recipient's platform and working habits rather than on conversion capability.

Convert HTML to images

Image output is used to produce document previews, thumbnails, and page-by-page illustrations. Document->SaveImageToStreams() renders the specified pages to image streams, and Stream->ToArray() returns the image bytes, which can be written to a file to produce an image. The method provides three overloads for a single page, a consecutive range of pages, and all pages.

Overload Purpose
SaveImageToStreams(pageIndex, ImageType::Bitmap) Renders the specified page
SaveImageToStreams(pageIndex, pageCount, ImageType::Bitmap) Renders a consecutive range of pages starting at the specified page
SaveImageToStreams(ImageType::Bitmap) Renders all pages

The detailed steps are as follows.

  • Create a Document object and load the HTML file.
  • Call Document->SaveImageToStreams() to render the first page and obtain the image stream.
  • Call Stream->ToArray() to read the image bytes.
  • Write the bytes to a .png file in binary mode.
  • Call Stream->Dispose() and Document->Close() to release the resources.

The code for converting the first page of the HTML to a PNG image is shown below.

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/XHTMLValidationType.h"
#include "Spire/Doc/Documents/ImageType.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/common/h/Stream.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Common;

int main() {

    //Specify the input file path
    string inputFile = "Data/QuarterlyReport.html";

    //Specify the output directory and file name
    string outputPath = "Output/";
    string outputFile = outputPath + "QuarterlyReport.png";

    //Create a Document object and load the HTML
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile(inputFile, FileFormat::Html, XHTMLValidationType::None);

    //Render the first page as a bitmap; page indexes start at 0
    intrusive_ptr<Stream> imageStream = document->SaveImageToStreams(0, ImageType::Bitmap);
    vector<BYTE> imageData = imageStream->ToArray();

    //Write the image bytes to a PNG file
    ofstream out(outputFile, ios::binary);
    out.write(reinterpret_cast<const char*>(imageData.data()), imageData.size());
    out.close();

    //Release the image stream and the document
    imageStream->Dispose();
    document->Close();

    cout << "Image bytes: " << imageData.size() << endl;
}

After execution, the image of the first page is produced, with page content identical to the first page of the PDF output:

The PNG image converted from the first page of the HTML

Page index starts at 0

The first parameter of SaveImageToStreams() is the page index, which starts at 0; 0 in the example means the first page. When only one page is needed, use the single-page overload. When a consecutive range is needed, use the overload with pageCount; for example, SaveImageToStreams(0, 2, ImageType::Bitmap) returns a collection of streams containing the first two pages. When all pages are needed, use the overload that accepts only ImageType, and the number of returned streams matches GetPageCount().

PNG encoding at 96 DPI

The example writes the bytes directly to a .png file because the rendering result uses PNG encoding by default, and the bytes begin with the PNG signature 89 50 4E 47. An A4 page is rendered at 96 DPI to 794 × 1123 pixels, including the margins around the page. For other formats such as JPEG, pass the bytes to an image library for transcoding rather than changing only the file extension. For a higher resolution, save the document as PDF first and then rasterize the pages at the target DPI with a PDF rendering tool; enlarging the image directly does not add detail.

Complete page setup before rendering

Image rendering and PDF saving use the same layout result. The page size, orientation, and margins should be set before SaveImageToStreams() is called; otherwise the image uses the default A4 page setup. The HTML in the example uses the default page setup, so the text width of the image and the PDF is the same. If the page setup is changed and the document is loaded and rendered again, the pixel size of the image changes with the page size.

Feature comparison

Output Main call Typical use
PDF SaveToFile(..., FileFormat::PDF) General distribution, printing, and cross-platform viewing
PDF/A SetPdfConformanceLevel() + SaveToFile() Long-term archiving and compliance storage
XPS SaveToFile(..., FileFormat::XPS) Fixed-layout exchange in Windows environments
Images SaveImageToStreams() + Stream->ToArray() Previews, thumbnails, and page-by-page illustrations

All four outputs are based on the same HTML document object. When converting to PDF, PDF/A, and XPS, pages are laid out at save time; when converting to images, pages are laid out at render time. To keep the output consistent, complete the page setup before saving or rendering.

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.