Przejdź do treści stopki
NARZęDZIA PDF

Jak tworzyć pliki PDF w C++

Pliki PDF (Portable Document Format) są powszechnie używane do udostępniania i przechowywania dokumentów w spójnym formacie na różnych platformach. W tym artykule omówimy, jak generować pliki PDF w języku C++ przy użyciu biblioteki wkhtmltopdf. Jest to narzędzie typu open source działające w wierszu poleceń, służące do konwersji treści HTML na pliki PDF. Wykorzystując możliwości tej biblioteki, możemy programowo tworzyć dokumenty PDF na podstawie treści HTML w naszych aplikacjach C++.

Biblioteka WkhtmltoPdf

wkhtmltopdf to narzędzie wiersza poleceń typu open source oraz silnik renderujący, który konwertuje strony internetowe HTML lub treści HTML na dokumenty PDF. Wykorzystuje silnik renderujący WebKit do analizowania i renderowania HTML, CSS i JavaScript, a następnie generuje plik PDF na podstawie wyrenderowanej treści.

"Biblioteka wkhtmltopdf C++" (znana również jako "wkhtmltopdf C API"). This library provides a C++ interface to the wkhtmltopdf command-line tool, allowing you to create PDF files from HTML content directly in your C++ applications. Przyjrzyjmy się krok po kroku procesowi konwersji HTML do PDF w języku C++ przy użyciu biblioteki Wkhtmltopdf.

Wymagania wstępne

Aby tworzyć pliki PDF w języku C++, potrzebujemy następujących elementów:

  1. Kompilator C++, taki jak GCC lub Clang, zainstalowany w systemie. Możesz użyć dowolnego środowiska IDE obsługującego programowanie w języku C++.
  2. Pobrano i zainstalowano bibliotekę wkhtmltopdf. Najnowszą wersję można pobrać z oficjalnej strony internetowej wkhtmltopdf i zainstalować zgodnie z instrukcjami dla danego systemu operacyjnego.
  3. Podstawowa znajomość programowania w języku C++.

C++ Utwórz projekt PDF w Code::Blocks

Utwórz projekt w Code::Blocks, a następnie wykonaj poniższe kroki, aby połączyć folder biblioteki i plik. Jeśli korzystasz z innego środowiska IDE, opcje mogą się różnić, ale musisz odwołać się do pobranej biblioteki w swoim projekcie, aby działała.

1. Dodawanie folderu include w katalogach wyszukiwania

Aby zapewnić, że Code::Blocks może znaleźć niezbędne pliki nagłówkowe, musimy skonfigurować katalogi wyszukiwania.

  1. Kliknij menu "Projekt" na pasku menu i wybierz "Opcje kompilacji". Pamiętaj, aby wybrać opcję "Debug".
  2. W oknie dialogowym "Opcje kompilacji" wybierz zakładkę "Katalogi wyszukiwania".
  3. W zakładce "Kompilator" kliknij przycisk "Dodaj".
  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 Create PDF Files in C++: Figure 1

2. Linking the Libraries in Linker Settings

To link against the wkhtmltox library, follow these steps:

  1. Again, click the "Project" menu in the menu bar and select "Build options". Pamiętaj, aby wybrać opcję "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 Create PDF Files in C++: Figure 2

Steps to Create a PDF in C++ using Wkhtmltopdf

1. Include Necessary Libraries

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

#include <iostream>
#include <fstream>
#include <string>
#include <wkhtmltox/pdf.h> // Include wkhtmltopdf library headers
#include <iostream>
#include <fstream>
#include <string>
#include <wkhtmltox/pdf.h> // Include wkhtmltopdf library headers
C++

2. Disable the GUI Component

If you are not working with a GUI, then you need to disable it to avoid errors. Kod wygląda następująco:

wkhtmltopdf_init(false); // Initialize the wkhtmltopdf library in non-GUI mode
wkhtmltopdf_init(false); // Initialize the wkhtmltopdf library in non-GUI mode
C++

3. Initialize Settings and Converter

Next, we need to initialize global and object settings pointers, and then the wkhtmltopdf converter.

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

4. Adding PDF Content

Now, let's create an HTML string to fill some content into our newly created PDF document. Kod wygląda następująco:

std::string htmlString = "<html><body><h1>Create a PDF in C++ using WKHTMLTOPDF Library</h1></body></html>";
wkhtmltopdf_add_object(converter, os, htmlString.c_str());
std::string htmlString = "<html><body><h1>Create a PDF in C++ using WKHTMLTOPDF Library</h1></body></html>";
wkhtmltopdf_add_object(converter, os, htmlString.c_str());
C++

5. Convert HTML String to PDF File

Wkhtmltopdf provides a converter method to convert HTML content to PDF. Here's the code snippet:

wkhtmltopdf_convert(converter); // Converts HTML content to PDF
wkhtmltopdf_convert(converter); // Converts HTML content to PDF
C++

6. Getting output as Memory Buffer

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

const unsigned char* pdfData;
int pdfLength = wkhtmltopdf_get_output(converter, &pdfData); // Get PDF data and length
const unsigned char* pdfData;
int pdfLength = wkhtmltopdf_get_output(converter, &pdfData); // Get PDF data and length
C++

7. Save PDF File

The pdfData pointer will now have the stream of characters from the wkhtmltopdf_converter. To save to a PDF file, first, we will specify the file path where we want to save the PDF. Then, using the output file stream, we open the file in binary mode and write the pdfData to it by type casting it using the reinterpret_cast function. Finally, we close the file.

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

8. Freeing up Memory

After successfully creating a PDF file, it's essential to clean up the resources allocated by Wkhtmltopdf, otherwise, it will result in a memory leak.

wkhtmltopdf_destroy_converter(converter); // Destroy the converter
wkhtmltopdf_destroy_object_settings(os);  // Destroy object settings
wkhtmltopdf_destroy_global_settings(gs);  // Destroy global settings
wkhtmltopdf_deinit();                     // Deinitialize the library

std::cout << "PDF created successfully." << std::endl; // Inform the user
wkhtmltopdf_destroy_converter(converter); // Destroy the converter
wkhtmltopdf_destroy_object_settings(os);  // Destroy object settings
wkhtmltopdf_destroy_global_settings(gs);  // Destroy global settings
wkhtmltopdf_deinit();                     // Deinitialize the library

std::cout << "PDF created successfully." << std::endl; // Inform the user
C++

9. 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 Create PDF Files in C++: Figure 3

Create PDF File in C

IronPDF

IronPDF is a .NET C# PDF library that allows developers to create PDF documents from HTML effortlessly. It provides an intuitive API that simplifies the process of creating PDF files from HTML.

IronPDF is robust and versatile when it comes to working with PDFs. It not only creates a PDF from 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 an example code to create PDF with IronPDF using HTML string to PDF conversion:

using IronPdf;

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

// Create a PDF 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 a PDF 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 a PDF 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

We create an instance of ChromePdfRenderer to render the HTML content as a PDF. We call the RenderHtmlAsPdf method on the renderer object and pass in the HTML string. This generates the PDF document, and then we save the PDF document using the SaveAs method.

How to Create PDF Files in C++: Figure 4

For more details on how to create a PDF from various resources with IronPDF, please visit this IronPDF code examples page.

Wnioski

In this article, we explored PDF generation in C++ using the wkhtmltopdf C++ Library and also learned how to use IronPDF to generate PDF documents in C#.

With IronPDF, generating PDF files from HTML content becomes a straightforward task in .NET Framework languages. Its extensive feature set makes 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. Download IronPDF and try it out for yourself.

Curtis Chau
Autor tekstów technicznych

Curtis Chau posiada tytuł licencjata z informatyki (Uniwersytet Carleton) i specjalizuje się w front-endowym rozwoju, z ekspertką w Node.js, TypeScript, JavaScript i React. Pasjonuje się tworzeniem intuicyjnych i estetycznie przyjemnych interfejsów użytkownika, Curtis cieszy się pracą z nowoczesnymi frameworkami i tworzeniem dobrze zorganizowanych, atrakcyjnych wizualnie podrę...

Czytaj więcej

Zespol wsparcia Iron

Jestesmy online 24 godziny, 5 dni w tygodniu.
Czat
Email
Zadzwon do mnie