mPDF: HTML to PDF introduction

mPDF is a simple and popular tool for shared hosting users to create and convert UTF-8 encoded HTML pages to PDF files. In other words mPDF is a PHP classes based on FPDF and HTML2PDF tools which purpose is the same – to create and manage PDF documents using simple PHP. It’s worth mentioning that on some basis mPDF is slower and can produce bigger PDF files than its predecessors, however it has many capabilities and simpler to use for daily basis.

By using mPDF you have to create an HTML file structure which will be converted to PDF format file. You can also use some CSS coding and improve your files. You can find all the supported CSS attributes in this classes documentation, but I can say that you can securely use most popular and common CSS attributes for your elements. However, there are some restrictions using HTML tables and styling text inside cells.

With mPDF you will be able to create rich PDFs with headers and footers, CSS styling, included pictures, password protection, watermarks, pages numbering, justification and more….

mPDF Installation and setup

You can download latest mPDF version from the official website. After you have downloaded the necessary files just extract zipped file content to your defined folder and rename it to mpdf for better usage in the future. Lowercased folder name prevents you from foolish mistakes including the class and etc. It’s a good practice to keep this kind of tools in special folder called library, modules or plugins.

In addition, you should allow three catalogs to be written. Folders list:

  • /ttfontdata/
  • /tmp/
  • /graph_cache/

You now successfully installed mPDF to your website.

Initializing mPDF and a first try

You now can produce all kinds of different PDF’s generated from HTML. The easiest way to ensure that you done everything right is to initialize mPDF class after including it to your PHP file and generating a simple line in PDF.

Here’s a code snippet that will help you:


require_once('library/mpdf.php');

$mpdf = new mPDF();

$mpdf->WriteHTML('<p>Your first taste of creating PDF from HTML</p>');

$mpdf->Output();
exit;

You should get a downloadable PDF file with your specified line in it. If you do not get it, ensure you are seeing PHP errors and try to eliminate them or make sure you installed it right.

More complex usage

I think you have already understood that WriteHTML method enables you to write HTML code to the PDF file and output it. You should consider looking all available and supported HTML tags in documentation. However, you should not have any problems using common HTML tags, for example, creating divs, tables, headings, all kinds of lists, text and etc.

It’s a good practice to put CSS and HTML codes in separate files and you can keep up with this rule when using mPDF too. So imagine that you have all your file styling in file “stylesheet.css” and want to include everything to your PDF. By using the same function WriteHTML and adding second parameter you can easily do this. Second parameter tells how to parse the contents. For example, if you specified 1, it would only parse content as CSS styles. If you specified 2, the content would only be parsed as HTML elements. Default value is zero which orders to parse the file as HTML document including both elements and styles.

We are trying to parse only CSS contents from file and add  some div to the file. View the example here:


$mpdf = new mPDF();
$stylesheet = file_get_contents('stylesheet.css');
$mpdf->WriteHTML($stylesheet,1);
$mpdf->WriteHTML('<div id="mydiv"><p>HTML content goes here...</p></div>', 2);
$mpdf->Output();
exit;

If you want to be more specific about encoding and page size, you can put those parameters when initializing mPDF class like this:


$mpdf = new mPDF('utf-8', 'A4');

You can even specify actual page size in mm. In the example below the page size will be 190mm wide x 236mm height:


$mpdf = new mPDF('utf-8', array(190,236));

If you want full functionality, you can even specify margins and if the page is landscape like this:


$mpdf = new mPDF('',    // mode - default ''
 '',    // format - A4, for example, default ''
 0,     // font size - default 0
 '',    // default font family
 15,    // margin_left
 15,    // margin right
 16,     // margin top
 16,    // margin bottom
 9,     // margin header
 9,     // margin footer
 'L');  // L - landscape, P - portrait

In later articles and tutorials we will see how to set headers and make complex structure of our PDF file.

, , , , , , ,

About Richard Smaizys

I am a freelance PHP developer working mostly on projects using PrestaShop for ecommerce (modules, theme integration, projects from 0 etc.) and WordPress as CMS solution.

43 Responses to “mPDF: HTML to PDF introduction”

  1. atomboy November 29, 2011 at 2:13 am # Reply

    Hello,

    I can’t download the latest version, there isn’t that site, I got this message: “Error 500″. Can you upload the source anywhere?

    Thanks!
    Tom

    • Richard Smaizys November 29, 2011 at 8:17 am # Reply

      It seems that the link have changed and is now: http://www.mpdf1.com/mpdf/

      Thanks for the comments, I have also edited the article.

  2. Songket January 11, 2012 at 7:07 am # Reply

    Hi,

    I am using this tool for my website, however the resulting pdf page shows blank. when converting the parent article, it is ok but when it comes to child article, the pdf page shows blank. Please help me

    Thank you

    • Richard Smaizys January 11, 2012 at 10:08 am # Reply

      Hello, I did not really understand about what child and parent articles you are talking. Can you describe it?

  3. koula January 18, 2012 at 9:56 pm # Reply

    I am using the ‘L’ property, but the output pdf remains in portrait. Do you have any idea why this happens?

    • mArvin January 26, 2012 at 6:13 pm # Reply

      I also ran into this problem, then I opened mpdf.php only to see that it searches for ‘A4-L’ attribute to set the page to landscape. So instead of providing just ‘A4′ as format, type in ‘A4-L’.

      • rachel October 4, 2012 at 2:19 am # Reply

        Thank you! This comment saved my life. :)

      • Vanaja October 29, 2012 at 10:28 am # Reply

        Hi, Can we adjust page size our own instead of define A4 or A3, because for my PDF required widthy portrait, off-course I can use landscape but its giving horizontal scroll. That I don’t want. Can you suggest…!

  4. PDev March 8, 2012 at 8:13 pm # Reply

    Hi I am using MPDF 5.3 and want to display japanese language data in PDF file genereted using MPDF script. In HTML charset is set to UTF-8 but when I run the program it says ‘HTML contains invalid UTF-8 character(s)’. Could you plz plz plz help me on this.

    Thanks!

    • Richard Smaizys April 6, 2012 at 9:26 am # Reply

      When using my language symbols there were not any problems with UTF-8. Try changing other fonts.

  5. barry March 13, 2012 at 8:53 pm # Reply

    mPDF is GREAT. i’ve tried several of these and it’s the best by far in terms of handling paging and tables and headers and footer correctly every time.

    • Richard Smaizys April 6, 2012 at 9:25 am # Reply

      Yep, the same here.

  6. martin April 1, 2012 at 5:56 pm # Reply

    Hi.

    I’m getting a blank page when saving the PDF in Chrome, but it works perfectly during the preview. PDF also works perfectly when saving and previewing in Firefox.
    Where is problem?

    Thanks

    • Richard Smaizys April 6, 2012 at 9:25 am # Reply

      It’s hard to say. Have you tried to look on Google for this? Maybe Chrome’s PDF reader needs some options or maybe you’ve made a very simple mistake.

  7. Vikram April 5, 2012 at 9:04 pm # Reply

    Hi,
    I am planning to initiate pdf generation via ajax call, and in turn i want the location of the file generated, how can i get this location at server side php, so that i can send it back as ajax response.

    Thanks

    • Vikram April 5, 2012 at 9:12 pm # Reply

      i got it i was lazy fellow, just checked the doc—
      string Output ([ string $filename , string $dest ])

  8. Jay Edgar June 7, 2012 at 5:35 pm # Reply

    When this tenders a table, does it space the columns proportionately, or are they all fixed width? Tcpdf does fixed, unless you define the widths manually, of course. Thanks.

  9. banti June 16, 2012 at 12:50 pm # Reply

    hi i m using mpdf every thig is fine but remot image no loading in pdf please help meee

  10. Ignacio Cortorreal June 22, 2012 at 6:00 pm # Reply

    I really like your job. This is a great introduction. The only complaint I have is the difficulty of coping the snippets when they get highlighted and formatted. Please add a ‘Copy to Clipboard’ or ‘Plain Code’ feature. Many thanks.

  11. mithun June 29, 2012 at 6:35 pm # Reply

    Hi i am using mpdf for converting my web page which is in php long with html design but i am getting a blank pdf when i use the mpdf can u help me out pls

  12. Gav July 5, 2012 at 2:22 pm # Reply

    I am trying to save a PDF to a directory but I’m having no joy?

    // code..
    $mpdf->Output(‘file.pdf’, ‘F’);

    How would I save the file to a folder called ‘documents’ in the root folder of the site?

    Thanks in advance

    • Gav July 5, 2012 at 2:40 pm # Reply

      Ok.. I sussed it – just put the directory in the first parameter.

  13. Serega August 7, 2012 at 10:27 am # Reply

    Hi!
    How would I print the headers/footers without printing they at first page?

  14. alex donskih August 14, 2012 at 5:27 pm # Reply

    Thank you very much for this small tutorial. It helped me to understand the usage of mpdf.

  15. Simon September 6, 2012 at 7:26 am # Reply

    We were using mPDF for a couple of years until recently when we moved to a new server. Suddenly, it stopped working. We spend a few days until we finally found out the new server’s PHP didn’t have mbregex required for mPDF. It did have MBString, but not MBREGEX. So we compiled the Apache with EasyApache to include MBREGEX in the PHP.

    If anyone is in the same situation, just recompile PHP with mbregext. It may save you a few days of debugging.

    It is good to make a note in

    • Justin Givens February 23, 2014 at 11:15 pm # Reply

      Simon,

      Thank you soo much for pointing out mbregex. For some reason mine as also disabled and couldn’t get an error message. I rebuild php with enabled line and it worked!

      Thanks again!

  16. manindra September 12, 2012 at 10:16 am # Reply

    hiow can i call a page having my html table with php code into mpdf in between

    require_once(‘library/mpdf.php’);

    $mpdf = new mPDF();

    $mpdf->WriteHTML(‘Your first taste of creating PDF from HTML’);

    $mpdf->Output();
    exit;

  17. manindra September 18, 2012 at 2:39 pm # Reply

    how can i call a page having my html table with php code into mpdf in between
    WriteHTML(‘Your first taste of creating PDF from HTML’);

    $mpdf->Output();
    exit;
    ?>

  18. Dinesh October 26, 2012 at 9:52 pm # Reply

    I need to add a link(url) to an external website in the pdf. How can I do that? Right now it shows as plain text for the url.

  19. xjshiya February 19, 2013 at 9:16 am # Reply

    Hello,

    I’m searching for something that can output the result of my PHP code to PDF file. My PHP code fetch result from MySQL database. How can I make it work using mPDF? Please help me. Thanks.

    • Richard Smaizys February 19, 2013 at 11:11 am # Reply

      Everything is written in the article or try to use Google for more information

      • Rekha May 4, 2013 at 12:27 pm # Reply

        im using mpdf for converting html to pdf and its working great.i want to set windows default font .so i set windows font path in config_fonts.php as define(“_MPDF_SYSTEM_TTFONTS”, ‘C:/Windows/Fonts/’);.but its not taking.could you plz help me to set windows font in mpdf?

  20. Kieran Headley May 8, 2013 at 10:32 am # Reply

    Great Article Richard, I have been using mpdf and it is great, one question I do have, is there a way of preempting the title of the document when you save it? Currently I am just getting the .php filename that the script is written in.

    Thanks Again

    • Pierre March 20, 2014 at 1:36 pm # Reply

      Hey, did you find a way of changing the document title? I search the web and the mpdf doc but no luck! :-(

  21. Nisha June 17, 2013 at 12:38 pm # Reply

    I’m using mpdf to display a regional language in pdf. But it is not working. I have used all the methods to specify font family, but it still display characters as boxes.

  22. David Heath July 17, 2013 at 4:36 am # Reply

    I have just started using mpdf – it seems to work great with html code but I have a requirement to insert a blob image from mysql.
    The code to convert the image which works in html is:
    – photo.php is the software that converts the blob image..

    However, when I try to use this expression within mpdf –

    $html=(“……….”)
    $mpdf->WriteHTML(“$heading”);

    it won’t work.

    However this does work.

    $html=(“……….”)
    $mpdf->WriteHTML(“$heading”);

    What is the corrent syntax for the expression or is it even possible?

    Thanks.

    • David Heath July 17, 2013 at 7:45 am # Reply

      For some reason the code didn’t come through

      The line that didn’t work is

      The line that works is

      • David Heath July 17, 2013 at 7:46 am # Reply

        Doesn’t work

        IMG SRC=”photo.php?page=image&id=1″ WIDTH=”140

        Works:

        IMG SRC=image.jpg WIDTH=”140″

        • David Heath July 22, 2013 at 2:51 am # Reply

          Please ignore my comments above – looking for another solution. Thanks.

  23. abhinav July 17, 2013 at 8:16 am # Reply

    when i convert html to pdf,it is not showing image in pdf.also the url is correct and image displayed on browser.

  24. Roberto Torres December 7, 2013 at 12:03 pm # Reply

    Thanks!

  25. Greeg G August 22, 2014 at 1:56 pm # Reply

    Hi there,

    I was following the instruction here but it seems not working here. Is it ok if you send me a ZIP file which contain all necessary file to display what is it suppose to be? Hope you dont mind.

    Thanks

Trackbacks/Pingbacks

  1. Convert HTML to PDF in batch | Personal Publishing - March 29, 2012

    [...] one for all HTML pages within the supply batch. this protects a lot of time on multiple conversions.A lot of knowledge is stored within the net within the format of HTML pages. If you'd wish to have a…text editor and reserve it as text document. Stored as text, the data is simply changed or deleted. [...]

Leave a Reply