CXII. Funciones PDF

Introducción

Las funciones PDF en PHP pueden crear archivos PDF utilizando la biblioteca PDFlib creada por Thomas Merz.

La documentación en esta sección solamente es una descripción de las funciones de la biblioteca PDFlib y no debería considerarse una referencia exhaustiva. Se ha de consultar la documentación incluida en el código fuente de la distribución de PDFlib para una completa y detallada explicación de cada función. Proporciona muy buena descripción de las capacidades de PDFlib y contiene actualizada la documentación de todas las funciones.

Todas las funciones de PDFlib y del módulo PHP tienen nombres iguales para las funciones y parámetros. Se necesitará entender algunos de los conceptos básicos de PDF y PostScript para un eficiente uso de esta extensión. Todas las longitudes y coordenadas se mesuran en puntos PostScript. Generalmente hay 72 puntos PostScript por pulgada, pero esto depende de la resolución de salida. Se puede consultar la documentación incluida en la distribución de PDFlib para una detallada explicación del sistema de coordenadas utilizado.

Hay que tener en cuenta que la mayoría de las funciones PDF requieren un primer parámetro pdfdoc. En los siguientes ejemplos hay más información.

Nota: Si se está interesado en alternativas de generadores gratis de PDF que no utilizen liberías externas PDF, mirar este FAQ relacionado.

Requisitos

PDFlib está disponible para descargar en http://www.pdflib.com/products/pdflib/index.html, pero requiere la compra de una licencia para uso comercial. Se requieren las bibliotecas JPEG y TIFF para compilar esta extensión.

Compatibilidad con versiones antiguas de PDFlib

Cualquier versión de PHP después del 9 de Marzo del 2000 no soporta versiones de PDFlib anteriores a la 3.0.

PDFlib 3.0 o superior es compatible desde PHP 3.0.19 en adelante.

Instalación

Esta extension PECL no esta ligada a PHP. Mas informacion sobre nuevos lanzamientos, descargas ficheros de fuentes, informacion sobre los responsables asi como un 'CHANGELOG', se puede encontrar aqui: http://pecl.php.net/package/pdflib.

To get these functions to work in PHP < 4.3.9, you have to compile PHP with --with-pdflib[=DIR]. DIR is the PDFlib base install directory, defaults to /usr/local.

As of PHP 4.3.9, you must install this extension through PEAR, using the following command: pear install pdflib.

Configuración en tiempo de ejecución

Esta extensión no tiene directivas de configuración en php.ini.

Confusiones con antiguas versiones de PDFlib

Desde PHP 4.0.5, la extensión PHP para PDFlib es oficialmente soportada por PDFlib GmbH. Esto significa que todas las funciones descritas en el manual de PDFlib (V3.00 o superior) son soportadas por PHP 4 con el mismo funcionamiento y parámetros. Sólo los valores devueltos pueden variar en el manual PDFlib, ya que PHP adoptó la convención de devolver FALSE. Por razones de compatibilidad, PDFlib aún soporta las antiguas funciones, pero deberían reemplazarlas en sus nuevas versiones. PDFlib GmbH no dará soporte a cualquier problema causado por el uso de estas funciones obsoletas.

Tabla 1. Funciones obsoletas y sus reemplazos.

Antigua funciónReemplazo
pdf_put_image()Ya no se necesita.
pdf_execute_image()Ya no se necesita.
pdf_get_annotation()pdf_get_bookmark() utilizando los mismos parámetros.
pdf_get_font()pdf_get_value() pasando "font" como segundo parámetro.
pdf_get_fontsize()pdf_get_value() pasando "fontsize" como segundo parámetro.
pdf_get_fontname()pdf_get_parameter() pasando "fontname" como segundo parámetro.
pdf_set_info_creator()pdf_set_info() pasando "Creator" como segundo parámetro.
pdf_set_info_title()pdf_set_info() pasando "Title" como segundo parámetro.
pdf_set_info_subject()pdf_set_info() pasando "Subject" como segundo parámetro.
pdf_set_info_author()pdf_set_info() pasando "Author" como segundo parámetro.
pdf_set_info_keywords()pdf_set_info() pasando "Keywords" como segundo parámetro.
pdf_set_leading()pdf_set_value() pasando "leading" como segundo parámetro.
pdf_set_text_rendering()pdf_set_value() pasando "textrendering" como segundo parámetro.
pdf_set_text_rise()pdf_set_value() pasando "textrise" como segundo parámetro.
pdf_set_horiz_scaling()pdf_set_value() pasando "horizscaling" como segundo parámetro.
pdf_set_text_matrix()Ya no se necesita.
pdf_set_char_spacing()pdf_set_value() pasando "charspacing" como segundo parámetro.
pdf_set_word_spacing()pdf_set_value() pasando "wordspacing" como segundo parámetro.
pdf_set_transition()pdf_set_parameter() pasando "transition" como segundo parámetro.
pdf_open()pdf_new() más la subsecuente llamada de pdf_open_file()
pdf_set_font()pdf_findfont() más la subsecuente llamada de pdf_setfont()
pdf_set_duration()pdf_set_value() pasando "duration" como segundo parámetro.
pdf_open_gif()pdf_open_image_file() pasando "gif" como segundo parámetro.
pdf_open_jpeg()pdf_open_image_file() pasando "jpeg" como segundo parámetro.
pdf_open_tiff()pdf_open_image_file() pasando "tiff" como segundo parámetro.
pdf_open_png()pdf_open_image_file() pasando "png" como segundo parámetro.
pdf_get_image_width()pdf_get_value() pasando "imagewidth" como segundo parámetro y la imágen como tercer parámetro.
pdf_get_image_height()pdf_get_value() pasando "imageheight" como segundo parámetro y la imágen como tercer parámetro.

Ejemplos

La mayoría de las funciones son bastante fáciles de utilizar. La parte más difícil probablemente es la creación de un primer documento PDF. El siguiente ejemplo debería ayudar para comenzar. El ejemplo crea el archivo test.pdf en una página. La página contiene el texto "Times Roman outlined" en un contorno, con fuente de 30pt. El texto también está subrayado.

Ejemplo 1. Creando un documento PDF con PDFlib

<?php
$pdf
= pdf_new();
pdf_open_file($pdf, "test.pdf");
pdf_set_info($pdf, "Author", "Javier Tacon");
pdf_set_info($pdf, "Title", "Test for PHP wrapper of PDFlib 2.0");
pdf_set_info($pdf, "Creator", "See Author");
pdf_set_info($pdf, "Subject", "Testing");
pdf_begin_page($pdf, 595, 842);
pdf_add_outline($pdf, "Page 1");
$font = pdf_findfont($pdf, "Times New Roman", "winansi", 1);
pdf_setfont($pdf, $font, 10);
pdf_set_value($pdf, "textrendering", 1);
pdf_show_xy($pdf, "Times Roman outlined", 50, 750);
pdf_moveto($pdf, 50, 740);
pdf_lineto($pdf, 330, 740);
pdf_stroke($pdf);
pdf_end_page($pdf);
pdf_close($pdf);
pdf_delete($pdf);
echo
"<A HREF=getpdf.php>finished</A>";
?>
El script getpdf.php simplemente devuelve el documento pdf.

Ejemplo 2. Mostrando un documento PDF precalculado

<?php
$len
= filesize($filename);
header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=foo.pdf");
readfile($filename);
?>

La distrubución PDFlib contiene un ejemplo más complejo para crear un reloj analógico en una página. Aquí se utiliza el método de creación en memoria de PDFlib para no tener que crear un archivo temporal. El ejemplo se ha convertido a PHP desde uno de PDFlib (El mismo ejemplo está disponible en la documentación ClibPDF.)

Ejemplo 3. Ejemplo pdfclock de la distribución PDFlib

<?php
$radius
= 200;
$margin = 20;
$pagecount = 10;

$pdf = pdf_new();

if (!
pdf_open_file($pdf, "")) {
    echo
error;
    exit;
};

pdf_set_parameter($pdf, "warning", "true");

pdf_set_info($pdf, "Creator", "pdf_clock.php");
pdf_set_info($pdf, "Author", "Uwe Steinmann");
pdf_set_info($pdf, "Title", "Analog Clock");

while (
$pagecount-- > 0) {
    
pdf_begin_page($pdf, 2 * ($radius + $margin), 2 * ($radius + $margin));

    
pdf_set_parameter($pdf, "transition", "wipe");
    
pdf_set_value($pdf, "duration", 0.5);
  
    
pdf_translate($pdf, $radius + $margin, $radius + $margin);
    
pdf_save($pdf);
    
pdf_setrgbcolor($pdf, 0.0, 0.0, 1.0);

    
/* minute strokes */
    
pdf_setlinewidth($pdf, 2.0);
    for (
$alpha = 0; $alpha < 360; $alpha += 6) {
        
pdf_rotate($pdf, 6.0);
        
pdf_moveto($pdf, $radius, 0.0);
        
pdf_lineto($pdf, $radius-$margin/3, 0.0);
        
pdf_stroke($pdf);
    }

    
pdf_restore($pdf);
    
pdf_save($pdf);

    
/* 5 minute strokes */
    
pdf_setlinewidth($pdf, 3.0);
    for (
$alpha = 0; $alpha < 360; $alpha += 30) {
        
pdf_rotate($pdf, 30.0);
        
pdf_moveto($pdf, $radius, 0.0);
        
pdf_lineto($pdf, $radius-$margin, 0.0);
        
pdf_stroke($pdf);
    }

    
$ltime = getdate();

    
/* draw hour hand */
    
pdf_save($pdf);
    
pdf_rotate($pdf,-(($ltime['minutes']/60.0)+$ltime['hours']-3.0)*30.0);
    
pdf_moveto($pdf, -$radius/10, -$radius/20);
    
pdf_lineto($pdf, $radius/2, 0.0);
    
pdf_lineto($pdf, -$radius/10, $radius/20);
    
pdf_closepath($pdf);
    
pdf_fill($pdf);
    
pdf_restore($pdf);

    
/* draw minute hand */
    
pdf_save($pdf);
    
pdf_rotate($pdf,-(($ltime['seconds']/60.0)+$ltime['minutes']-15.0)*6.0);
    
pdf_moveto($pdf, -$radius/10, -$radius/20);
    
pdf_lineto($pdf, $radius * 0.8, 0.0);
    
pdf_lineto($pdf, -$radius/10, $radius/20);
    
pdf_closepath($pdf);
    
pdf_fill($pdf);
    
pdf_restore($pdf);

    
/* draw second hand */
    
pdf_setrgbcolor($pdf, 1.0, 0.0, 0.0);
    
pdf_setlinewidth($pdf, 2);
    
pdf_save($pdf);
    
pdf_rotate($pdf, -(($ltime['seconds'] - 15.0) * 6.0));
    
pdf_moveto($pdf, -$radius/5, 0.0);
    
pdf_lineto($pdf, $radius, 0.0);
    
pdf_stroke($pdf);
    
pdf_restore($pdf);

    
/* draw little circle at center */
    
pdf_circle($pdf, 0, 0, $radius/30);
    
pdf_fill($pdf);

    
pdf_restore($pdf);

    
pdf_end_page($pdf);

    
# to see some difference
    
sleep(1);
}

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=foo.pdf");
echo
$buf;

pdf_delete($pdf);
?>

Ver también

Nota: Una alternativa de módulo PHP para la creación de documentos PDF basados en FastIO's ClibPDF está disponible. Mirar la sección ClibPDF para más detalles. Tener en cuenta que ClibPDF tiene alguna diferencia con PDFlib.

Tabla de contenidos
pdf_activate_item -- Activate structure element or other content item
pdf_add_annotation -- Adds annotation
pdf_add_bookmark2 -- Add bookmark for current page [deprecated]
pdf_add_bookmark -- Add bookmark for current page [deprecated]
pdf_add_launchlink -- Add launch annotation for current page [deprecated]
pdf_add_locallink -- Add link annotation for current page [deprecated]
pdf_add_nameddest -- Create named destination
pdf_add_note2 -- Set annotation for current page [deprecated]
pdf_add_note -- Set annotation for current page [deprecated]
PDF_add_outline -- Adds bookmark for current page
pdf_add_pdflink -- Add file link annotation for current page [deprecated]
pdf_add_thumbnail -- Add thumbnail for current page
pdf_add_weblink -- Add weblink for current page [deprecated]
PDF_arc -- Draws an arc
pdf_arcn -- Draw a clockwise circular arc segment
pdf_attach_file2 -- Add file attachment for current page [deprecated]
pdf_attach_file -- Add file attachment for current page [deprecated]
pdf_begin_document -- Create new PDF file
pdf_begin_font -- Start a Type 3 font definition
pdf_begin_glyph -- Start glyph definition for Type 3 font
pdf_begin_item -- Open structure element or other content item
pdf_begin_layer -- Start layer
pdf_begin_page_ext -- Start new page
PDF_begin_page -- Starts new page
pdf_begin_pattern -- Start pattern definition
pdf_begin_template -- Start template definition
PDF_circle -- Draws a circle
PDF_clip -- Clips to current path
PDF_close_image -- Closes an image
pdf_close_pdi_page --  Close the page handle
pdf_close_pdi --  Close the input PDF document
PDF_close -- Closes a pdf document
PDF_closepath_fill_stroke -- Closes, fills and strokes current path
PDF_closepath_stroke -- Closes path and draws line along path
PDF_closepath -- Closes path
pdf_concat -- Concatenate a matrix to the CTM
PDF_continue_text -- Outputs text in next line
pdf_create_action -- Create action for objects or events
pdf_create_annotation -- Create rectangular annotation
pdf_create_bookmark -- Create bookmark
pdf_create_field -- Create form field
pdf_create_fieldgroup -- Create form field group
pdf_create_gstate -- Create graphics state object
pdf_create_pvf -- Create PDFlib virtual file
pdf_create_textflow -- Create textflow object
PDF_curveto -- Draws a curve
pdf_define_layer -- Create layer definition
pdf_delete_pvf -- Delete PDFlib virtual file
pdf_delete_textflow -- Delete textflow object
pdf_delete -- Delete PDFlib object
pdf_encoding_set_char -- Add glyph name and/or Unicode value
pdf_end_document -- Close PDF file
pdf_end_font -- Terminate Type 3 font definition
pdf_end_glyph -- Terminate glyph definition for Type 3 font
pdf_end_item -- Close structure element or other content item
pdf_end_layer -- Deactivate all active layers
pdf_end_page_ext -- Finish page
PDF_end_page -- Ends a page
pdf_end_pattern -- Finish pattern
pdf_end_template -- Finish template
PDF_endpath -- Ends current path
pdf_fill_imageblock -- Fill image block with variable data
pdf_fill_pdfblock -- Fill image block with variable data
PDF_fill_stroke -- Fills and strokes current path
pdf_fill_textblock -- Fill text block with variable data
PDF_fill -- Fills current path
pdf_findfont -- Prepare font for later use [deprecated]
pdf_fit_image -- Place image or template
pdf_fit_pdi_page -- Place imported PDF page
pdf_fit_textflow -- Format textflow in rectangular area
pdf_fit_textline -- Place single line of text
pdf_get_apiname -- Get name of unsuccessfull API function
pdf_get_buffer -- Get PDF output buffer
pdf_get_errmsg -- Get error text
pdf_get_errnum -- Get error number
pdf_get_font -- Get font [deprecated]
pdf_get_fontname -- Get font name [deprecated]
pdf_get_fontsize -- Font handling [deprecated]
pdf_get_image_height -- Get image height [deprecated]
pdf_get_image_width -- Get image width [deprecated]
pdf_get_majorversion -- Get major version number [deprecated]
pdf_get_minorversion -- Get minor version number [deprecated]
PDF_get_parameter -- Gets certain parameters
pdf_get_pdi_parameter -- Get PDI string parameter
pdf_get_pdi_value -- Get PDI numerical parameter
PDF_get_value -- Gets certain numerical value
pdf_info_textflow -- Query textflow state
pdf_initgraphics -- Reset graphic state
PDF_lineto -- Draws a line
pdf_load_font -- Search and prepare font
pdf_load_iccprofile -- Search and prepare ICC profile
pdf_load_image -- Open image file
pdf_makespotcolor -- Make spot color
PDF_moveto -- Sets current point
pdf_new -- Create PDFlib object
pdf_open_ccitt -- Open raw CCITT image [deprecated]
pdf_open_file -- Create PDF file [deprecated]
PDF_open_gif -- Opens a GIF image
pdf_open_image_file -- Read image from file [deprecated]
pdf_open_image -- Use image data [deprecated]
PDF_open_jpeg -- Opens a JPEG image
PDF_open_memory_image -- Opens an image created with PHP's image functions
pdf_open_pdi_page --  Prepare a page
pdf_open_pdi -- Open PDF file
pdf_open_tiff -- Open TIFF image [deprecated]
PDF_place_image -- Places an image on the page
pdf_place_pdi_page -- Place PDF page [deprecated]
pdf_process_pdi -- Process imported PDF document
PDF_rect -- Draws a rectangle
PDF_restore -- Restores formerly saved environment
pdf_resume_page -- Resume page
PDF_rotate -- Sets rotation
PDF_save -- Saves the current environment
PDF_scale -- Sets scaling
PDF_set_border_color -- Sets color of border around links and annotations
PDF_set_border_dash -- Sets dash style of border around links and annotations
PDF_set_border_style -- Sets style of border around links and annotations
PDF_set_char_spacing -- Sets character spacing
PDF_set_duration -- Sets duration between pages
pdf_set_gstate -- Activate graphics state object
PDF_set_horiz_scaling -- Sets horizontal scaling of text
pdf_set_info_author --  Fill the author document info field [deprecated]
pdf_set_info_creator --  Fill the creator document info field [deprecated]
pdf_set_info_keywords --  Fill the keywords document info field [deprecated]
pdf_set_info_subject --  Fill the subject document info field [deprecated]
pdf_set_info_title --  Fill the title document info field [deprecated]
PDF_set_info -- Fills a field of the document information
pdf_set_layer_dependency -- Define relationships among layers
PDF_set_leading -- Sets distance between text lines
PDF_set_parameter -- Sets certain parameters
PDF_set_text_matrix -- Sets the text matrix
PDF_set_text_pos -- Sets text position
PDF_set_text_rendering -- Determines how text is rendered
PDF_set_text_rise -- Sets the text rise
PDF_set_value -- Sets certain numerical value
PDF_set_word_spacing -- Sets spacing between words
pdf_setcolor -- Set fill and stroke color
PDF_setdash -- Sets dash pattern
pdf_setdashpattern -- Set dash pattern
PDF_setflat -- Sets flatness
pdf_setfont -- Set font
PDF_setgray_fill -- Sets filling color to gray value
PDF_setgray_stroke -- Sets drawing color to gray value
PDF_setgray -- Sets drawing and filling color to gray value
PDF_setlinecap -- Sets linecap parameter
PDF_setlinejoin -- Sets linejoin parameter
PDF_setlinewidth -- Sets line width
pdf_setmatrix -- Set current transformation matrix
PDF_setmiterlimit -- Sets miter limit
pdf_setpolydash -- Set complicated dash pattern [deprecated]
PDF_setrgbcolor_fill -- Sets filling color to rgb color value
PDF_setrgbcolor_stroke -- Sets drawing color to rgb color value
PDF_setrgbcolor -- Sets drawing and filling color to rgb color value
pdf_shading_pattern -- Define shading pattern
pdf_shading -- Define blend
pdf_shfill -- Fill area with shading
PDF_show_boxed -- Output text in a box
PDF_show_xy -- Output text at given position
PDF_show -- Output text at current position
PDF_skew -- Skews the coordinate system
PDF_stringwidth -- Returns width of text using current font
PDF_stroke -- Draws line along path
pdf_suspend_page -- Suspend page
PDF_translate -- Sets origin of coordinate system
pdf_utf16_to_utf8 -- Convert string from UTF-16 to UTF-8
pdf_utf8_to_utf16 -- Convert string from UTF-8 to UTF-16
pdf_xshow -- Output text at current position