Adding more pages and more style

bool pdf_setcolor ( resource pdfdoc, string type, string colorspace, float color1 [, float color2 [, float color3 [, float color4]]])

At this point, our script enables us merely to display one page - here's a simple modification to demonstrate multiple pages:

for ($i = 1; $i < 10; ++$i) {
    
pdf_begin_page($pdf, 595, 842);
    
pdf_setfont($pdf, $font, 30);
    
pdf_show_xy($pdf, "This is page $i", 50, 750);
    
pdf_end_page($pdf);
}

As you can see, it is simply a matter of calling pdf_begin_page() and pdf_end_page() repeatedly - although you will likely want to make the content in between more interesting!

A good start is to have a selection of type faces ready for various parts of your document. In our first example, we have just one - Times-Roman is stored in $font. However, that could be easily modified as such:

$times = pdf_findfont($pdf, "Times-Roman", "host");
$timesb = pdf_findfont($pdf, "Times-Bold", "host");
$timesi = pdf_findfont($pdf, "Times-Italic", "host");

Combined with the use of pdf_setfont() 's third parameter, we can therefore create headers and subheaders like this:

for ($i = 1; $i < 10; ++$i) {
    
pdf_begin_page($pdf, 595, 842);

    
pdf_setfont($pdf, $times, 24);
    
pdf_show_xy($pdf, "This is page $i", 50, 750);

    
pdf_setfont($pdf, $timesb, 16);
    
pdf_show_xy($pdf, "Subheader", 100, 700);

    
pdf_setfont($pdf, $timesi, 16);
    
pdf_show_xy($pdf, "This is some standard text.", 100, 700);

    
pdf_end_page($pdf);
}

We can even throw in the pdf_setcolor() function, which takes two text values followed by colour values for its fourth, fifth, sixth, and optionally its seventh parameters, and uses them to set the colour of fills and objects that follow.

Try adding this line just before the first pdf_setfont()...

pdf_setcolor($pdf, "both", "rgb", 1.0 - (0.1 * $i), 0.0, 0.0);

And adding this line just before the second pdf_setfont()...

pdf_setcolor($pdf, "both", "rgb", 0.0, 0.0, 0.0 + (0.1 * $i));

The "both" in there means "set both fill and stroke colour" (recommended most of the time), and the "rgb" means "we're going to provide red, green, and blue values for the value. If you'd rather provide CMYK, specify "cmyk" instead of RGB and add the extra colour value. Save the file as pdf2.php and load it up in your browser - your output should be very close to the picture below - if not, you might want to check your code for errors.

All being well, your top header should start off red and fade into black, whereas your second-level header and the main text should start off black and fade into blue.

 

Next chapter: Adding imagery >>

Previous chapter: Getting started

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar