My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
Usage  

Featured, Phase-Implementation
Updated Jan 18, 2011 by fabien.menager

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.

Comment by abhijeet...@gmail.com, Aug 11, 2009

Thanks for The Code......Gr8 job .....

Comment by cubezero...@gmail.com, Oct 29, 2009

http://www.digitaljunkies.ca site is not available long time and archive with dompdf does not contain offline documentation as well as no other places in the internet to see docs. It's really bad that you leave such good library without any support or backup. :(

Comment by project member eclecticgeek@gmail.com, Oct 29, 2009

You can find a copy of the original documentation at http://eclecticgeek.com/dompdf/docs/

This documentation is from the 0.5.1 release, which is the most current available at present. We'll update the documentation when we get closer to a final version of 0.6.0.

Comment by david.le...@gmail.com, Oct 29, 2009

Where we can get the doc for the api ? I want to add a simple footer :(

Comment by project member eclecticgeek@gmail.com, Oct 29, 2009

Samples of creating headers/footers are available on the FAQ. Most but not all the available functions available are shown under the questions "Is there a way to add headers and footers or page numbers?" and "How can I add an image to a header or footer on every page?" http://code.google.com/p/dompdf/wiki/FAQ

Currently you can only find the full API documentation on digitaljunkies.ca. Until Benj's site comes back up it's not available elsewhere. I believe the API documentation was created using PHPDocumentor so when I get a chance I'll see about regenerating it and posting it to eclecticgeek.com. However, it should be noted that the functionality available to inline scripts is a subset of the full API, and you can't access the PDF functions through the object directly.

When we're ready to release the next revision we'll add a more detailed page that covers the capabilities available with inline scripts.

Comment by vanleerd...@gmail.com, Nov 9, 2009

When will digitaljunkies.ca come back? This is redicilous...

Comment by project member eclecticgeek@gmail.com, Nov 9, 2009

@vanleerdamwebsolutions: It is my understanding the Benj has less time to devote to this project than he used to. As such you should consider the documentation here to be the official documentation. The information available on this site will be the most up-to-date as DOMPDF is developed further. Everything that was available on digitaljunkies.ca can either be found here or, in the case of the usage and api documentation, on my site: http://eclecticgeek.com/dompdf/docs/

If there's any other information you need please post a query to the support group: http://groups.google.com/group/dompdf

Comment by krzyszto...@gmail.com, Jan 20, 2010

Great job :) Big THX!!

Comment by saso.fil...@gmail.com, Feb 16, 2010

Hay, great sw! How is it possible to add background to page (image or other PDF) ? Can you elaborate on font adding (Tahoma, for example), or do some php cli tool to help with adding TTF fonts?

Comment by project member eclecticgeek@gmail.com, Feb 16, 2010

@saso.filipovic: Can you post your questions to the support group? We'll do our best to answer you there. http://groups.google.com/group/dompdf

Comment by lastboyo...@gmail.com, Dec 8, 2010

Have any solution for japanese text? All i got is weird characters instead of Japanese text on output...

Comment by project member eclecticgeek@gmail.com, Dec 9, 2010

@lastboyofsiberspace: Working with non-ASCII characters can be tricky. You need a font that supports your characters and DOMPDF 0.6.0. Post your question to the support group and we'll do our best to answer you there. http://groups.google.com/group/dompdf

Comment by Funkyami...@gmail.com, Mar 21, 2011

fab work ....

Comment by pdoli...@gmail.com, Apr 12, 2011

I'm trying to add IMAGE to footer and then TEXT placed over that image. The problem is that the text is hidden behind the image. Is there a way to bring the text to the front? Thanks.

Comment by project member eclecticgeek@gmail.com, May 6, 2011

@pdolinaj: This may be due to the order the content is placed in the document. If you haven't already, please ask your question on the support group: http://groups.google.com/group/dompdf

Comment by jamesmeh...@gmail.com, Jun 29, 2011

Wow... amazing script! Thanks for your work. Can you provide some comments / docs to your 'Pages' example? Not sure what you're doing with the js width and height in that example. I have about 80 html tables (user profiles) that I would like to put in one giant php string and output to pdf; having each table on it's own page.. so the final product would be an 80 page pdf. Ideas?

Comment by project member eclecticgeek@gmail.com, Jul 6, 2011

@jamesmehorter you'll get a better response from the support forum. The short answer is to add a page break in your HTML before each table, e.g.:

<div style="page-break-before: always;"></div>

Comment by DeepC...@gmail.com, Jul 21, 2011

Great project! I'm using it on a project to generate contracts in pdf format, it works perfect! Now I would like automatic save the file before it prompt to me, is that possible?

Comment by project member eclecticgeek@gmail.com, Jul 21, 2011

@DeepCell? use $dompdf->output() in conjunction with file_put_contents() to save the file, then call $dompdf->stream() to send it off to the web browser. Or, if you're saving to a web accessible directory, point to the saved file rather than use $dompdf->stream()

Comment by leifont@gmail.com, Oct 27, 2011

Very nice! I've started using R&OS class, but needed to translate html tags. ¿Is there any way to just get the translated HTML to \"pdf language\"? I'm doing some formating using R&OS methods like setColor() and filledRectangle().

Thanks in advice.

Comment by project member eclecticgeek@gmail.com, Oct 27, 2011

@leifont not sure what you mean. Can you explain more over at the support forum: https://groups.google.com/forum/#!forum/dompdf

Comment by mahmoudz...@gmail.com, Nov 23, 2011

How can I add a button to convert a current web page to PDF, is that easy?

Comment by project member eclecticgeek@gmail.com, Nov 28, 2011

@mahmoudzadah it can be as simple or complex as you want to make it. Post your question on the support forum and we'll see if we can help you out: https://groups.google.com/forum/#!forum/dompdf

Comment by ashusaxe...@gmail.com, Jan 9, 2012

How Can I add page header in each page saying "PAGE NUMBER/PAGE COUNT"? although I have tried following code but it does not work:

// $dompdf = new DOMPDF();

$canvas = $dompdf->get_canvas(); $font = Font_Metrics?::get_font("helvetica", "bold");

// the same call as in my previous example $canvas->page_text(72, 18, "Header: {PAGE_NUM} of {PAGE_COUNT}", $font, 6, array(0,0,0));

$dompdf->load_html($POST["html"]); $dompdf->set_paper($POST["paper"], $POST["orientation"]); $dompdf->render();

$dompdf->stream("dompdf_out.pdf"); //

The above code give me Error "Fatal error: Call to a member function page_text() on a non-object"

Anybody please help!

Thanks Ashu

Comment by project member eclecticgeek@gmail.com, Jan 10, 2012

@ashusaxena.mca script to generate a header should be included as part of the body of the HTML document.

Re-post your question on the support forum and we'll see if we can help you out: http://groups.google.com/group/dompdf

Comment by drew.bor...@gmail.com, Feb 5, 2012

Installed. All images with absolute paths get red x's. Tried a million things. No matter what, I get red xs instead of images.

Comment by project member eclecticgeek@gmail.com, Feb 6, 2012

@drew.borland if you need help please post to the support forum: http://groups.google.com/group/dompdf

Comment by BillalMa...@gmail.com, Mar 1, 2012

Can some one tell me if domPDF supports PDF templates? I want to load a PDF file as template and fill the empty places using X,Y coordinates. This is helpful when I need to fill a form and I don't want to waste time in making a ditto copy of that PDF form in HTML. I'll be thankful if some gives a sample code along with explanation. Thanx.

Comment by jpar...@sigmasolve.net, Apr 5, 2012

Use "ini_set('magic_quotes_runtime', 0);" in place of set_magic_quotes_runtime(0); and "ini_set('magic_quotes_runtime', $tmp);" in place of set_magic_quotes_runtime($tmp); as set_magic_quotes_runtime() is deprecated w.e.f php 5.3.0 in lib/class.pdf.php

Comment by Emad.had...@gmail.com, Apr 17, 2012

Thang You Very much

Comment by curzio.d...@gmail.com, Apr 24, 2012

Page numeration using inline php,

requirements are:

  • bottom-right corner,
  • show only if more than one page
  • number format customization (example: Roman numerals)

you could use a simple inline:

if ( isset($pdf) ) { 
    $font = Font_Metrics::get_font("yourfont", "normal");
    $size = 9;
    $y = $pdf->get_height() - 24;
    $x = $pdf->get_width() - 15 - Font_Metrics::get_text_width("1/1", $font, $size);
    $pdf->page_text($x, $y, "{PAGE_NUM}/{PAGE_COUNT}", $font, $size);
}   

But this does not met any of the requirements:

  • as soon as you have more than 10 pages the lineup is different on pages
  • can't control the actual page number, therefore is always shown .. also if only one page
  • no possibility of customization of the shown numbers

this because PAGE_NUM and PAGE_COUNT tokens can be used only in the page_text method

here the solution to all my requirements:

if ( isset($pdf) ) { 
    $pdf->page_script('
        if ($PAGE_COUNT > 1) {
            $font = Font_Metrics::get_font("yourfont", "normal");
            $size = 9;
            $pageText = $PAGE_NUM . "/" . $PAGE_COUNT;
            $y = $pdf->get_height() - 24;
            $x = $pdf->get_width() - 15 - Font_Metrics::get_text_width($pageText, $font, $size);
            $pdf->text($x, $y, $pageText, $font, $size);
        }        
    ');
}   

Now I can customize without problems my page number string, and is always displayed in the right way.


Sign in to add a comment
Powered by Google Project Hosting