How to Convert HTML to PDF in C++

The ability to convert HTML files or content to PDF pages format is a valuable feature in many applications. In C++, it is quite a tedious task to build an application from scratch, to generate HTML to PDF format files. So in this article, we will explore how to convert HTML to PDF in C++ using the wkhtmltopdf library.

WKTOPdf Library

wkhtmltopdf is an open-source command-line tool that seamlessly transforms HTML plain text pages into high-quality PDF documents. By leveraging its functionalities in C++ programs, we can easily convert HTML string content to PDF format. Let's dig into the step-by-step process of HTML page to PDF conversion in C++ using the wkhtmltopdf library.

Prerequisites

To create HTML to PDF files converter in C++, we need to check the following things are in place:

  1. A C++ compiler such as GCC or Clang installed on your system.

  2. wkhtmltopdf library installed. You can download the latest version from the official wkhtmltopdf website and install it according to your operating system's instructions.

  3. Basic knowledge of C++ programming.

Create a C++ HtmltoPdf project in Code:Blocks

To create a C++ PDF conversion project in Code::Blocks, follow these steps:

  1. Open the Code::Blocks IDE.

  2. Go to the "File" menu and select "New" and then "Project" to open the New Project wizard.

  3. In the New Project wizard, select "Console Application".

  4. Select C++ Language.

  5. Set Project Title and Location on which you want to save. Click "Next" to proceed.

  6. Select the appropriate C++ compiler and build target, such as Debug or Release. Click "Finish" to create the project.

Setting up Search Directories

To ensure that Code::Blocks can find the necessary header files, we need to set up the search directories.

  1. Click the "Project" menu in menu bar and select "Build options". Make sure you select "Debug".

  2. In "Build options" dialog-box, select "Search directories" tab.

  3. Under the "Compiler" tab, click on the "Add" button.

  4. Browse to the directory where the wkhtmltox header files are located (e.g., C:\Program Files\wkhtmltopdf\include), and select it.

  5. Finally, click "OK" to close the dialog-box.

How to Convert HTML to PDF in C++: Figure 1 - Search Directories

Linking the Libraries

To link against the wkhtmltox library, follow these steps:

  1. Again Click the "Project" menu in menu bar and select "Build options". Make sure you select "Debug".

  2. In "Build options" dialog-box, select "Linker settings" tab.

  3. Under the "Link libraries" tab, click the "Add" button.

  4. Browse to the directory where the wkhtmltox library files are located (e.g., C:\Program Files\wkhtmltopdf\lib), and select the appropriate library file.

  5. Click "Open" to add the library to your project.

  6. Finally, click "OK" to close the dialog-box.

How to Convert HTML to PDF in C++: Figure 2 - Linking libraries

Steps to Easily Convert HTML to PDF in C++

Step 1 Including the Library to Convert HTML Files

To get started, include the necessary header files to utilize the functionalities of the wkhtmltopdf library in your C++ program. Include the following header files at the beginning of main.cpp source code file as shown in the following example:


    #include <iostream>
    #include <fstream>
    #include <string>
    #include <wkhtmltox/pdf.h>

    #include <iostream>
    #include <fstream>
    #include <string>
    #include <wkhtmltox/pdf.h>
#include <iostream>
	#include <fstream>
	#include <string>
	#include <wkhtmltox/pdf.h>
VB   C#

Step 2 Initializing the Converter

To convert HTML to PDF, we need to initialize the wkhtmltopdf converter. The code goes as follows:


    wkhtmltopdf_init(false);

    wkhtmltopdf_global_settings* gs = wkhtmltopdf_create_global_settings();
    wkhtmltopdf_object_settings* os = wkhtmltopdf_create_object_settings();
    wkhtmltopdf_converter* converter = wkhtmltopdf_create_converter(gs);

    wkhtmltopdf_init(false);

    wkhtmltopdf_global_settings* gs = wkhtmltopdf_create_global_settings();
    wkhtmltopdf_object_settings* os = wkhtmltopdf_create_object_settings();
    wkhtmltopdf_converter* converter = wkhtmltopdf_create_converter(gs);
wkhtmltopdf_init(False)

	wkhtmltopdf_global_settings* gs = wkhtmltopdf_create_global_settings()
	wkhtmltopdf_object_settings* os = wkhtmltopdf_create_object_settings()
	wkhtmltopdf_converter* converter = wkhtmltopdf_create_converter(gs)
VB   C#

Step 3 Setting HTML Content

Now, let's provide the HTML content that needs to be converted to a PDF. You can either load an HTML file or provide the string directly.


    string htmlString = "<html><body><h1>Hello, World!</h1></body></html>";   wkhtmltopdf_add_object(converter, os, htmlString.c_str());

    string htmlString = "<html><body><h1>Hello, World!</h1></body></html>";   wkhtmltopdf_add_object(converter, os, htmlString.c_str());
Dim htmlString As String = "<html><body><h1>Hello, World!</h1></body></html>"
wkhtmltopdf_add_object(converter, os, htmlString.c_str())
VB   C#

Step 4 Converting HTML to PDF

With the converter and HTML content ready, we can proceed to convert the HTML to a PDF file. Use the following code snippet:


    wkhtmltopdf_convert(converter);

    wkhtmltopdf_convert(converter);
wkhtmltopdf_convert(converter)
VB   C#

Step 5 Getting output as Memory Buffer

With wkhtmltopdf_get_output function, we can get the existing PDF data as memory buffer stream. It also returns the length of the PDF. Following example will perform this task:


    const unsigned char* pdfData;
    const int pdfLength = wkhtmltopdf_get_output(converter, &pdfData);

    const unsigned char* pdfData;
    const int pdfLength = wkhtmltopdf_get_output(converter, &pdfData);
const unsigned Char* pdfData
	Const pdfLength As Integer = wkhtmltopdf_get_output(converter, &pdfData)
VB   C#

Step 6 Saving the PDF File

Once the conversion is complete, we need to save the generated PDF file to disk. Specify the file path where you want to save the PDF. Then using output file stream, open the file in binary mode and write the pdfData to it. Finally, close the file. Here's a code example:


    const char* outputPath = "file.pdf";
    ofstream outputFile(outputPath, ios::binary);
    outputFile.write(reinterpret_cast<const char*>(pdfData), pdfLength);
    outputFile.close();

    const char* outputPath = "file.pdf";
    ofstream outputFile(outputPath, ios::binary);
    outputFile.write(reinterpret_cast<const char*>(pdfData), pdfLength);
    outputFile.close();
const Char* outputPath = "file.pdf"
	ofstream outputFile(outputPath, ios:=:=binary)
	outputFile.write(reinterpret_cast<const Char*>(pdfData), pdfLength)
	outputFile.close()
VB   C#

Step 7 Cleaning Up

After converting HTML to PDF, it's essential to clean up the resources allocated by wkhtmltopdf. Use the following code snippet:


    wkhtmltopdf_destroy_converter(converter);
    wkhtmltopdf_destroy_object_settings(os);
    wkhtmltopdf_destroy_global_settings(gs);
    wkhtmltopdf_deinit();

    cout << "PDF saved successfully." << endl;

    wkhtmltopdf_destroy_converter(converter);
    wkhtmltopdf_destroy_object_settings(os);
    wkhtmltopdf_destroy_global_settings(gs);
    wkhtmltopdf_deinit();

    cout << "PDF saved successfully." << endl;
wkhtmltopdf_destroy_converter(converter)
	wkhtmltopdf_destroy_object_settings(os)
	wkhtmltopdf_destroy_global_settings(gs)
	wkhtmltopdf_deinit()

	cout << "PDF saved successfully." << endl
VB   C#

Step 8 Execute the Code and Generate PDF file

Now, build the project and execute the code using F9. The output is generated and saved in the project folder. The resulting PDF is as follows:

How to Convert HTML to PDF in C++: Figure 3 - PDF Output

HTML File to PDF File in C#

IronPDF

IronPDF is a robust .NET and .NET Core C# library that allows developers to generate PDF document from HTML content effortlessly. It provides a straightforward and intuitive API that simplifies the process of converting HTML web page to PDF, making it a popular choice for various applications and use cases.

One of the key advantages of IronPDF is its versatility. It supports not only the conversion of simple HTML documents but also complex web pages with CSS styling, JavaScript interactions, and even dynamic content. Moreover, you can develop different PDF converter with quick access to its conversion methods.

Here's the code example to convert HTML string to PDF using IronPDF in C#:


    using IronPdf;

    // Instantiate Renderer
    var renderer = new ChromePdfRenderer();

    // Create PDF content from a HTML string using C#
    var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");

    // Export to a file or Stream
    pdf.SaveAs("output.pdf");

    using IronPdf;

    // Instantiate Renderer
    var renderer = new ChromePdfRenderer();

    // Create PDF content from a HTML string using C#
    var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");

    // Export to a file or Stream
    pdf.SaveAs("output.pdf");
Imports IronPdf

	' Instantiate Renderer
	Private renderer = New ChromePdfRenderer()

	' Create PDF content from a HTML string using C#
	Private pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")

	' Export to a file or Stream
	pdf.SaveAs("output.pdf")
VB   C#

The PDF output:

How to Convert HTML to PDF in C++: Figure 4 - IronPDF Output

For more details on how to convert different HTML files, Web page URLs, and Images to PDF, please visit this code example page.

With IronPDF, generating PDF files from HTML content becomes a straightforward task in .NET Framework languages. Its intuitive API and extensive feature set make it a valuable tool for developers needing to convert HTML to PDF in their C# projects. Whether it's generating reports, invoices, or any other document that requires precise HTML-to-PDF conversion, IronPDF is a reliable and efficient solution.

IronPDF is free for development purposes but for commercial-use it needs to be licensed. It also provides a free trial for commercial use to test out its complete functionality. You can download the software from here.