Leverage the Work of Others
In principle, you could read the PDF standard and teach your C and C++ programs to write correct PDF on your own. Far wiser, though, is to take advantage of one of the several fine libraries that have already been written. For this example, we'll use the PDFlib library from PDFlib GmbH of Mï¿_nchen. PDFlib is a moderately-priced commercial product, available on a wide variety of platforms, with bindings for many languages, including both C and C++. The software can be freely downloaded; only when you are ready to pay for the commercial license do you buy a key.
For this example, start by downloading http://www.pdflib.com/products/pdflib/download/PDFlib-5.0.1-Linux.tar.gz to an x86-based Linux host. Unpack the archive. Create hello.c with the following contents:
#include <stdio.h> #include <stdlib.h> #include "pdflib.h" int main(int argc, char **argv) { PDF *document; int font; document = PDF_new(); PDF_open_file(document, "example.pdf"); PDF_begin_page(document, letter_width, letter_height); font = PDF_load_font(document, "Helvetica-Bold", 0, "host", ""); PDF_setfont(document, font, 34); PDF_set_text_pos(document, 200, 600); PDF_show(document, "Hello, world."); PDF_setfont(document, font, 14); PDF_continue_text(document, "(programmatically speaking)"); PDF_end_page(document); PDF_close(document); PDF_delete(document); return 0; }
Generate an executable with an invocation such as the following:
cc -o hello -I./PDFlib-5.0.1-Linux/bind/c/include/ hello.c PDFlib-5.0.1-Linux/bind/c/lib/libpdf.a -lm
Launching the resulting ./hello produces example.pdf, as shown in Figure 1. You've done it!
Figure 1 .hello produces this PDF image.
This is only a tiny example, of course; it's not even complete, in the sense that the program doesn't check error conditions from PDF_*() function calls. It hints at what's possible, though: If your C-coded programs can access and compute important textual data, they can automatically render it into good-looking PDF documents.