How to export an HTML/PHP page to PDF

Asked

Viewed 67,841 times

68

How to export an HTML page to a PDF file?

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

Code example:

$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>';
  • 2

    Since I only have a link and I don’t have the experience to speak, I will just post the link of what I have already been told: http://html2pdf.fr/en/default

  • @mustache, thanks! I’m testing that one too html2pdf :) but I don’t know much about this library or the native PHP functions for Pdfs, hence the question... _

  • 1

    I’ve used mpdf, and the fpdf, worth taking a look too.

  • FPDF is very simple and comes with the documentation that helps a lot

  • @Sergio which one you used and why?

8 answers

57


I use a tool called DOMPDF (english) dompdf which is an HTML to PDF converter.

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

There are many examples from their page (english), but there’s one working here:

anyhow.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, ie, poorly formatted HTML will be ignored.
Supports virtually everything from CSS 2.1.


Summary:

Here is the short version of the example presented above to demonstrate that it is possible to generate PDF with 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);

?>
  • 1

    Only one problem, it rejects a lot of Html5 tags.

  • 1

    Does it reject as much as the html2pdf ? =/

  • 1

    @Marcoshenzel The simplest is to take a test... Take a piece of perfectly valid HTML and use each of the tools that look promising to you to generate the PDF with that same HTML. Then you check which one behaves best ;)

  • Yeah, I’m testing to see, the good of html2pdf is that it generates barcodes

  • And if it doesn’t work out with this code you posted?

  • @Carloshenrique If you are in difficulty, open a question here on the site with your code that I or others help to solve. Without seeing your code it’s hard to know what’s wrong or anything else that’s going on to "not work". ;)

  • https://answall.com/questions/235720/fun%C3%A7%C3%A3o-get-Magic-Quotes-gpc-error

  • Speak my dear, all beauty ? pull my html via JS and send to my controller, but it does not run in pdf, and the pdf page comes blank.

Show 3 more comments

17

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 integrated into the language without major difficulties.

I found this topic, who cites the WKHTMLTOPDF. It is not a PHP library, but a command line program that does the conversion of HTMLfor PDF and can be integrated into PHP as described here. It is based on the Webkit, and there are several reports that the output is true to the original.

There is still a extension for PHP and a higher level implementation, which seeks to facilitate use.

Obviously, there is the question of the need for access as root the operating system to make the installation and configuration, not always available at hosts hired. In addition, some users reported difficulties in installing the library on some Linux distributions or certain types of processors.

  • 1

    The speed of export is a differential, since the others (TCPDF, FPDF, DOMPDF, etc.) can take a long time for large pages or if there are tables.

  • Supports barcodes and CSS ?

10

I already make use of the Headless Browser Phantomjs to download COMPLETE WEB pages FAITHFULLY rendered to displayed in the common browser (it interprets JS and CSS) but with it it is also possible to perform a print screen of the desired page of the shape sequinte:

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

Command that accesses a given page and saves the contents of it 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 from the following foma at the command line: program name (if it has been inserted in the path) plus npath of the javascript file created in the above item so it is as follows:

    phantomjs test.js

With it 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 setting should 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 in this way:

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

Note: step a third variable that represents the site to have its page printada the site is picked up by the vector of args that are passed to the shell.

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

Phantomjs was very useful to me and is very configurable and I could not describe all the possibilities here so I am pasting some links Official and not Official that may be useful:

Download

Link: http://phantomjs.org/download.html

Documentation

Screen Capture: Link

viewportSize: Link

shell_exec (PHP): Link

  • in my implementation Phantomjs ran the export in about 2% of the time of the other libraries in PHP. In addition the possibility to add header and footer is a differential.

  • @Sanction it is very good indeed and has a gigantic range of configuration forms and functionalities (which even scrutinize the scope of this question)

4

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

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

Has good documentation and several practical examples.

Some of the available resources:

  • Render HTML content
  • Insert Barcode (1D/2D)
  • Work with CMYK colors
  • Insert Vector Images (EPS/AI)
  • Move, copy and delete pages

4

4

3

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');

?>

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

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

Download available at http://sourceforge.net/projects/phphtml2pdf/

Examples http://html2pdf.fr/en/example

0

Use the library jsPDF.

Runs on the client side without the need for any server processing. That doesn’t mean you don’t 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 this processing as a data source for the generation of your PDF files with Javascript.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.