Exporting an HTML / PHP page to PDF

66

How to export an HTML page to a PDF file?

Having a default document where you can change variables within this template, then export that page to an A4 format PDF file, without spoiling the layout.

Code sample:

$conteudo_html = '
    <!DOCTYPE html>
    <html>
        <head>
            <link type="text/css" rel="stylesheet" href="stylesheet.css"/>
            <title></title>
        </head>
        <body>
            <div id="header">'.$titulo.'</div>
            <div class="left">'.$conteudo_esq.'</div>
            <div class="right">'.$conteudo_dto.'</div>
            <div id="footer">'.$rodape.'</div>
        </body>
    </html>';
    
asked by anonymous 20.12.2013 / 16:23

8 answers

53

I usually use a tool called DOMPDF (English) dompdf which is an HTML converter for PDF.

What it does is read the DOM from the HTML page in question and convert it to a PDF document:

There are many examples from their page (English) , but here's one to work:

anyCase.php

<?php

/* Preparação do conteúdo
 * (costumo ter uma função a realizar esta tarefa)
 */
$html = '
<p>O meu HTML como quero ver no navegador!</p>
<p>Já formatado e com CSS.</p>';


/* Preparação do documento final
 */
$documentTemplate = '
<!doctype html> 
<html> 
    <head>
        <link rel="stylesheet" media="screen" href="http://www.site.com/css/style.css" type="text/css">
    </head> 
    <body>
        <div id="wrapper">
            '.$html.'
        </div>
    </body> 
</html>';


// inclusão da biblioteca
require_once("dompdf/dompdf_config.inc.php");


// alguns ajustes devido a variações de servidor para servidor
if ( get_magic_quotes_gpc() )
    $documentTemplate = stripslashes($documentTemplate);


// abertura de novo documento
$dompdf = new DOMPDF();

// carregar o HTML
$dompdf->load_html($documentTemplate);

// dados do documento destino
$dompdf->set_paper("A4", "portrail");

// gerar documento destino
$dompdf->render();

// enviar documento destino para download
$dompdf->stream("dompdf_out.pdf");

exit(0);
?>

Notes:
It is particularly demanding, meaning poorly formatted HTML will be ignored. It supports almost everything from CSS 2.1.

Summary:

Here is the summarized version of the example above to demonstrate that it is possible to generate the PDF with a few lines of code:

<?php

$html = 'o meu HTML pronto tal como vai para o navegador!';

$documentTemplate = '
<!doctype html> 
<html> 
 <head>
  <link rel="stylesheet" type="text/css" href="http://www.example.com/style.css">
 </head> 
 <body>
  <div id="wrapper">
   '.$html.'
  </div>
 </body> 
</html>';

require_once("dompdf/dompdf_config.inc.php");

if ( get_magic_quotes_gpc() )
    $documentTemplate = stripslashes($documentTemplate);

$dompdf = new DOMPDF();
$dompdf->load_html($documentTemplate);
$dompdf->set_paper("A4", "portrail");
$dompdf->render();

// enviar documento destino para download
$dompdf->stream("dompdf_out.pdf");

exit(0);

?>
    
20.12.2013 / 16:46
15
While it is desirable to have a native implementation of this type of library in the language we use, it is important to consider options that can be seamlessly integrated into the language.

I found this topic , which cites WKHTMLTOPDF . It is not a PHP library, but a command line program that converts from HTML to PDF and can be integrated with PHP as described here . It is based on WebKit , and there are several reports that output is quite true to the original.

There's even a extension for PHP and a higher level implementation , which seeks to facilitate the use.

Obviously, there is the question of needing root access to the operating system to do the installation and configuration, not always available on contracted hosts . In addition, some users have reported difficulties installing the library on some Linux distributions or certain types of processors.

    
20.12.2013 / 17:07
7

I already use the Headless Browser PhantomJS to download full FAX-rendered WEB pages that are displayed in the regular browser (it interprets JS and CSS) but with it is also possible to perform a print screen of the desired page of the following form:

  • Create a file with .js extension
  • Paste and save the following content:

Command that accesses a certain page and saves its contents in a .png (but can save as PDF):

var page = require('webpage').create();
page.open('http://stackoverflow.com/', function() {
  page.render('stackoverflow.png');
  phantom.exit();
});
  • Call it the following command line: program name (if it has been entered in the path) plus npath of the javascript file created in the above item getting as follows:

    phantomjs test.js

It is also possible to establish the dimensions of the window where the site is displayed (this is useful if you want to see how a responsive site is being rendered) as follows (this configuration must be done before the page.open ()) :

var webPage = require('webpage');
var page = webPage.create();

page.viewportSize = {
  width: 480,
  height: 800
};

You can call it using the shell_exec command like this:

    $pathToPhantomJS = 'C:\phantomjs-2.0.0-windows\bin\phantomjs';
    $pathToJSScript = 'GetPage.js';
    $comand = $pathToPhantomJS . ' ' . $pathToJSScript . ' ' . $site;
    shell_exec($comand);

It is possible to create a CRON JOB to run the phantomjs teste.js command at a certain time.

The PhantomJS was very useful to me and it is very configurable and I could not describe all the possibilities here so I am sticking some official and non-official links that may be useful:

Download

Link: link

Documentation

Screen Capture: Link

viewportSize: Link

shell_exec (PHP): Link

    
25.04.2015 / 16:59
3

Use the FPDF at a glance at link this library is very interesting.

    
30.01.2014 / 04:34
3

Of all the libraries I've used, the one I liked the most was TCPDF

In my opinion it is the most complete and the simplest to use.

It has good documentation and several practical examples .

Some of the features available:

  • Render HTML content
  • Insert Bar Code (1D / 2D)
  • Working with CMYK colors
  • Insert Vector Images (EPS / AI)
  • Move, copy, and delete pages
31.01.2014 / 15:09
3

If you prefer one that recognizes CSS properties, I recommend mPDF

Resources:

  • Accepts UTF-8
  • CSS support
  • Supports JPEG, GIF, PNG, WMF and SVG images
  • Watermark
  • Standalone PHP Library
  • Etc ...

See all features at link

Download: link

    
29.05.2014 / 21:56
2

I recommend using html2pdf, it just needs to put the HTML content and output.

<?php
date_default_timezone_set('America/Sao_Paulo');
    $content = "<!DOCTYPE html><html><body><h1>This is heading 1</h1>
    <h2>This is heading 2</h2><h3>This is heading 3</h3>
    <h4>This is heading 4</h4><h5>This is heading 5</h5>
    <h6>This is heading 6</h6></body></html>";

    require_once(dirname(__FILE__).'\html2pdf\html2pdf.class.php');
    $html2pdf = new HTML2PDF('P','A4','fr');
    $html2pdf->WriteHTML($content);
    $html2pdf->Output('example.pdf', 'F');

?>

$html2pdf->Output without 'F' causes the PDF to be printed on the screen, saving the local file without displaying it. In the example above, the PDF is saved on the server and can be downloaded later.

To display set the output so $html2pdf->Output('example.pdf');

Download available at link

Examples link

    
04.08.2015 / 13:22
-2

Use the jsPDF library.

Wheel on the client side without the need for any processing on the server. This does not mean that you do not need a server, of course, but it makes jsPDF compatible with any server-side technology , because you can process your data on the server and use the result of that processing as a source. data for generating your PDF files with JavaScript.

    
25.11.2015 / 00:07