Php html to pdf mpdf

PDF from every page of website

If you want to add a link to pages on your website to create a PDF version of the page, here is one way to do it.

(If you have already set up a CSS stylesheet for media=»print» which works for mPDF, you can omit the first 2 steps.)

Write a stylesheet suitable for presenting your webpage in mPDF. Most webpages have a header and menu on the left or right which you will not want to appear in the PDF document. You can use display: none to omit these elements. From mPDF ≥ 5.0 this will also work for inline elements. You may have something like this:

#myheader, #mysearchbar, #myleftcol, #myfooter  display: none; > span.abstract_link  display: none; > #maincontents  float:none; margin:0px; overflow:auto; padding:0; width:100%; > 

Save this file as e.g. mypdf.css

Then add this line to your webpages. This should be at the end of the document section, to override any preceding style definitions:

 href="mypdf.css" type="text/css" rel="stylesheet" media="mpdf" /> 

NB The media=»mpdf» means that the stylesheet will be ignored by browsers, but can be selected for use by mPDF — see below.

Now create a file e.g. makepdf.php and add the following script. Note you will need to edit the lines in italics.

 // require composer autoload require __DIR__ . '/vendor/autoload.php'; $mpdf = new \Mpdf\Mpdf(); $url = urldecode($_REQUEST['url']); // To prevent anyone else using your script to create their PDF files if (!preg_match('@^https?://www\.mydomain\.com/@', $url))  die("Access denied"); > // For $_POST i.e. forms with fields if (count($_POST) > 0)  $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1 ); foreach($_POST as $name => $post)  $formvars = array($name => $post . " \n"); > curl_setopt($ch, CURLOPT_POSTFIELDS, $formvars); $html = curl_exec($ch); curl_close($ch); > elseif (ini_get('allow_url_fopen'))  $html = file_get_contents($url); > else  $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt ( $ch , CURLOPT_RETURNTRANSFER , 1 ); $html = curl_exec($ch); curl_close($ch); > $mpdf = new \Mpdf\Mpdf(); $mpdf->useSubstitutions = true; // optional - just as an example $mpdf->SetHeader($url . "\n\n" . 'Page '); // optional - just as an example $mpdf->CSSselectMedia='mpdf'; // assuming you used this in the document header $mpdf->setBasePath($url); $mpdf->WriteHTML($html); $mpdf->Output(); 
 language="javascript" type="text/javascript"> /* document.write('' + encodeURIComponent(location.href) +'">'); document.write('Create PDF file of this page'); document.write(' '); /* ]]> */  

Use this to generate the code, if the webpages are selected using variables hidden from the URI e.g. HTTP POST method using a form:

 $mpdf_link = '  '; echo $mpdf_link; 

Источник

Php : create pdf from html using mpdf

Many php applications need to create pdf of documents like invoice , receipt and even id card etc. In this article we shall create a pdf invoice using the mpdf pdf creation library. Mpdf is made in php without any other external library. Mpdf parses css much better than any other free pdf libraries like tcpdf and creates pdf files which resemble the original html file to a large extent. Along with html to pdf, mpdf can also be used to create 1d barcodes of various formats.

Create the document in Html

The first step would be to make or design an invoice in html.

Use CSS and absolute measurement units like mm instead of px. Absolute units give the elements «real» dimensions instead of relative like pixel. The length/width of pixel measured elements will depend on dpi settings etc of the printer and will not give consistent printouts across different machines.

So height , width , margin , padding and anything can have units of mm , cm , in etc.
Fonts should be specified in pt — point unit instead of px.

Tables give more consistent layouts in prints.

All containers like a div , or a td should have right height and width , otherwise if they dont contain anything , they will «flexibly» shrink , spoiling the whole print layout.

<!DOCTYPE html> <html> <head> <title>Print Invoice</title> <style> * < margin:0; padding:0; font-family:Arial; font-size:10pt; color:#000; >body < width:100%; font-family:Arial; font-size:10pt; margin:0; padding:0; >p < margin:0; padding:0; >#wrapper < width:180mm; margin:0 15mm; >.page < height:297mm; width:210mm; page-break-after:always; >table < border-left: 1px solid #ccc; border-top: 1px solid #ccc; border-spacing:0; border-collapse: collapse; >table td < border-right: 1px solid #ccc; border-bottom: 1px solid #ccc; padding: 2mm; >table.heading < height:50mm; >h1.heading < font-size:14pt; color:#000; font-weight:normal; >h2.heading < font-size:9pt; color:#000; font-weight:normal; >hr < color:#ccc; background:#ccc; >#invoice_body < height: 149mm; >#invoice_body , #invoice_total < width:100%; >#invoice_body table , #invoice_total table < width:100%; border-left: 1px solid #ccc; border-top: 1px solid #ccc; border-spacing:0; border-collapse: collapse; margin-top:5mm; >#invoice_body table td , #invoice_total table td < text-align:center; font-size:9pt; border-right: 1px solid #ccc; border-bottom: 1px solid #ccc; padding:2mm 0; >#invoice_body table td.mono , #invoice_total table td.mono < font-family:monospace; text-align:right; padding-right:3mm; font-size:10pt; >#footer < width:180mm; margin:0 15mm; padding-bottom:3mm; >#footer table < width:100%; border-left: 1px solid #ccc; border-top: 1px solid #ccc; background:#eee; border-spacing:0; border-collapse: collapse; >#footer table td < width:25%; text-align:center; font-size:9pt; border-right: 1px solid #ccc; border-bottom: 1px solid #ccc; ></style> </head> <body> <div <p style="text-align:center; font-weight:bold; padding-top:5mm;">INVOICE</p> <br /> <table style="width:100%;"> <tr> <td style="width:80mm;"> <h1 Corp</h1> <h2 Happy Street<br /> CoolCity - Pincode<br /> Region , Country<br /> Website : www.website.com<br /> E-mail : [email protected]<br /> Phone : +1 - 123456789 </h2> </td> <td rowspan="2" valign="top" align="right" style="padding:3mm;"> <table> <tr><td>Invoice No : </td><td>11-12-17</td></tr> <tr><td>Dated : </td><td>01-Aug-2011</td></tr> <tr><td>Currency : </td><td>USD</td></tr> </table> </td> </tr> <tr> <td> <b>Buyer</b> :<br /> Client Name<br /> Client Address <br /> City - Pincode , Country<br /> </td> </tr> </table> <div style="background:#eee;"> <td style="width:8%;"><b>Sl. No.</b></td> <td><b>Product</b></td> <td style="width:15%;"><b>Quantity</b></td> <td style="width:15%;"><b>Rate</b></td> <td style="width:15%;"><b>Total</b></td> </tr> </table> <table> <tr> <td style="width:8%;">1</td> <td style="text-align:left; padding-left:10px;">Software Development<br />Description : Upgradation of telecrm</td> <td style="width:15%;">1</td><td style="width:15%;" <td style="width:15%;" colspan="3"></td> <td></td> <td></td> </tr> <tr> <td colspan="3"></td> <td>Total :</td> <td Amount : <table> <tr> <td style="text-align:left; padding-left:10px;">One Hundred And Fifty Seven only</td> <td style="width:15%;">USD</td> <td style="width:15%;" /> <hr /> <br /> <table style="width:100%; height:35mm;"> <tr> <td style="width:65%;" valign="top"> Payment Information :<br /> Please make cheque payments payable to : <br /> <b>ABC Corp</b> <br /><br /> The Invoice is payable within 7 days of issue.<br /><br /> </td> <td> <div &amp; O.E.<br /> For ABC Corp<br /><br /><br /><br /> Authorised Signatory </div> </td> </tr> </table> </div> <br /> </div> <htmlpagefooter name="footer"> <hr /> <div Solutions</td><td>Mobile Solutions</td><td>Web Solutions</td></tr> </table> </div> </htmlpagefooter> <sethtmlpagefooter name="footer" value="on" /> </body> </html>

Its a simple design made using tables and css styles. The html invoices is formatted enough to take a printout or email as attachment.

Convert the html to pdf

The php code to convert the html to pdf would be :

include("MPDF53/mpdf.php"); $mpdf=new mPDF('c','A4','','' , 0 , 0 , 0 , 0 , 0 , 0); $mpdf->SetDisplayMode('fullpage'); $mpdf->list_indent_first_level = 0; // 1 or 0 - whether to indent the first level of a list $mpdf->WriteHTML(file_get_contents('invoice.html')); $mpdf->Output();

Simple and fast. The mpdf library directly converts the html file into a pdf. It parses the CSS and applies the corresponding styles to the pdf document in a very effective manner , making the pdf look the same as the html file.

mpdf library enables tags like htmlpagefooter which make it very easy to add html footers etc to the pdf pages.
The footer for the above invoice is generated using :

<htmlpagefooter name="footer"> <hr /> <div Solutions</td><td>Mobile Solutions</td><td>Web Solutions</td></tr> </table> </div> </htmlpagefooter> <sethtmlpagefooter name="footer" value="on" />

No need to call any functions or anything in the php code. Everything lies in the html itself.

So many different kind of pdf documents like invoices , money receipts , fillup forms and reports etc can be generated using php and mpdf library.

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected] .

69 Comments

  1. Carlos June 15, 2018 at 11:11 am Hi,
    How can I link the name, the client’s address with the query of the mysql database. Should I go inside php? You can indicate an example, thank you. would it be something like client?> .

Источник

HTML or PHP?

Most of the functions of mPDF can be achieved two ways:

Use whichever suits your purpose better, and you can always combine a mixture of the two.

If you are new to mPDF, I would recommend using HTML/CSS for everything — you can test most things out in a browser this way as you are writing it.

Examples

 $mpdf = new \Mpdf\Mpdf(); $mpdf->Bookmark('Start of the document'); $mpdf->WriteHTML('
Section 1 text
'
); $mpdf->Output();

Example #2 Custom HTML Tag

 $html = '
Section 1 text
'
; $mpdf = new \Mpdf\Mpdf(); $mpdf->WriteHTML($html); $mpdf->Output();

Invalid HTML?

If you want to hide mPDF custom tags from a browser, enclose any mPDF code within:

mPDF will strip away the tag and any preceeding spaces, and process all enclosed code e.g.

Источник

mPDF

mPDF is a PHP library which generates PDF files from UTF-8 encoded HTML.

It is based on FPDF and HTML2FPDF with a number of enhancements.

The original author, Ian Back, wrote mPDF to output PDF files ‘on-the-fly’ from his website, handling different languages. It is slower than the original scripts e.g. HTML2FPDF and produces larger files when using Unicode fonts, but support for CSS styles etc. and has been much enhanced – see the features.

Support

Consider supporting development of mPDF with a donation of any value.

About CSS support and development state

mPDF as a whole is a quite dated software. Nowadays, better alternatives are available, albeit not written in PHP.

Use mPDF if you cannot use non-PHP approach to generate PDF files or if you want to leverage some of the benefits of mPDF over browser approach – color handling, pre-print, barcodes support, headers and footers, page numbering, TOCs, etc. But beware that a HTML/CSS template tailored for mPDF might be necessary.

If you are looking for state of the art CSS support, mirroring existing HTML pages to PDF, use headless Chrome.

mPDF will still be updated to enhance some internal capabilities and to support newer versions of PHP, but better and/or newer CSS support will most likely not be implemented.

Useful manual pages

Development

Troubleshooting

Please use https://stackoverflow.com/questions/tagged/mpdf for all your general questions or troubleshooting!

Contributions are welcome 🙂 For contributing with a bug report, feature request or pull request, please see the guideline at GitHub. Please provide a nice small example case or unit test. That will be really helpful for everybody. Thanks!

Acronyms

These are the most used acronyms throughout this manual.

  • CJK — Chinese-Japanese-Korean languages
  • HTML — Hypertext Markup Language (code used to display Internet pages)
  • IE — Internet Explorer (Microsoft)
  • LTR — Left-to-Right document, used for most langauges
  • PDF — Portable Document Format
  • PHP — PHP: Hypertext Preprocessor
  • RTL — Right-to-Left document, used for Hebrew and Arabic languages
  • ToC — Table of Contents

Источник

Читайте также:  background
Оцените статью