Chapter 17. Creating PDFs

Adobe makes a collection of commercial products to create, view, and modify PDFs, but they invariably come with a hefty price tag and generally are restricted to Windows and Macintosh platforms. Once again, PHP comes to the rescue!

Before you begin, note that measurements are in points, and there are 72 points to an inch. However, this can be altered by changing the output resolution of the produced PDF.

Getting Started

Creating a PDF document is similar to creating a picture in that, to get the desired end result, you state the list of drawing actions required to get there—drawing lines, text, adding fonts, etc. You need to track the PDF document you are working with at all times, because other PDF functions use it.

Even creating a simple PDF takes quite a few functions; this next code block does comparatively little:

    $pdf = pdf_new();
    pdf_open_file($pdf, "/path/to/your.pdf");
    $font = pdf_findfont($pdf, "Times-Roman", "host");

    pdf_begin_page($pdf, 595, 842);
    pdf_setfont($pdf, $font, 30);
    pdf_show_xy($pdf, "Printing text is easy", 50, 750);
    pdf_end_page($pdf);

    pdf_close($pdf);
    pdf_delete($pdf);

Starting at line one, we use pdf_new() to create a new PDF document and store it in $pdf. This value will be used in all the subsequent functions, so it is important to keep.

The pdf_open_file() function is used to open a file for writing. Note that the free version of PDFlib does not allow alteration of existing PDFs; this function merely creates a new PDF of the ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.