Programming PHPProgramming PHPSearch this book

10.3. Text

Text is the heart of a PDF file. As such, there are many options for changing the appearance and layout of text. In this section, we'll discuss the coordinate system used in PDF documents, functions for inserting text and changing text attributes, and font usage.

10.3.1. Coordinates

The origin ((0,0)) in a PDF document is in the bottom-left corner. All of the measurements are specified in DTP points. A DTP point is equal to 1/72 of an inch, or 0.35277777778 mm.

Example 10-2 puts text in the corners and center of a page.

Example 10-2. Demonstrating coordinates

<?php
 $pdf = pdf_new( );
 pdf_open_file($pdf);
 pdf_set_info($pdf,"Creator","coords.php");
 pdf_set_info($pdf,"Author","Rasmus Lerdorf");
 pdf_set_info($pdf,"Title","Coordinate Test (PHP)");
 pdf_begin_page($pdf,612,792);

 $font = pdf_findfont($pdf,"Helvetica-Bold","host",0);
 pdf_setfont($pdf,$font,38.0);
 pdf_show_xy($pdf, "Bottom Left", 10, 10);
 pdf_show_xy($pdf, "Bottom Right", 350, 10);
 pdf_show_xy($pdf, "Top Left", 10, 752);
 pdf_show_xy($pdf, "Top Right", 420, 752);
 pdf_show_xy($pdf, "Center",612/2-60,792/2-20);

 pdf_end_page($pdf);
 pdf_set_parameter($pdf, "openaction", "fitpage");
 pdf_close($pdf);

 $buf = pdf_get_buffer($pdf);
 $len = strlen($buf);
 header("Content-Type: application/pdf");
 header("Content-Length: $len");
 header("Content-Disposition: inline; filename=coords.pdf");
 echo $buf;
 pdf_delete($pdf);
?>

The output of Example 10-2 is shown in Figure 10-2.

Figure 10-2

Figure 10-2. Coordinate demo output

It can be inconvenient to use a bottom-left origin. Example 10-3 puts the origin in the top-left corner and displays a string near that corner.

Example 10-3. Changing the origin

<?php
 $pdf = pdf_new( );
 pdf_open_file($pdf);
 pdf_set_info($pdf,"Creator","coords.php");
 pdf_set_info($pdf,"Author","Rasmus Lerdorf");
 pdf_set_info($pdf,"Title","Coordinate Test (PHP)");
 pdf_begin_page($pdf,612,792);
 pdf_translate($pdf,0,792);                 // move origin
 pdf_scale($pdf, 1, -1);                    // redirect horizontal coordinates
 pdf_set_value($pdf,"horizscaling",-100);   // keep normal text direction

 $font = pdf_findfont($pdf,"Helvetica-Bold","host",0);
 pdf_setfont($pdf,$font,-38.0);             // text points upward
 pdf_show_xy($pdf, "Top Left", 10, 40);

 pdf_end_page($pdf);
 pdf_set_parameter($pdf, "openaction", "fitpage");
 pdf_close($pdf);

 $buf = pdf_get_buffer($pdf);
 $len = strlen($buf);
 Header("Content-Type:application/pdf");
 Header("Content-Length:$len");
 Header("Content-Disposition:inline; filename=coords.pdf");
 echo $buf;
 pdf_delete($pdf);
?>

The output of Example 10-3 is shown in Figure 10-3.

Figure 10-3

Figure 10-3. Changing the origin

The pdf_translate( ) function moves the origin to the top of the page, and pdf_scale( ) inverts the Y-axis coordinates. To avoid producing text that can be read only in a mirror, we set the horizscaling parameter.

10.3.2. Text Functions

PDF files have the concept of the current text position. It's like a cursor—unless you specify another location, when you insert text it appears at the current text location. You set the text location with the pdf_set_textpos( ) function:

pdf_set_textpos(pdf, x, y);

Once you have positioned the cursor, use the pdf_show( ) function to draw text there:

pdf_show(pdf, text);

After you call pdf_show( ), the cursor moves to the end of the inserted text.

You can also move the location and draw text in one function, with pdf_show_xy( ):

pdf_show_xy(pdf, text, x, y);

The pdf_continue_text( ) function moves to the next line and outputs text:

pdf_continue_text(pdf, text);

Set the leading parameter with pdf_set_parameter( ) to change the vertical separation between lines.

The pdf_show_boxed( ) function lets you define a rectangular area within which a string of text is formatted:

$c = pdf_show_boxed(pdf, text, x, y, width, height, mode [, feature]);

The mode parameter controls the alignment of the text within the box, and can be "left", "right", "center", "justify", or "fulljustify". The difference between "justify" and "fulljustify" is in the treatment of the last line. The last line in a "justify"-formatted area is not justified, whereas in a "fulljustify" area it is. Example 10-4 shows all five cases.

Example 10-4. Text alignment within a box

<?php
 $pdf = pdf_new( );
 pdf_open_file($pdf);
 pdf_begin_page($pdf,612,792);

 $font = pdf_findfont($pdf,"Helvetica-Bold","host",0);
 pdf_setfont($pdf,$font,38);
 $text = <<<FOO
 This is a lot of text inside a text box in a small pdf file.
 FOO;

 pdf_show_boxed($pdf, $text, 50, 590, 300, 180, "left");
 pdf_rect($pdf,50,590,300,180); pdf_stroke($pdf);
 pdf_show_boxed($pdf, $text, 50, 400, 300, 180, "right");
 pdf_rect($pdf,50,400,300,180); pdf_stroke($pdf);
 pdf_show_boxed($pdf, $text, 50, 210, 300, 180, "justify");
 pdf_rect($pdf,50,210,300,180);
 pdf_stroke($pdf);
 pdf_show_boxed($pdf, $text, 50, 20, 300, 180, "fulljustify");
 pdf_rect($pdf,50,20,300,180);
 pdf_stroke($pdf);
 pdf_show_boxed($pdf, $text, 375, 235, 200, 300, "center");
 pdf_rect($pdf,375,250,200,300);
 pdf_stroke($pdf); pdf_end_page($pdf); 
 pdf_set_parameter($pdf, "openaction", "fitpage");
 pdf_close($pdf);

 $buf = pdf_get_buffer($pdf); 
 $len = strlen($buf);
 header("Content-Type:application/pdf");
 header("Content-Length:$len"); 
 header("Content-Disposition:inline; filename=coords.pdf");
 echo $buf; 
 pdf_delete($pdf); 
?>

Figure 10-4 shows the output of Example 10-4.

Figure 10-4

Figure 10-4. Different text alignments

The pdf_show_boxed( ) function returns the number of characters that did not fit in the box. If the feature parameter is present, it must be set to the string "blind". This prevents the text from being drawn on the page and is useful for checking whether a string will fit in the box without actually drawing it.

10.3.3. Text Attributes

There are three common ways to alter the appearance of text. One is to underline, overline, or strike out the text using parameters. Another is to change the stroking and filling. The third is to change the text's color.

Each of the underline, overline, and strikeout parameters may be set to "true" or "false" independently of the others. For example:

pdf_set_parameter($pdf, "underline", "true");  // enable underlining

Stroking text means drawing a line around the path defined by the text. The effect is an outline of the text. Filling text means to fill the shape defined by the text. You can set whether text should be stroked or filled with the textrendering parameter. The valid values are shown in Table 10-2.

Table 10-2. Values for the textrendering parameter

Value

Effect

0

Normal

1

Stroke (outline)

2

Fill and stroke

3

Invisible

4

Normal, add to clipping path

5

Fill and stroke, add to clipping path

6

Invisible, add to clipping path

You can select the text color using the pdf_setcolor( ) function:

pdf_setcolor(pdf, type, colorspace, c1 [, c2, c3 [, c4]]);

The type parameter is either "stroke", "fill", or "both", indicating whether you're specifying the color to be used for outlining the letters, filling the letters, or both. The colorspace parameter is one of "gray", "rgb", "cmyk", "spot", or "pattern". The "gray", "spot", and "pattern" colorspaces take only one color parameter, whereas "rgb" takes three and "cmyk" takes all four.

Example 10-5 shows colors, underlines, overlines, strikeouts, stroking, and filling at work.

Example 10-5. Changing text attributes

<?php
 $p = pdf_new( );
 pdf_open_file($p);
 pdf_begin_page($p,612,792);

 $font = pdf_findfont($p,"Helvetica-Bold","host",0);
 pdf_setfont($p,$font,38.0);
 pdf_set_parameter($p, "overline", "true");
 pdf_show_xy($p, "Overlined Text", 50,720);
 pdf_set_parameter($p, "overline", "false");
 pdf_set_parameter($p, "underline", "true");
 pdf_continue_text($p, "Underlined Text");
 pdf_set_parameter($p, "strikeout", "true");
 pdf_continue_text($p, "Underlined strikeout Text");
 pdf_set_parameter($p, "underline","false");
 pdf_set_parameter($p, "strikeout","false");
 pdf_setcolor($p,"fill","rgb", 1.0, 0.1, 0.1);
 pdf_continue_text($p, "Red Text");
 pdf_setcolor($p,"fill","rgb", 0, 0, 0);
 pdf_set_value($p,"textrendering",1);
 pdf_setcolor($p,"stroke","rgb", 0, 0.5, 0);
 pdf_continue_text($p, "Green Outlined Text");
 pdf_set_value($p,"textrendering",2);
 pdf_setcolor($p,"fill","rgb", 0, .2, 0.8);
 pdf_setlinewidth($p,2);
 pdf_continue_text($p, "Green Outlined Blue Text");
 pdf_end_page($p); 
 pdf_close($p); 

 $buf = pdf_get_buffer($p); 
 $len = strlen($buf);
 header("Content-Type: application/pdf");
 header("Content-Length: $len"); 
 header("Content-Disposition: inline; filename=coord.pdf");
 echo $buf; 
 pdf_delete($p); 
?>

Figure 10-5 shows the output of Example 10-5.

Figure 10-5

Figure 10-5. Lining, stroking, filling, and coloring text

10.3.4. Fonts

There are 14 built-in fonts in PDF, as listed in Table 10-3. If you use only these fonts, the documents you create will be smaller and more portable than if you use nonstandard fonts.

Table 10-3. Standard PDF fonts

Courier

Courier-Bold

Courier-BoldOblique

Courier-Oblique

Helvetica

Helvetica-Bold

Helvetica-BoldOblique

Helvetica-Oblique

Times-Bold

Times-BoldItalic

Times-Italic

Times-Roman

Symbol

ZapfDingbats

   

You can select a font with the pdf_findfont( ) function:

$font = pdf_findfont(pdf, fontname, encoding, embed);

The encoding parameter indicates how the internal numeric codes for characters map onto the font's characters. The built-in encodings are "winansi" (Windows, a superset of ISO 8859-1, which is itself a superset of ASCII), "macroman" (Macintosh), "ebcdic" (IBM mainframe), "builtin" (for symbol fonts), and "host" ("macroman" on the Mac, "ebcdic" on EBCDIC-based systems, and "winansi" on everything else). When using built-in fonts, stick to "host".

You can load nonstandard fonts if you have the PostScript font metrics or TrueType files. If you want to embed the nonstandard fonts in the PDF file, rather than using whatever fonts on the viewer's system most resemble them, set the embed parameter to 1. You do not need to embed the standard fonts.

Using nonstandard fonts without embedding them makes your documents much less portable, while embedding them makes your generated PDF files much larger. You also need to be careful of not violating any font license terms, because some fonts are not supposed to be embedded. TrueType font files have an indicator that is set if the font should not be embedded. This is honored by pdflib, which produces an error if you try to embed such a font.

10.3.5. Embedding Fonts

To use nonstandard fonts, you must tell pdflib where they are with the FontAFM, FontPFM, or FontOutline parameters. For example, to use a TrueType font, you can do this:

pdf_set_parameter($p,"FontOutline", "CANDY==/usr/fonts/candy.ttf");
$font = pdf_findfont($p, "CANDY", "host", 1);

The double equals sign in this code tells pdflib that you are specifying an absolute path. A single equals sign would indicate a path relative to the default font directory.

Instead of using explicit pdf_set_parameter( ) calls each time you want to use a nonstandard font, you can tell your pdflib installation about these extra fonts by adding the FontAFM, FontPFM, and FontOutline settings to pdflib's pdflib.upr file.

Here's a sample set of additions to the FontAFM and FontOutline sections of the pdflib.upr file. The line that starts with two slashes (//) indicates the default directory for font files. The format for the other lines is simply fontname=filename:

//usr/share/fonts

FontAFM
LuciduxSans=lcdxsr.afm
Georgia=georgia.afm

FontOutline
Arial=arial.ttf
Century Gothic=GOTHIC.TTF
Century Gothic Bold=GOTHICB.TTF
Century Gothic Bold Italic=GOTHICBI.TTF
Century Gothic Italic=GOTHICI.TTF

You can specify an absolute path to a font file if you wish.

Example 10-6 shows most of the built-in fonts along with the five extra AFM (Adobe Font Metric) and two extra TrueType fonts installed in the pdflib.upr file above. It displays new Euro currency symbol along with a collection of accented characters used in French.

Example 10-6. Font demonstration

<?php 
 $p = pdf_new( ); 
 pdf_open_file($p); 
 pdf_set_info($p,"Creator","hello.php"); 
 pdf_set_info($p,"Author","Rasmus Lerdorf"); 
 pdf_set_info($p,"Title","Hello world (PHP)"); 
 pdf_set_parameter($p, "resourcefile", '/usr/share/fonts/pdflib/pdflib.upr');
 pdf_begin_page($p,612,792);
 pdf_set_text_pos($p,25,750);
 $fonts = array('Courier'=>0,'Courier-Bold'=>0,'Courier-BoldOblique'=>0,
                'Courier-Oblique'=>0,'Helvetica'=>0,'Helvetica-Bold'=>0,
                'Helvetica-BoldOblique'=>0,'Helvetica-Oblique'=>0,
                'Times-Bold'=>0,'Times-BoldItalic'=>0, 'Times-Italic'=>0,
                'Times-Roman'=>0, 'LuciduxSans'=>1,
                'Georgia' => 1, 'Arial' => 1, 'Century Gothic' => 1,
                'Century Gothic Bold' => 1, 'Century Gothic Italic' => 1,
                'Century Gothic Bold Italic' => 1
               );  
 foreach($fonts as $f=>$embed) { 
   $font = pdf_findfont($p,$f,"host",$embed); 
   pdf_setfont($p,$font,25.0); 
   pdf_continue_text($p,"$f (".chr(128)." Ç à á â ã ç è é ê)");
 }
 pdf_end_page($p); 
 pdf_close($p); 
 $buf = pdf_get_buffer($p); 
 $len = strlen($buf);
 Header("Content-Type: application/pdf");
 Header("Content-Length: $len"); 
 Header("Content-Disposition: inline; filename=hello_php.pdf");
 echo $buf; 
 pdf_delete($p); 
?>

The output of Example 10-6 is shown in Figure 10-6.

Figure 10-6

Figure 10-6. Output of the font demonstration



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.