C++: Create a PDF Document from Scratch

PDF documents generated through code are consistent in terms of formatting, layout, and content, ensuring a professional look. Automating the creation of PDF documents reduces the time and effort required to produce them manually. Nowadays, most invoices, receipts and other financial documents are generated programmatically. In this article, you will learn how to create PDF documents from scratch in C++ using Spire.PDF for C++.

Install Spire.PDF for C++

There are two ways to integrate Spire.PDF for C++ into your application. One way is to install it through NuGet, and the other way is to download the package from our website and copy the libraries into your program. Installation via NuGet is simpler and more recommended. You can find more details by visiting the following link.

Integrate Spire.PDF for C++ in a C++ Application

Background Knowledge

A page in Spire.PDF for C++ (represented by PdfPageBase class) consists of client area and margins all around. The content area is for users to write various contents, and the margins are usually blank edges.

As shown in the figure below, the origin of the coordinate system on the page is located at the top left corner of the client area, with the x-axis extending horizontally to the right and the y-axis extending vertically down. All elements added to the client area must be based on the specified coordinates.

C++: Create a PDF Document from Scratch

In addition, the following table lists the important classes and methods, which can help you easily understand the code snippet provided in the following section.

Member Description
PdfDocument class Represents a PDF document model.
PdfPageBase class Represents a page in a PDF document.
PdfSolidBrush class Represents a brush that fills any object with a solid color.
PdfTrueTypeFont class Represents a true type font.
PdfStringFormat class Represents text format information, such as alignment, characters spacing and indent.
PdfTextWidget class Represents the text area with the ability to span several pages.
PdfTextLayout class Represents the text layout information.
PdfDocument->GetPages()->Add() method Adds a page to a PDF document.
PdfPageBase->GetCanvas()->DrawString() method Draws string on a page at the specified location with specified font and brush objects.
PdfLayoutWidget->Draw() method Draws widget on a page at the specified location.
PdfDocument->Save() method Saves the document to a PDF file.

Create a PDF Document from Scratch in C++

Despite the fact that Spire.PDF for C++ enables users to add various elements to PDF documents, this article demonstrates how to create a simple PDF document with only plain text. The following are the detailed steps.

  • Create a PdfDocument object.
  • Add a page using PdfDocument->GetPages()->Add() method.
  • Create brush and font objects.
  • Draw string on the page at a specified coordinate using PdfPageBase->GetCanvas()->DrawString() method.
  • Create a PdfTextWidget object to hold a chunk of text.
  • Convert the text widget to an object of PdfLayoutWidget class and draw it on the page using PdfLayoutWidget->Draw() method
  • Save the document to a PDF file using PdfDocument->Save() method.
  • C++
#include "Spire.Pdf.o.h";

using namespace Spire::Pdf;
using namespace Spire::Common;
using namespace std;

wstring readFileIntoWstring(const string& path) {

    ifstream input_file(path);
    if (!input_file.is_open()) {
        cerr << "Could not open the file - '"
            << path << "'" << endl;
        exit(EXIT_FAILURE);
    }
    string s1 = string((std::istreambuf_iterator<char>(input_file)), std::istreambuf_iterator<char>());
    wstring ws(s1.begin(), s1.end());
    return ws;
}

int main() {

    //Create a PdfDocument object
    intrusive_ptr<PdfDocument> doc = new PdfDocument();

    //Add a page
    intrusive_ptr<PdfPageBase> page = doc->GetPages()->Add(PdfPageSize::A4(), new PdfMargins(35));

    //Specify title text
    wstring titleText = L"What is MySQL";

    //Create solid brushes
    intrusive_ptr<PdfSolidBrush> titleBrush = new PdfSolidBrush(new PdfRGBColor(Color::GetPurple()));
    intrusive_ptr<PdfSolidBrush> paraBrush = new PdfSolidBrush(new PdfRGBColor(Color::GetBlack()));

    //Create true type fonts
    intrusive_ptr<PdfTrueTypeFont> titleFont = new PdfTrueTypeFont(L"Times New Roman", 18, PdfFontStyle::Bold, true);
    intrusive_ptr<PdfTrueTypeFont> paraFont = new PdfTrueTypeFont(L"Times New Roman", 12, PdfFontStyle::Regular, true);

    //Set the text alignment via PdfStringFormat class
    intrusive_ptr<PdfStringFormat> format = new PdfStringFormat();
    format->SetAlignment(PdfTextAlignment::Center);

    //Draw title on the page
    page->GetCanvas()->DrawString(titleText.c_str(), titleFont, titleBrush, page->GetClientSize()->GetWidth() / 2, 20, format);  

    //Get paragraph text from a .txt file
    wstring paraText = readFileIntoWstring("C:\\Users\\Administrator\\Desktop\\content.txt");

    //Create a PdfTextWidget object to hold the paragraph content
    intrusive_ptr<PdfTextWidget> widget = new PdfTextWidget(paraText.c_str(), paraFont, paraBrush);

    //Create a rectangle where the paragraph content will be placed
    intrusive_ptr<RectangleF> rect = new RectangleF(0, 50, (float)page->GetClientSize()->GetWidth(), (float)page->GetClientSize()->GetHeight());

    //Set the PdfLayoutType to Paginate to make the content paginated automatically
    intrusive_ptr<PdfTextLayout> layout = new PdfTextLayout();
    layout->SetLayout(PdfLayoutType::Paginate);

    //Draw paragraph text on the page
    Object::Convert<PdfLayoutWidget>(widget)->Draw(page, rect, layout);

    //Save to file
    doc->SaveToFile(L"output/CreatePdfDocument.pdf");
    doc->Dispose();
}

C++: Create a PDF Document from Scratch

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.