Skip to footer content
PDF TOOLS

How to Convert HTML to PDF in C++

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

WKHTMLTOPDF 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 an HTML to PDF file converter in C++, ensure the following prerequisites are fulfilled:

  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 where you want to save it. 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 the menu bar and select "Build options". Make sure you select "Debug".
  2. In the "Build options" dialog box, select the "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 the menu bar and select "Build options". Make sure you select "Debug".
  2. In the "Build options" dialog box, select the "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 the 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>
C++

Step 2: Initializing the Converter

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

// Initialize the wkhtmltopdf library
wkhtmltopdf_init(false);

// Create global settings object
wkhtmltopdf_global_settings* gs = wkhtmltopdf_create_global_settings();

// Create object settings object
wkhtmltopdf_object_settings* os = wkhtmltopdf_create_object_settings();

// Create the PDF converter with global settings
wkhtmltopdf_converter* converter = wkhtmltopdf_create_converter(gs);
// Initialize the wkhtmltopdf library
wkhtmltopdf_init(false);

// Create global settings object
wkhtmltopdf_global_settings* gs = wkhtmltopdf_create_global_settings();

// Create object settings object
wkhtmltopdf_object_settings* os = wkhtmltopdf_create_object_settings();

// Create the PDF converter with global settings
wkhtmltopdf_converter* converter = wkhtmltopdf_create_converter(gs);
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.

std::string htmlString = "<html><body><h1>Hello, World!</h1></body></html>";

// Add the HTML content to the converter
wkhtmltopdf_add_object(converter, os, htmlString.c_str());
std::string htmlString = "<html><body><h1>Hello, World!</h1></body></html>";

// Add the HTML content to the converter
wkhtmltopdf_add_object(converter, os, htmlString.c_str());
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:

// Perform the actual conversion
if (!wkhtmltopdf_convert(converter)) {
    std::cerr << "Conversion failed!" << std::endl;
}
// Perform the actual conversion
if (!wkhtmltopdf_convert(converter)) {
    std::cerr << "Conversion failed!" << std::endl;
}
C++

Step 5: Getting Output as Memory Buffer

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

// Retrieve the PDF data in memory buffer
const unsigned char* pdfData;
int pdfLength = wkhtmltopdf_get_output(converter, &pdfData);
// Retrieve the PDF data in memory buffer
const unsigned char* pdfData;
int pdfLength = wkhtmltopdf_get_output(converter, &pdfData);
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 an output file stream, open the file in binary mode and write the pdfData to it. Finally, close the file:

const char* outputPath = "file.pdf";
std::ofstream outputFile(outputPath, std::ios::binary);

// Write the PDF data to the file
outputFile.write(reinterpret_cast<const char*>(pdfData), pdfLength);
outputFile.close();
const char* outputPath = "file.pdf";
std::ofstream outputFile(outputPath, std::ios::binary);

// Write the PDF data to the file
outputFile.write(reinterpret_cast<const char*>(pdfData), pdfLength);
outputFile.close();
C++

Step 7: Cleaning Up

After converting HTML to PDF, it's essential to clean up the resources allocated by wkhtmltopdf:

// Clean up the converter and settings
wkhtmltopdf_destroy_converter(converter);
wkhtmltopdf_destroy_object_settings(os);
wkhtmltopdf_destroy_global_settings(gs);

// Deinitialize the wkhtmltopdf library
wkhtmltopdf_deinit();

std::cout << "PDF saved successfully." << std::endl;
// Clean up the converter and settings
wkhtmltopdf_destroy_converter(converter);
wkhtmltopdf_destroy_object_settings(os);
wkhtmltopdf_destroy_global_settings(gs);

// Deinitialize the wkhtmltopdf library
wkhtmltopdf_deinit();

std::cout << "PDF saved successfully." << std::endl;
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 HTML-to-PDF Conversion Library is a robust .NET and .NET Core C# library that allows developers to generate PDF documents from HTML content effortlessly. It provides a straightforward and intuitive API that simplifies the process of converting HTML web pages 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 converters 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 an 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 an 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 an HTML string using C#
Private pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")

' Export to a file or Stream
pdf.SaveAs("output.pdf")
$vbLabelText   $csharpLabel

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 HTML to PDF Code Examples.

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 of IronPDF's Full Functionality for commercial use to test out its complete functionality. You can download the software from Download IronPDF.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.
Talk to an Expert Five Star Trust Score Rating

Ready to Get Started?

Nuget Passed