Generating Dynamic PDF Documents


The PDF is an extremely versatile and well-supported format. PDF viewers are available for nearly every computing platform, and the format itself is designed specifically for the needs of printable documents discussed earlier in this chapter. On top of these requirements, PDF files also support a number of useful navigation aids, such as hyperlinks and bookmarks, making it an ideal format for many types of documents.

The PDFLib Coordinate System

In my discussions of dynamic generation of PDF files from within PHP, I will often refer to the unit points when discussing sizes or positions within a PDF document. A point in PDF documents is a unit of measure: 1 printed inch = 72 points. Thus, there are 72 points to every printed inch in a PDF document. All PDF documents use points to represent distances and dimensions, and unless specifically instructed otherwise, points should be used in any PDF-related function where a location or distance is required.

By the same token, the coordinate system used by PDFLib documents is often a further point of confusion. In PDFLib PDF documents, the X-axis coordinates increase from left to right. However, Y-axis coordinates begin from the bottom and increase toward the top of a given page. Thus, the location (0,0) does not refer to the upper-left corner of the page; it refers to the lower-left corner.

Using PDFLib Configuration Parameters

When you are working with PDFLib, a great number of global settings affect the way a PDF document will be rendered. Some of these settings affect the document on a global scale and some affect specific parts, such as text rendering.

To determine the value of these settings or to change them, you should consider four functions. These functions are pdf_get_parameter(), pdf_set_parameter(), pdf_get_value(), and pdf_set_value(). The syntax for these function is as follows:

 pdf_set_parameter($pdf_r, $parameter, $value) pdf_set_value($pdf_r, $parameter, $value) pdf_get_parameter($pdf_r, $parameter); pdf_get_value($pdf_r, $parameter); 

For each of the preceding functions, the $pdf_r parameter represents the PDF Object resource. $parameter is a string representing the name of the parameter. For the pdf_set_* functions, $value represents the new value to set the setting to. Finally, both pdf_get_* functions return the value of the specified parameter.

As you have noticed, two sets of functions seemingly provide the same functionality to PHP (pdf_*_parameter() and pdf_*_value()). Although PHP is an untyped language (meaning that there is no difference between the string "1" and the integer value 1), the underlying PDFLib library does distinguish between the two. Hence, when setting parameters that are expected to be strings by PDFLib, the pdf_*_parameter() family is expected to be used, whereas the pdf_*_value() family is used for integer values. It is important to use the appropriate function or the results will not be as expected.

Generating PDF Documents from Scratch

The following section introduces some fairly simple examples using PDFLib; you'll move on from there.

When you generate PDF documents from within PHP using PDFLib, the following common set of steps is always taken:

1.

Create a new PDF Object resource.

2.

Begin a new page in the PDF file.

3.

Add the desired graphics, text, formatting, and so on.

4.

Close the page.

5.

Repeat steps 3 through 5, as necessary.

6.

Close the PDF document.

PDF files can be either written to the file system or kept in memory for display to the client browser. Starting from the first step in this process, all PDF generation using PDFLib begins with a call to the pdf_new() function. This function accepts no parameters and returns a reference to an empty PDF Object that all other functions within the PDFLib extension reference.

NOTE

To avoid confusion, the term PDF Object does not indicate that the pdf_new() function returns an instance of a PHP object. The pdf_new() function returns a resource representing what is called a PDF Object.


Although the pdf_new() function returns a resource representing the PDF document to be created, it is not valid until it is "opened" using the pdf_begin_document() function. This function is responsible for determining whether the document will be opened in memory or written to a file and is always called immediately following the pdf_new() function. The syntax for the pdf_begin_document() is as follows:

 pdf_begin_document($pdf_r, $filename, $options); 

$pdf_r is the PDF Object resource returned from a call to pdf_new(), $filename is the file to write the PDF file to, and $options is a string containing a list of options to set for this particular document (see the PDFLib manual for a complete list of valid options). Although none of the parameters can be omitted, the $filename and $options parameters can both be set to an empty string. If the $filename parameter is not a valid filename, the PDFLib extension will create the PDF file only in memory and must be retrieved at a later time using functions to be introduced shortly.

At this point, a PDF file has been created; however, it contains no pages. To add a page to the document, the pdf_begin_page() function is used, which has the following syntax:

 pdf_begin_page($pdf_r, $width, $height); 

$pdf_r is the PDF Object resource, and $width and $height represent the size of the page in points. For your reference, Table 28.1 shows common paper sizes and their width and height in points:

Table 28.1. Common Paper Sizes in Points

Paper Size

Width

Height

A0

2380

3368

A1

1684

2380

A2

1190

1684

A3

842

1190

A4

595

842

A5

421

595

A6

297

421

B5

501

709

Letter

612

792

Legal

612

1008

Ledger

1224

792


While the page is open, all functions that display content will be drawn to that page. To complete a page after all content for it is complete, the pdf_end_page() function is used, which has the following syntax:

 pdf_end_page($pdf_r); 

$pdf_r is the PDF Object resource. As previously mentioned, the process of creating and ending pages can be done as many times as necessary to create the desired document. After the document is complete, the entire PDF object is closed using the pdf_end_document() function with the following syntax:

 pdf_end_document($pdf_r); 

$pdf_r is the PDF Object resource to close. When this function is executed, depending on whether a filename was specified for the original pdf_begin_document() function call, the PDF will be written to disk. If no filename was specified, the PDF must be copied from memory into a PHP variable using the pdf_get_buffer() function, using the syntax:

 pdf_get_buffer($pdf_r); 

Again, $pdf_r is the PDF Object resource. When executed, the pdf_get_buffer() function returns a copy of the buffer containing the PDF document that would have been written to the file system, which can then be displayed to the client browser by specifying the appropriate headers. Although some variations are acceptable, in general the standard headers that must be sent to display PDF documents within a browser are shown next:

 header('Content-type: application/pdf'); header("Content-disposition: inline; filename=example1.pdf"); header("Content-length: " . strlen($data)) ; 

A Skeleton PDF Document

With these basic introductions out of the way, you can create a skeleton PDF document (shown in Listing 28.3) which is displayed directly to the browser:

Listing 28.3. A Skeleton PDF Document Using PDFLib
 <?php     define('PAGE_WIDTH', 612);     define('PAGE_HEIGHT', 792);     $pdf = pdf_new();     pdf_begin_document($pdf, "", "");     pdf_begin_page($pdf, PAGE_WIDTH, PAGE_HEIGHT);     /* Code to display content in the page here */     pdf_end_page($pdf);     pdf_end_document($pdf, "");     $data = pdf_get_buffer($pdf);     header('Content-type: application/pdf');     header("Content-disposition: inline; filename=example1.pdf");     header("Content-length: " . strlen($data));     echo $data; ? > 

Now that you have a skeleton to generate a basic PDF document from, you can generate some real content for the page. PDFLib supports a wide range of functions to render text, place images, and draw within PDF documents. Because most people are initially concerned with rendering text, you'll start there.

NOTE

The skeleton PDF document in Listing 28.3 is referenced throughout this chapter. You should keep this code handy if you plan to experiment with future examples in this chapter.


Rendering Text in a PDF Document

In PDF documents, a number of considerations must be made relating to how text is rendered when displayed. For instance, before any text can be rendered, a font must be selected and used. This task is accomplished using two separate functionsthe first of which is the pdf_findfont() function, which has the following syntax:

 pdf_findfont($pdf_r, $fontname, $encoding, $embed); 

$pdf_r is the PDF Object resource to load the font whose name is specified by the $fontname parameter using the encoding specified by $encoding. The fourth parameter, $embed, is a Boolean value indicating whether the font should be embedded within the PDF document.

The two key parameters in the preceding function are the $fontname and $encoding parameters. The $fontname parameter is the string name of the font, such as "Helvetica", whereas the $encoding parameter can be a wide range of different string values. Unless there is a specific need to specify a specific font encoding, this parameter can be safely set to the string auto, indicating PDFLib should automatically determine the encoding.

NOTE

If you are interested in learning more about the different encodings supported by PDF and PDFLib, consult the PDFLib documentation (Section 4.4 "Encoding Details") for more information.


If you are not sure what types of fonts are standard across most platforms, the following is a list of the fonts provided by default in the PDFLib library:

  • Courier

  • Courier-Bold

  • Courier-Oblique

  • Courier-BoldOblique

  • Helvetica

  • Helvetica-Bold

  • Helvetica-Oblique

  • Helvetica-BoldOblique

  • Times-Roman

  • Times-Bold

  • Times-Italic

  • Times-BoldItalic

  • Symbol

  • ZapfDingbats

The final parameter in the pdf_findfont() function is the $embed parameter, which indicates whether the font should be embedded within the PDF document itself. For most general-use cases (where the fonts being used are common to most systems) this parameter can safely be set to false. However, if custom fonts are used in the generation of PDF documents, they must be included with the document in order to be rendered properly.

Upon successfully locating the desired font, the pdf_findfont() function will return a resource representing that font, or the function will return false on failure.

The pdf_findfont() function can be used as many times as desired to locate multiple different fonts to be used within your PDF document. To actually use a specific font after it has been found to render text, you should use the pdf_setfont() function, whose syntax is as follows:

 pdf_setfont($pdf_r, $font_r, $size); 

$pdf_r represents the PDF Object resource and $font_r represents the font resource returned from a call to pdf_findfont(). The final parameter, $size, indicates the size (in points) to render the font.

After a font has been selected, text may be rendered to the PDF document using various text-rendering functions. For the purposes of these examples, I'll formally introduce the pdf_show_xy() function; its syntax is as follows:

 pdf_show_xy($pdf_r, $text, $start_x, $start_y) 

$pdf_r represents the PDF Object resource, and $text represents the string to write starting at the coordinate ($start_x, $start_y).

Armed with everything you need to insert text into a PDF document, you can now look at the famous "Hello, World!" script using PHP and the PDFLib library:

Listing 28.4. "Hello, World!" Using PDFLib
 <?php     define('PAGE_WIDTH', 612);     define('PAGE_HEIGHT', 792);     $pdf = pdf_new();     pdf_begin_document($pdf, "", "");     pdf_begin_page($pdf, PAGE_WIDTH, PAGE_HEIGHT);     $font = pdf_findfont($pdf, "Helvetica", "auto", false);     pdf_setfont($pdf, $font, 30);     pdf_show_xy($pdf, "PHP Unleashed", 10, PAGE_HEIGHT-40);     pdf_setfont($pdf, $font, 12);     pdf_show_xy($pdf, "Hello, World! Using PDFLib 2.0 and PHP", 10,                 PAGE_HEIGHT-55);     pdf_end_page($pdf);     pdf_end_document($pdf, "");     $data = pdf_get_buffer($pdf);     header('Content-type: application/pdf');     header("Content-disposition: inline; filename=example1.pdf");     header("Content-length: " . strlen($data));     echo $data; ? > 

When the preceding example is rendered, it will produce an output similar to that found in Figure 28.4.

Figure 28.4. A simple "Hello, World!" document in PHP using PDFLib.


In Listing 28.4, I have rendered two separate strings using different font sizes. Note that after a font has been located, it is not necessary to locate it again as long as the initial font resource is still available.

NOTE

PDFLib supports the capability to render fonts outlined, underlined, and other ways. These features can be activated by setting the appropriate PDFLib parameters. Consult the PDFLib documentation for a complete listing of parameters.


Rendering Shapes in PDF Documents

In addition to rendering text, PDFLib supports a number of functions to draw geometric shapes, such as rectangles, circles, and lines. In PDFLib, all drawing in PDF documents is done in two phases. The first phase defines what shapes will be drawn where, and the second phase actually draws those shapes. In the next section, you'll look at how lines are drawn within a PDF document. Note that for each of the following functions, the example provided omits the skeleton code found in Listing 28.3.

Using PDFLib, lines are drawn using a combination of two functions. The first function, pdf_moveto(), is used to define the start location of the line, and the pdf_lineto() function is used to define the end of the line. The syntax for each of these functions is as follows:

 pdf_moveto($pdf_r, $x_location, $y_location); pdf_lineto($pdf_r, $end_x, $end_y); 

In both cases, $pdf_r represents the PDF Object resource. Regarding pdf_moveto(), the $x_location and $y_location parameters represent the X,Y coordinate where the next rendering operation will occur. In the pdf_lineto() function, the $end_x and $end_y parameters represent the X,Y coordinate pair representing the endpoint of the line starting from the last call to pdf_moveto(). For example, to draw a line starting from the upper-right corner of the page to the lower-left corner using the default PDFLib coordinate system, the following two calls must be made (assume PAGE_WIDTH, PAGE_HEIGHT, and $pdf have been defined, as in the skeleton script found in Listing 28.3):

 pdf_moveto($pdf_r, PAGE_WIDTH, PAGE_HEIGHT); pdf_lineto($pdf_r, 0, 0); 

$pdf_r is the PDF object resource in question.

As already noted, graphics are not actually rendered to the PDF document until instructed to do so. This rendering is accomplished using the pdf_stroke() function with the following syntax:

 pdf_stroke($pdf_r); 

When you use the pdf_stroke() function, all noncontinuous drawing routines that occurred since the last call to the pdf_stroke() function will be rendered continuously. For the pdf_lineto() function, this behavior is fairly obvious. However, be aware that this behavior applies to all noncontinuous drawing routines (such as arc segments or Bézier curves) as well.

Similar to the pdf_stroke() function, PDFLib provides the pdf_fill_stroke() function for continuous geometric shapes. This function, whose syntax is identical to pdf_stroke(), will not only outline the geometric shape drawn, but also fill in the shape:

 pdf_fill_stroke($pdf_r); 

Beyond simple lines, similar facilities for drawing other geometric shapes also exist; for instance, to draw rectangles, PDFLib provides the pdf_rect() function with the following syntax:

 pdf_rect($pdf_r, $start_x, $start_y, $width, $height); 

$pdf_r is the PDF Object resource, and the rectangle is defined by the start of the upper-left corner of the rectangle ($start_x, $start_y) and the rectangle's width and height ($width by $height).

For drawing arcs, PDFLib provides two functions, pdf_arc() and pdf_arcn(), which are used to draw arcs in the counterclockwise and clockwise directions, respectively. The syntax for these functions is as follows:

 pdf_arc($pdf_r, $center_x, $center_y, $radius, $start_angle, $end_angle); pdf_arcn($pdf_r, $center_x, $center_y, $radius, $start_angle, $end_angle); 

$center_x and $center_y represent the origin of the arc segment defined by a radius $radius and ranging from $start_angle to $end_angle. All angles are represented in degrees.

Although either of these functions could be used to draw a circle, PDFLib also provides the pdf_circle() function for this special case, which has the following syntax:

 pdf_circle($pdf_r, $center_x, $center_y, $radius); 

$pdf_r represents the PDF Object resource, and the circle is defined by its center coordinates ($center_x, $center_y) with the radius given by $radius.

To provide an example of each function's use, the following three calls, in conjunction with the skeleton code provided in Listing 28.3 (placing the following code before the call to pdf_end_page()), create the image in Figure 28.5:

 pdf_arc($pdf, PAGE_WIDTH/2, PAGE_HEIGHT/2, 100, 0, 90); pdf_stroke($pdf); pdf_arcn($pdf, PAGE_WIDTH/2, PAGE_HEIGHT/2, 50, 0, 90); pdf_stroke($pdf); pdf_circle($pdf, PAGE_WIDTH/2, PAGE_HEIGHT/2, 25); pdf_stroke($pdf); 

Figure 28.5. Drawing arcs and circles using PDFLib.


The final graphic rendering functionality I'll be discussing, the pdf_curveto() function, is used to draw Bézier curves. The syntax for this function is as follows:

 pdf_curveto($pdf_r, $cp1_x, $cp1_y, $cp2_x, $cp2_y,  $end_x, $end_y); 

$pdf_r is the PDF Object resource and the Bézier curve extends from the current coordinates (dictated by the last pdf_moveto() function call) and ends at the coordinate ($end_x, $end_y). The actual nature of the curve between these two points is defined by the coordinates ($cp1_x, $cp1_y) and ($cp2_x, $cp2_y), called control points. To help illustrate how the Bézier curve is rendered, consider the output of the following code segment, which draws a Bézier curve as well as lines connecting each point of the curve:

   pdf_moveto($pdf, 0, PAGE_HEIGHT/2); pdf_curveto($pdf, PAGE_WIDTH/4, PAGE_HEIGHT/2+250,                     (3/4)*PAGE_WIDTH, PAGE_HEIGHT/2-250,                     PAGE_WIDTH, PAGE_HEIGHT/2);   pdf_stroke($pdf);   pdf_moveto($pdf, 0, PAGE_HEIGHT/2);   pdf_lineto($pdf, PAGE_WIDTH/4, PAGE_HEIGHT/2+250);   pdf_lineto($pdf, (3/4)*PAGE_WIDTH, PAGE_HEIGHT/2-250);   pdf_lineto($pdf, PAGE_WIDTH, PAGE_HEIGHT/2);   pdf_stroke($pdf); 

When executed within the skeleton code provided in Listing 28.3, this code snippet produces an output found in Figure 28.6:

Figure 28.6. Rendering Bézier curves using PDFLib.


As you can see by the lines that connect each point defined in the Bézier curve, both defined control points effectively "pull" the line toward that point.

Adding Colors to PDF Documents

Although all the work we have been doing with graphics thus far has been without color, PDF documents generated using PDFLib also support rendering everything using the entire spectrum of colors. In PDFLib, two specific types of colors can be setthe stroke color and the fill color. The stroke color represents the outline of a font or geometric shape, whereas the fill color represents the inner color of the font or shape.

To use colors when rendering PDF documents, the pdf_setcolor() function is used, which has the following syntax:

 pdf_setcolor($pdf_r, $fill_type, $color_type, $c1, $c2, $c3, $c4); 

$pdf_r represents the PDF Object resource, $fill_type represents which color you are setting (fill, stroke, or both), and $color_type identifies how the color is represented, which can be rgb, gray, cmyk, or pattern. The final parameters ($c1, $c2, $c3, and $c4) represent the intensity of each component, depending on the value of the $color_type parameter. For example, if $color_type is set to gray (which has only a single component) only the $c1 parameter is used. In this case a value of 0.5 for $c1 would set the color to the middle range of the grayscale, whereas a value of 1 would be complete black. Likewise, if the rgb type is specified for the $color_type parameter (which has three components), $c1, $c2, and $c3 would all be used, representing red, green, and blue, respectively. In the event a particular color parameter is not used, they should be set to an integer zero.

NOTE

Because it is not widely used, an additional possible value for the $color_type value "spot" has been omitted from the acceptable values. For information regarding this color type, consult the PHP manual and the PDFLib documentation.


To use the pdf_setcolor() function, set up the desired color scheme (for the fill or stroke, or both) and then render text and/or graphics using that color. Note that when you attempt to fill in shapes with a color, the pdf_fill_stroke() function must be used instead of pdf_stroke(). Similarly, fonts do not support the stroke value for the $fill_type parameter (only fill).

For instance, to render a red circle in the center of the PDF document, you can use the following code:

 pdf_setcolor($pdf, "both", "rgb", 1.0, 0.0, 0.0, 0.0); pdf_circle($pdf, PAGE_WIDTH/2, PAGE_HEIGHT/2, 100); pdf_fill_stroke($pdf); 

In another example, the following text will be rendered blue (assume the font has already been selected):

 pdf_setcolor($pdf, "fill", "rgb", 0.0, 0.0, 1.0, 0.0); pdf_show_xy($pdf, "PHP Unleashed", 0, 100); 

Adding Images to PDF Documents

As you may have suspected, PDFLib is capable of embedding images within PDF documents. Although PDFLib provides a number of built-in functions for loading a wide range of graphics from the file system, these functions come with significant restrictions, such as no stream-wrapper support and extremely confusing prototypes.

However, instead of explaining how to use the image-loading functionality provided by PDFLib, a much easier approach is to leverage the capability of the GD graphics library (introduced in Chapter 27, "Working with Images") bundled with PHP and the pdf_open_memory_image() function. The syntax for this function is as follows:

 pdf_open_memory_image($pdf_r, $img_r); 

$pdf_r represents the PDF Object resource, and $img_r represents a valid image resource from a call to the imagecreate family of functions in the GD graphics library. When executed, this function will return a resource representing the image for use with DFLib. After the image has been loaded, it can be placed anywhere on a PDF page using the pdf_place_image() function; the syntax is as follows:

 pdf_place_image($pdf_r, $pdf_img_r, $start_x, $start_y, $scale); 

$pdf_r represents the PDF Object resource, and $pdf_img_r represents the PDF image resource returned by pdf_open_memory_image() or any other PDF image-loading function. The last three parameters define the location where the image will be rendered, starting from the upper-left corner of the image ($start_x, $start_y) and the scale $scale. The $scale parameter is represented by a floating-point value representing the scaling factor.

After the image has been placed as needed within the PDF document, it may be safely discarded using the pdf_image_close() function:

 pdf_image_close($pdf_r, $pdf_img_r); 

NOTE

If you have chosen to use the advised method of loading images into a PDF document (via the GD graphics library), remember that the GD graphics resource should also be freed after it has been passed to the pdf_open_memory_image() function by using the imagedestroy() function. See Chapter 28, "Working with Images," for more information.


For an example of embedding images within PDF documents, see Listing 28.5:

Listing 28.5. Embedding Images in PDF Documents
 <?php     define('PAGE_WIDTH', 612);     define('PAGE_HEIGHT', 792);     $pdf = pdf_new();     pdf_begin_document($pdf, "", "");     pdf_begin_page($pdf, PAGE_WIDTH, PAGE_HEIGHT);     /* Load the logo image and relevant metrics*/     $gd_logo = imagecreatefromjpeg("php-logo.jpg");     $logo = pdf_open_memory_image($pdf, $gd_logo);     $logo_w = pdf_get_value($pdf, "imagewidth", $logo);     imagedestroy($gd_logo);     pdf_place_image($pdf, $logo, PAGE_WIDTH/2 - ($logo_w/2), PAGE_HEIGHT/2, 1.0);     pdf_close_image($pdf, $logo);     pdf_end_page($pdf);     pdf_end_document($pdf, "");     $data = pdf_get_buffer($pdf);     header('Content-type: application/pdf');     header("Content-disposition: inline; filename=example1.pdf");     header("Content-length: " . strlen($data));     echo $data; ?> 

Manipulating the PDF Document Coordinate System

In addition to all the graphics manipulation routines available to you through PDFLib, PHPLib provides a number of useful functions for manipulating the PDF document and the coordinate system itself. The first of these functions is the pdf_translate() function, which is used to move the origin (the location of the 0,0 coordinate) of the coordinate system used by PDFLib; the syntax is as follows:

 pdf_translate($pdf_r, $trans_x, $trans_y); 

$pdf_r is the PDF Object resource, and the coordinates represented by ($TRans_x, $trans_y) identify the new origin of the coordinate system.

In the same family of functions as pdf_translate()is the pdf_rotate() function. This function, as its name implies, is used to rotate the coordinate system using the center of the document (not the origin) as the axis of rotation. The syntax for the pdf_rotate() function is as follows:

 pdf_rotate($pdf_r, $angle); 

$pdf_r is the PDF Object resource and $angle is the angle by which to rotate the page. Positive angles indicate a rotation in the clockwise direction, whereas negative angles represent rotations in the counterclockwise direction.

Yet another coordinate system manipulation that can be done is scaling of the coordinate system via the pdf_scale() function. The syntax of this function is as follows:

 pdf_scale($pdf_r, $scale_x, $scale_y); 

$pdf_r is the PDF Object resource, and $scale_x / $scale_y represents the scaling factor for each axis. The values that can be used for the scaling factor of each axis are as follows:

Scale >= 0

Scale by value * 100 percent.

Scale < 0

Scale by value * 100 and mirror the axis.


When you are working with manipulating the coordinate system, it would prove very useful to be able to freeze the current state of a PDF document, manipulate the coordinate system to ease in the rendering of something, and then later restore the document to its original state (while still keeping your actual drawings, and so on are made in between). PDFLib supports this capability through the use of the pdf_save() and pdf_restore() functions, which save and restore the state of the PDF, respectively. The syntax for these functions are as follows:

 pdf_save($pdf_r); pdf_restore($pdf_r); 

In both cases, the $pdf_r parameter represents the PDF Object resource.

Defining and Using Patterns

Another useful feature of the PDFLib library is the capability to create and fill geometric objects and fonts using a pattern (instead of a solid color). In PDFLib, patterns are created using the same tools you have already been introduced to. The process breaks down as follows:

1.

Starting of the pattern and setting of its attributes

2.

Creating the pattern

3.

Ending the pattern

4.

Using the pattern

In terms of PDFLib functions, a pattern is defined by using the pdf_begin_pattern() function with the following syntax:

 pdf_begin_pattern($pdf_r, $width, $height, $x_step, $y_step, $paint_type); 

$pdf_r represents the PDF Object resource, $width/$height represent the width and height of the template, and $x_step/$y_step represent the distance between each repetition of the pattern when rendered. The final parameter, $paint_type, defines the color information PDFLib will use. If $paint_type is equal to 1, the pattern will be rendered using the same colors it was created with. Conversely, providing the value 2 to the $paint_type variable will create a template that will be rendered using the current, external colors at the time it is rendered.

NOTE

Patterns must be defined outside of any page. Thus, they must exist before calls to pdf_begin_page() and pdf_end_page().


When in the process of creating a pattern, any of the drawing routines already discussed are used. In practical terms, patterns can be considered a page of a PDF document in which width and height are defined by the $width and $height parameters of the call to the pdf_begin_pattern() function. Upon successful definition of the start of a pattern, the pdf_begin_pattern() function will return a resource representing that pattern. After a pattern has been defined, it is saved to memory through the use of the pdf_end_pattern() function with the following syntax:

 pdf_end_pattern($pdf_r); 

$pdf_r is the PDF Object resource.

After a pattern has been defined, it can be used as a fill color by using the pdf_setcolor() function, setting the $color_type parameter to "pattern", and specifying the resource returned from pdf_begin_pattern() as the $c1 parameter in pdf_setcolor(). Listing 28.6 demonstrates this use of patterns:

Listing 28.6. Defining Patterns in PDFLib
 <?php     define('PAGE_WIDTH', 612);     define('PAGE_HEIGHT', 792);     $pdf = pdf_new();     pdf_begin_document($pdf, "", "");     /* Define a pattern of dots */     $pattern = pdf_begin_pattern($pdf, 21, 21, 22, 22, 1);     pdf_setcolor($pdf, "stroke", "rgb", 0.0, 0.0, 1.0, 0);     pdf_circle($pdf, 11, 11, 10);     pdf_stroke($pdf);     pdf_end_pattern($pdf);     pdf_begin_page($pdf, PAGE_WIDTH, PAGE_HEIGHT);     /* Use the defined pattern to draw a circle */     pdf_setcolor($pdf, "fill", "pattern", $pattern, 0, 0, 0);     pdf_circle($pdf, PAGE_WIDTH/2, PAGE_HEIGHT/2, 150);     pdf_fill_stroke($pdf);     pdf_end_page($pdf);     pdf_end_document($pdf, "");     $data = pdf_get_buffer($pdf);     header('Content-type: application/pdf');     header("Content-disposition: inline; filename=example1.pdf");     header("Content-length: " . strlen($data));     echo $data; ?> 

When executed within the skeleton code provided in Listing 28.6, this code snippet produces an output found in Figure 28.7:

Figure 28.7. Using patterns to fill in shapes using PDFLib.


Defining and Using Templates

Another useful feature of PDFLib is its capability to define templates. Templates are extremely similar to patterns in the way they are constructed. However, instead of using them as the fill color for shapes or text, templates can be arbitrarily placed in PDF documents in the same way images are placed. The process of creating a template is as follows:

1.

Starting the template

2.

Ceating the template

3.

Eding the template

4.

Using the template

In a form similar to patterns, templates are created using the pdf_begin_template() function, whose syntax is as follows:

 pdf_begin_template($pdf_r, $width, $height); 

NOTE

Like patterns, templates must be created outside of the normal creation of pages. Thus, the pdf_begin_template() function must be called between calls to pdf_begin_page() and pdf_end_page().


$pdf_r is the PDF Object resource, and the size of the template is defined by the $width and $height parameters. Like patterns, the pdf_begin_template() function returns a template resource representing the template. However, before this template resource can be used, the template must be ended. This is accomplished by the use of the pdf_end_template() function with the following syntax:

 pdf_end_template($pdf_r); 

$pdf_r represents the PDF object resource.

Although templates and patterns have much in common, they have distinctly different uses in PDF generation. Templates are designed mostly for use across multiple pages of a document to provide a consistent look and feel, whereas patterns are tools that help define that look and feel.

The example provided in Listing 28.7 shows an example of a template's use. In this example, a standardized header is created as a template and then placed across five pages within a PDF document:

Listing 28.7. Using Templates in PDFLib
 <?php     define('PAGE_WIDTH', 612);     define('PAGE_HEIGHT', 792);     define('HEADER_HEIGHT', 100);     define('HEADER_TEXT', "PHP Unleashed");     define('HEADER_LOGO', "php-logo.jpg");     $pdf = pdf_new();     pdf_begin_document($pdf, "", "");     /* Load the logo image and relevant metrics*/     $logo = pdf_open_image_file($pdf, "jpeg", "php-logo.jpg", null, null);     $logo_h  = pdf_get_value($pdf, "imageheight", $logo);     /* Define a template header */     $template = pdf_begin_template($pdf, PAGE_WIDTH, HEADER_HEIGHT);         pdf_place_image($pdf, $logo, 5, (HEADER_HEIGHT-$logo_h)/2, 1.0);         $font = pdf_findfont($pdf, "Helvetica-Bold", "auto", false);         pdf_setfont($pdf, $font, 40);         $s_width = pdf_stringwidth($pdf, HEADER_TEXT, $font, 40);         pdf_show_xy($pdf, HEADER_TEXT, PAGE_WIDTH-$s_width - 10, 35);     pdf_end_template($pdf) ;     pdf_close_image($pdf, $logo);     for($i = 0; $i < 5; $i++) {         pdf_begin_page($pdf, PAGE_WIDTH, PAGE_HEIGHT);         pdf_place_image($pdf, $template, 0, PAGE_HEIGHT-80, 1.0);         pdf_end_page($pdf);     }     pdf_end_document($pdf, "");     $data = pdf_get_buffer($pdf);     header('Content-type: application/pdf');     header("Content-disposition: inline; filename=example1.pdf");     header("Content-length: " . strlen($data));     echo $data; ?> 

Setting PDF Publisher Information

In every PDF document are a number of embedded fields that provide useful information, such as the author and subject of the PDF. Using PDFLib, all these document attributes can be set using the pdf_set_info() function, which has the following syntax:

 pdf_set_info($pdf_r, $attribute, $value); 

$pdf_r is the PDF object resource, $attribute is the PDF attribute to set, and $value is the value of that attribute. Although there is no restriction on the attributes that may be set within a PDF document, there are a number of officially recognized fields that are provided next:

Attribute Name

Description

Subject

The topic of the document

Title

The title of the document

Creator

The creator of the document

Author

The document author

Keywords

A comma-separated list of keywords for this document




PHP 5 Unleashed
PHP 5 Unleashed
ISBN: 067232511X
EAN: 2147483647
Year: 2004
Pages: 257

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net