Green Files

How to Export an HTML/PHP Page to PDF

Day: 06/02/2022 - Time: 15:51:04

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

You can use a tool called 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 but here is one that works:


<?php /* Content preparation * (I usually have a function to perform this task) */ $html = ' <p>My HTML as I want to see it in the browser!</p> <p>Already formatted and with CSS.</p>'; /* Preparation of the final document */ $documentTemplate = ' <!doctype html> <html> <head> <link rel="stylesheet" media="screen" href="" type="text/css"> </head> <body> <div id="wrapper"> '.$html.' </div> </body> </html>'; // library inclusion require_once("dompdf/"); // some tweaks due to server to server variations if ( get_magic_quotes_gpc() ) $documentTemplate = stripslashes($documentTemplate); // opening new document $dompdf = new DOMPDF(); // load the HTML $dompdf->load_html($documentTemplate); // target document data $dompdf->set_paper("A4", "portrail"); // generate target document $dompdf->render(); // send destination document for download $dompdf->stream("dompdf_out.pdf"); exit(0); ?>

It is particularly demanding, ie badly formatted HTML will be ignored.

Suports pretty much everything from CSS 2.1.