libpdf++ is a object-oriented library for generating PDF (portable document format) files. It is design in a way that the objects in the document are mapped directly to classes in the library. For example, a text segment is represented by the CText class. The main purpose of this to make the library easy to use and understand.
libpdf++ is very easy to use. See the hello world example below:
using namespace pdf ; CDoc doc ; page::CPage page( 594, 828 ) ; font::CStandard *tmr = new font::CStandard( font::CStandard::times_roman ) ; doc.AddFont( tmr ) ; text::CState s( tmr, 12 ) ; page.DrawText( CText( "hello world!", s, 50, 758 ) ) ; doc.AddPage( page ) ; std::ofstream file( "hello.pdf" ) ; doc.Write( file ) ;
Now the program can produce a PDF file like this:
First, all classes in libpdf++ is in the namespace pdf. Adding a "using namespace pdf ;" can save you quite a number of keystrokes. In addition, there are also namespaces nested inside the pdf namespace, e.g. text, font and graph. The convention is that all nested namespaces have its own subdirectory. So if you want to #include the header of text::CState class, which is in namespace text, you will have to type:
#include "text/State.hh"
Now we create an PDF document object and a page object:
CDoc doc ; page::CPage page( 594, 828 ) ;
A document is made up of pages, and pages is made up of text and graphics. So now it is time to put some text in the page:
font::CStandard *tmr = new font::CStandard( font::CStandard::times_roman ) ; doc.AddFont( tmr ) ; text::CState s( tmr, 12 ) ; page.DrawText( CText( "hello world!", s, 50, 758 ) ) ;
The above code will create a times new roman font, which is one of the Adobe standard font that every PDF viewer must have. The font object must be added to the document object before use. Then a text state object is constructed. This object contain the formatting of the text: font, font size, character spacing, scaling, etc. In our simple tutorial, we just use 12 points times new roman. Please see the Text and Fonts page for details of text input of libpdf++.
Once we prepared a page, we can add it to the document:
doc.AddPage( page ) ;
The AddPage() function will make a copy of the page object and store it. As a result, further modification on the page object will not affect the document. If you want to modify the page after adding it, you can use the [] operator to get a reference of the page:
page::CPage& page1 = doc[0] ; page1.DrawText( ... ) ;
or simply:
doc[0].DrawText( ... ) ;
Once we have finished adding pages, the next step is to write the document into a file, using the CDoc::Write() function. We make a ofstream object and call CDoc::Write().
std::ofstream file( "hello.pdf" ) ; doc.Write( file ) ;
Now we have our hello.pdf!