generar pdf con sfDomPDF

437 views
Skip to first unread message

gonzakpo

unread,
May 27, 2011, 9:11:55 AM5/27/11
to symfony-es
no logro que funcione descargue el tgz lo descomprimi en plugin lo
cargue en ProjectConfiguration y en el settings modifique el
executeIndex y al entrar me tira el error:
500 | Internal Server Error | DOMPDF_Exception
Unable to find a suitable font replacement for: 'serif'
alguien podra ayudarme o que me recomiendan
version symfony 1.4

Arufe

unread,
May 27, 2011, 11:22:24 AM5/27/11
to symfony-es
Me pudieran explicar como generar con sfDomPDFPlugin, ya tengo la
libreria dompdf pero com es la configuracion, para generar los pdf,
saludos !!!

gonzakpo

unread,
May 27, 2011, 11:34:12 AM5/27/11
to symfony-es

Arufe

unread,
May 27, 2011, 11:59:38 AM5/27/11
to symfony-es
Gonzakpo gracias por la ayuda colega pero soy cubano y desde aka de
cuba no podemos entrar a code.google.com esta restringido para nuestro
pais, tiens otra via de ayurame, te lo agradeceria colega, saludos !!!

On May 27, 11:34 am, gonzakpo <gon...@gmail.com> wrote:
> fijate si esto te ayudahttp://code.google.com/p/dompdf/wiki/Introduction?tm=6

Gabriel Toledo

unread,
May 27, 2011, 12:47:48 PM5/27/11
to symfo...@googlegroups.com
arufe: te paso la parte de la instalacion, la verdad que no le he visto, espero que te sirva.

Requirements

  • PHP 5.0+ with the DOM extension enabled. Note that the domxml PECL extension conflicts with the DOM extension and must be disabled.
  • Some fonts. PDFs internally support Helvetica, Times-Roman, Courier & Zapf-Dingbats, but if you wish to use other fonts or Unicode charsets you will need to install some fonts. dompdf supports the same fonts as the underlying PDF backends: Type 1 (.pfb with the corresponding .afm) and TrueType (.ttf). At the minimum, you should probably have the Microsoft core fonts (now available at: http://corefonts.sourceforge.net/). See below for font installation instructions.
  • ttf2pt1 (available at http://ttf2pt1.sourceforge.net) is required to install new ttf fonts when using the CPDF backend.

Installation

  1. Untar/unzip the source package in a directory accessible by your webserver.
  2. Edit dompdf_config.custom.inc.php (in version 0.6) or dompdf_config.custom.inc.php (version 0.5) to fit your installation. If you leave the DOMPDF_PDF_BACKEND setting at 'auto' dompdf will use the bundled R&OS CPDF class.
  3. Give your webserver write permission on the path specified in DOMPDF_FONT_DIR (lib/fonts by default). Under *nix, ideally you can make the webserver group the owner of this directory and give the directory group write permissions. For example, on Debian systems, Apache runs as the www-data user:
$ chgrp www-data lib/fonts
$ chmod g+w lib/fonts

If your user is not a member of the www-data group or you do not have root privileges, you can make the directory world writable and set the sticky bit:

$ chmod 1777 lib/fonts

Configuration tool

Since 0.6 beta 2, dompdf has a configuration/helper page available at www/setup.php. This page will tell you if an extension is missing, and will check if the temp path is writable. It will also tell you what fonts are installed for the CPDF backend (the one used by default).

Font Installation

Note for all platforms

PDFs include support by default for Helvetica, Times-Roman, Courier and Zapf-Dingbats. You do not need to install any font files if you wish to use these fonts. This has the advantage of reducing the size of the resulting PDF, because additional fonts must be embedded in the PDF.

Also, if you have problems installing the font files, you can try and use the distributed dompdf_font_family_cache.dist file in lib/fonts. Copy this file to lib/fonts/dompdf_font_family_cache and edit it directly to match the files present in your lib/fonts directory.

Linux/Unix

The load_font.php utility installs and converts TrueType fonts for use with dompdf. Since CSS uses the concept of font families (i.e. the same face can be rendered in different styles & weights) dompdf needs to know which actual font files belong to which font family and which style. For example, the Microsoft core font pack includes the files !Verdana.ttf, Verdana_Italic.ttf, Verdana_Bold.ttf and Verdana_Bold_Italic.ttf. All four of these files need to be present in the dompdf font directory (DOMPDF_FONT_DIR), and entries need to be made in the dompdf_font_family_cache file.

Given the font family name and the path to the 'normal' font face file (Verdana.ttf, in our example), load_font.php will search for the bold, italic and bold italic font face files in the same directory as the specified file. It searches for files with the same base name followed by 'Bold', 'B', or 'b' (similarly for italic and bold italic). If it can not find the correct files, you can specify them on the command line.

In addition to copying the files to the dompdf font directory, it also generates .afm files. The R&OS CPDF class requires both the ttf file and an afm file, which describes glyph metrics. The afm file is generated using the ttf2pt1 utlity (available at http://ttf2pt1.sourceforge.net). If you are using the PDFLib backend, you will not need to create afm files for the fonts.

load_font.php usage:

$ ./load_font.php font-family n_file [b_file] [i_file] [bi_file]

font_family - the name of the font, e.g. Verdana, 'Times New Roman', monospace, sans-serif.
n_file - the .pfb or .ttf file for the normal, non-bold, non-italic face of the font.
{b|i|bi}file - the files for each of the respective (bold, italic, bold-italic) faces.

Examples:

$ ./load_font.php silkscreen /usr/share/fonts/truetype/slkscr.ttf

$
./load_font.php 'Times New Roman' /mnt/c_drive/WINDOWS/Fonts/times.ttf

$ php
-f load_font.php -- sans-serif /home/dude_mcbacon/myfonts/Verdana.ttf \
                                     
/home/dude_mcbacon/myfonts/V_Bold.ttf

Windows

(Note I don't have a windows test box at the moment, so these instructions may not work... If someone has tried this and has any suggestions for me, please send me an email!)

Read the Linux/Unix section above first, as most of it applies. The main difference is the ttf2pt1 utility. Fortunately, there is a windows version, available at http://gnuwin32.sourceforge.net/packages/ttf2pt1.htm. You will have to edit your dompdf_config.inc.php file to point to the path where you installed ttf2pt1.

You will also need the cli version of PHP in order to execute load_font.php, however it's usage is the same (see the last example above).




--
Has recibido este mensaje porque estás suscrito al grupo "symfony-es" de Grupos de Google.
Para publicar una entrada en este grupo, envía un correo electrónico a symfo...@googlegroups.com.
Para anular tu suscripción a este grupo, envía un correo electrónico a symfony-es+...@googlegroups.com
Para tener acceso a más opciones, visita el grupo en http://groups.google.com/group/symfony-es?hl=es.




--
Ing. Gabriel Toledo - Cel: 216 - 15 460 9360

Gabriel Toledo

unread,
May 27, 2011, 12:51:16 PM5/27/11
to symfo...@googlegroups.com
tambien te mando esto.

Usage

Using the dompdf class directly

Using the dompdf class directly is fairly straightforward:

<?php
require_once
("dompdf_config.inc.php");

$html
=
 
'<html><body>'.
 
'<p>Put your html here, or generate it with your favourite '.
 
'templating system.</p>'.
 
'</body></html>';

$dompdf
= new DOMPDF();
$dompdf
->load_html($html);
$dompdf
->render();
$dompdf
->stream("sample.pdf");

?>

Below is a summary of the methods available in the dompdf class.

Method summary

The methods available in the instances of the DOMPDF class are :

load_html

Loads an HTML string. Parse errors are stored in the global array $_dompdf_warnings.
Arguments:
  • string $str: HTML text to load
  • string[optional] $encoding: encoding, if not provided, dompdf will try to find it.

load_html_file

Loads an HTML file. Parse errors are stored in the global array $_dompdf_warnings.
Arguments:
  • string $file: a filename or url to load

output

Returns the PDF as a string. The file will open a download dialog by default. The options parameter controls the output.
Arguments:
  • array $options: accepted options are:
    • compress => 1 or 0 - apply content stream compression, this is on (1) by default

render

Renders the HTML to PDF.
Arguments: none.

set_base_path

Sets the base path, used for external stylesheets and images.
Arguments:
  • string $path: The base path to be used when resolving external resources URLs.

set_paper

Sets the paper size & orientation
Arguments:

stream

Streams the PDF to the client. The file will open a download dialog by default. The options parameter controls the output.
Arguments:
  • string $filename: the name of the streamed file
  • array $options: accepted options are:
    • 'compress' = > 1 or 0 - apply content stream compression, this is on (1) by default
    • 'Attachment' => 1 or 0 - if 1, force the browser to open a download dialog, on (1) by default

Invoking dompdf via the web

The dompdf.php script is not intended to be an interactive page. It receives input parameters via $_GET and can stream a PDF directly to the browser. This makes it possible to embed links to the script in a page that look like static PDF links, but are actually dynamically generated. This method is also useful as a redirection target.

dompdf.php accepts the following $_GET variables:


input_file required a rawurlencoded() path to the HTML file to process. Remote files (http/ftp) are supported if fopen wrappers are enabled.
paper optional the paper size. Defaults to 'letter' (unless the default has been changed in dompdf_config.inc.php). See include/pdf_adapter.cls.php, or invoke dompdf.php on the command line with the -l switch for accepted paper sizes.
orientation optional 'portrait' or 'landscape'. Defaults to 'portrait'.
base_path optional the base path to use when resolving relative links (images or CSS files). Defaults to the directory containing the file being accessed. (This option is useful for pointing dompdf at your CSS files even though the HTML file may be elsewhere.)
output_file optional the rawurlencoded() name of the output file. Defaults to 'dompdf_out.pdf'. Deprecated in 0.6, forced to "dompdf_out.pdf"
save_file optional If present (i.e. isset($_GET["save_file"])), output_file is saved locally, Otherwise the file is streamed directly to the client. Deprecated in 0.6, forced to false

One technique for generating dynamic PDFs is to generate dynamic HTML as you normally would, except instead of displaying the output to the browser, you use output buffering and write the output to a temporary file. Once this file is saved, you redirect to the dompdf.php script.

If you use a templating engine like Smarty, you can simply do:

<?php
$tmpfile
= tempnam("/tmp", "dompdf_");
file_put_contents
($tmpfile, $smarty->fetch()); // Replace $smarty->fetch()
                                               
// with your HTML string

$url
= "dompdf.php?input_file=" . rawurlencode($tmpfile) .
       
"&paper=letter&output_file=" . rawurlencode("My Fancy PDF.pdf");

header
("Location: http://" . $_SERVER["HTTP_HOST"] . "/$url");
?>

If you use any stylesheets, you may need to provide the base_path option to tell dompdf where to look for them, as they are not likely relative to /tmp ;).

Invoking dompdf via the command line

You can execute dompdf.php using the following command:

$ php -f dompdf.php -- [options]

(If you find yourself using only the cli interface, you can add #!/usr/bin/php as the first line of dompdf.php to invoke dompdf.php directly.)

dompdf.php is invoked as follows:

$ ./dompdf.php [options] html_file

html_file can be a filename, a url if fopen_wrappers are enabled, or the '-' character to read from standard input.

-h Show a brief help message
-l list available paper sizes
-p size paper size; something like 'letter', 'A4', 'legal', etc. Thee default is 'letter'
-o orientation either 'portrait' or 'landscape'. Default is 'portrait'.
-b path the base path to use when resolving relative links (images or CSS files). Default is the directory of html_file.
-f file the output filename. Default is the input [html_file].pdf.
-v verbose: display html parsing warnings and file not found errors.
-d very verbose: display oodles of debugging output; every frame in the tree is printed to stdout.

Examples:

$ php -f dompdf.php -- my_resume.html
$
./dompdf.php -b /var/www/ ./web_stuff/index.html
$ echo
'<html><body>Hello world!</body></html>' | ./dompdf.php -

Inline PHP support

dompdf supports two varieties of inline PHP code. All PHP evaluation is controlled by the DOMPDF_ENABLE_PHP configuration option. If it is set to false, then no PHP code is executed. Otherwise, PHP is evaluated in two passes:

The first pass is useful for inserting dynamic data into your PDF. You can do this by embedding <?php ?> tags in your HTML file, as you would in a normal .php file. This code is evaluated prior to parsing the HTML, so you can echo any text or markup and it will appear in the rendered PDF.

The second pass is useful for performing drawing operations on the underlying PDF class directly. You can do this by embedding PHP code within <script type="text/php"> </script> tags. This code is evaluated during the rendering phase and you have access to a few internal objects and operations. In particular, the $pdf variable is the current instance of Canvas. Using this object, you can write and draw directly on the current page. Using the Canvas::open_object(), Canvas::close_object() and Canvas::add_object() methods, you can create text and drawing objects that appear on every page of your PDF (useful for headers & footers).

The following variables are defined for you during the second pass of PHP execution:

$pdf the current instance of Canvas
$PAGE_NUM the current page number
$PAGE_COUNT the total number of pages in the document

For more complete documentation of the Canvas API, see the API documentation.











2011/5/27 Gabriel Toledo <gabrielan...@gmail.com>

david becerra montellano

unread,
May 27, 2011, 12:53:59 PM5/27/11
to symfo...@googlegroups.com
Posiblemente no sea la respuestas que buscas, pero existe una libreria excelente derivado de FPDF, llamado TCPDF. Con el puedes hacer muchas cosas, embeber css,html y hasta js. La verdad que a mi me a ayudado mucho, estube realizando un sistema de facturacion y con esta libreria logre hacer mis plantillas de facturacion tal y como las queria.

Joomla es unos de los CMS que mas utiliza esa libreria.

Saludos.

--
Has recibido este mensaje porque estás suscrito al grupo "symfony-es" de Grupos de Google.
Para publicar una entrada en este grupo, envía un correo electrónico a symfo...@googlegroups.com.
Para anular tu suscripción a este grupo, envía un correo electrónico a symfony-es+...@googlegroups.com
Para tener acceso a más opciones, visita el grupo en http://groups.google.com/group/symfony-es?hl=es.




--
debide beserura monterurano

Jonnatan Oyarzún

unread,
May 27, 2011, 1:00:48 PM5/27/11
to symfo...@googlegroups.com
Arufe

Sé que es off topic pero me sorprende el nivel de represión que tiene tu país, soy chileno y por estar en el mismo territorio conozco mas o menos la situación de cuba pero aun así no dejo de sorprenderme.

Saludos y suerte

2011/5/27 Arufe <juankit...@gmail.com>
--
Has recibido este mensaje porque estás suscrito al grupo "symfony-es" de Grupos de Google.
Para publicar una entrada en este grupo, envía un correo electrónico a symfo...@googlegroups.com.
Para anular tu suscripción a este grupo, envía un correo electrónico a symfony-es+...@googlegroups.com
Para tener acceso a más opciones, visita el grupo en http://groups.google.com/group/symfony-es?hl=es.




--
Jonnatan Oyarzún
Estudiante Ingeniería Civil Informática
Universidad de Santiago de Chile

Julian Lasso

unread,
May 27, 2011, 2:33:31 PM5/27/11
to symfo...@googlegroups.com
A ver aver, como así?
Sé que Arufe es de Cuba pero...... eso que tiene que ver con que Arufe pregunte tanto?
(Arufe es sin ofender ¿ok? estoy es desinformado)

-- 
Julian Lasso
Enviado con Sparrow

Arufe

unread,
May 30, 2011, 9:43:57 AM5/30/11
to symfony-es
Julian pues pregunto tanto porque me gusta tener bien claro las cosas
y como me estoi adentrando en el mundo de symfony y quisiera estar
bien informado y como estoi desarrollando un proyecto en symfony hay
cosas que no tengo muy claras, pero creo q los foros son para
preguntar, no ???...

On May 27, 2:33 pm, Julian Lasso <julian.la...@gmail.com> wrote:
> A ver aver, como así?
> Sé que Arufe es de Cuba pero...... eso que tiene que ver con que Arufe pregunte tanto?
> (Arufe es sin ofender ¿ok? estoy es desinformado)
>
> --
> Julian Lasso
> Enviado con Sparrow (http://www.sparrowmailapp.com/?sig)
>
> El viernes 27 de mayo de 2011 a las 12:00, Jonnatan Oyarzún escribió:
>
> > Arufe
>
> > Sé que es off topic pero me sorprende el nivel de represión que tiene tu país, soy chileno y por estar en el mismo territorio conozco mas o menos la situación de cuba pero aun así no dejo de sorprenderme.
>
> > Saludos y suerte
>
> > 2011/5/27 Arufe <juankito.ar...@gmail.com (mailto:juankito.ar...@gmail.com)>
> > >  Gonzakpo gracias por la ayuda colega pero soy cubano y desde aka de
> > >  cuba no podemos entrar a code.google.com (http://code.google.com) esta restringido para nuestro
> > >  pais, tiens otra via de ayurame, te lo agradeceria colega, saludos !!!
>
> > >  On May 27, 11:34 am, gonzakpo <gon...@gmail.com (mailto:gon...@gmail.com)> wrote:
> > > > fijate si esto te ayudahttp://code.google.com/p/dompdf/wiki/Introduction?tm=6
>
> > >  --
> > >  Has recibido este mensaje porque estás suscrito al grupo "symfony-es" de Grupos de Google.
> > >  Para publicar una entrada en este grupo, envía un correo electrónico a symfo...@googlegroups.com (mailto:symfo...@googlegroups.com).
> > >  Para anular tu suscripción a este grupo, envía un correo electrónico a symfony-es+...@googlegroups.com (mailto:symfony-es%2Bunsu...@googlegroups.com)
> > >  Para tener acceso a más opciones, visita el grupo enhttp://groups.google.com/group/symfony-es?hl=es.
>
> > --
> > Jonnatan Oyarzún
> > Estudiante Ingeniería Civil Informática
> > Universidad de Santiago de Chile
> >  --
> >  Has recibido este mensaje porque estás suscrito al grupo "symfony-es" de Grupos de Google.
> >  Para publicar una entrada en este grupo, envía un correo electrónico a symfo...@googlegroups.com (mailto:symfo...@googlegroups.com).
> >  Para anular tu suscripción a este grupo, envía un correo electrónico a symfony-es+...@googlegroups.com (mailto:symfony-es+...@googlegroups.com)

Arufe

unread,
May 30, 2011, 9:55:06 AM5/30/11
to symfony-es
david tengo conocimiento del plugin TCPDFPlugin de symfony pero no se
como configurarlo, o sea por ejemplo q en la esquina de mi tabla me
salga unna imagen de pdf y cuando de click en ella me salga para
guardar el archivo o una nueva ventana mostrandome el archivo, espero
puedas ayudarme, saludos !!!

david becerra montellano

unread,
May 30, 2011, 10:11:04 AM5/30/11
to symfo...@googlegroups.com
Mmm a ver si entiendo, quieres poner una imagen que te redireccione al archivo pdf que vas a crear dinamicamente?
<table>
<tr>
<td>Empleados</td>
<td><a href="procesar_pdf.php" >imagen PDF (icono PDF)</a></td>
</tr>
</table>

Procesar_pdf.php es en donde creas tu archivo pdf con la libreria TCPDF, realmente tienes que ser un poco mas claro, porque al momento de recibir datos se pueden hacer de muchas maneras, pero siempre te llevan a un archivo. Por ejemplo puede recibir por numero de id mediante el methodo GET o con un campo hidden si se envian datos de una BD.


Si aun no tienes claros algunos conceptos de php, te invito a visitar un buen blog de programacion php www.cesarcancino.com, tiene 26 videotutoriales de PHP estructurado y ahorita ya va en el videotutorial 36 de PHP POO, para entender bien a un framework hay que entender bien PHP5 Programacion orientada a objetos y ahora ya esta en su mas recienten version PHP6


Saludos y exitos, espero la info te pueda servir de ayuda.

--
Has recibido este mensaje porque estás suscrito al grupo "symfony-es" de Grupos de Google.
Para publicar una entrada en este grupo, envía un correo electrónico a symfo...@googlegroups.com.
Para anular tu suscripción a este grupo, envía un correo electrónico a symfony-es+...@googlegroups.com
Para tener acceso a más opciones, visita el grupo en http://groups.google.com/group/symfony-es?hl=es.




--
debide beserura monterurano

Arufe

unread,
May 30, 2011, 10:26:28 AM5/30/11
to symfony-es
David gracias nuevamente colega, mira te explico mas completo,
necesito filtrar los datos de mi sistema en en frontend, por ejemplo
las publicaciones segun el año, el autor o el nombre, para ello he
generado un modulo de tipo admin sin los batch_action y demas
elementos administrativos o sea solo lo deje con la parte de filtrar y
mostrar, entonces q necesito q cuando filtre mis datos pueda exportar
a pdf esos resultados, entinedes ???...espero puedas ayudarme,
saludos !!!
Reply all
Reply to author
Forward
0 new messages