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.

Leave a Reply to abhinav Cancel reply

Leave a comment

Comments

  • atomboy
    November 29th, 2011 / 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 29th, 2011 / 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.

  • Songket
    January 11th, 2012 / 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 11th, 2012 / 10:08 AM
      Reply

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

  • koula
    January 18th, 2012 / 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 26th, 2012 / 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 4th, 2012 / 2:19 AM

        Thank you! This comment saved my life. 🙂

      • Vanaja
        October 29th, 2012 / 10:28 AM

        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…!

  • PDev
    March 8th, 2012 / 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 6th, 2012 / 9:26 AM
      Reply

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

  • barry
    March 13th, 2012 / 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 6th, 2012 / 9:25 AM
      Reply

      Yep, the same here.

  • Convert HTML to PDF in batch | Personal Publishing
    March 29th, 2012 / 11:40 AM
    Reply

    […] 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. […]

  • martin
    April 1st, 2012 / 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 6th, 2012 / 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.

  • Vikram
    April 5th, 2012 / 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 5th, 2012 / 9:12 PM
      Reply

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

  • Jay Edgar
    June 7th, 2012 / 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.

  • banti
    June 16th, 2012 / 12:50 PM
    Reply

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

  • Ignacio Cortorreal
    June 22nd, 2012 / 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.

  • mithun
    June 29th, 2012 / 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

  • Gav
    July 5th, 2012 / 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 5th, 2012 / 2:40 PM
      Reply

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

  • Serega
    August 7th, 2012 / 10:27 AM
    Reply

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

  • alex donskih
    August 14th, 2012 / 5:27 PM
    Reply

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

  • Simon
    September 6th, 2012 / 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 23rd, 2014 / 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!

  • manindra
    September 12th, 2012 / 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;

  • manindra
    September 18th, 2012 / 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;
    ?>

  • Dinesh
    October 26th, 2012 / 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.

  • xjshiya
    February 19th, 2013 / 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 19th, 2013 / 11:11 AM
      Reply

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

      • Rekha
        May 4th, 2013 / 12:27 PM

        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?

  • Kieran Headley
    May 8th, 2013 / 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 20th, 2014 / 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! 🙁

  • Nisha
    June 17th, 2013 / 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.

  • David Heath
    July 17th, 2013 / 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 17th, 2013 / 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 17th, 2013 / 7:46 AM

        Doesn’t work

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

        Works:

        IMG SRC=image.jpg WIDTH=”140″

        • David Heath
          July 22nd, 2013 / 2:51 AM

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

  • abhinav
    July 17th, 2013 / 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.

  • Roberto Torres
    December 7th, 2013 / 12:03 PM
    Reply

    Thanks!

  • Carolina
    August 3rd, 2014 / 12:17 AM
    Reply

    Hello, really liked the mpdf, but I have a problem, he is ignoring any of the pages using CSS with writeHTML mode 0 and pass the CSS content with writeHTML mode 1 does not work. Know what can be?

  • Greeg G
    August 22nd, 2014 / 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

  • arum
    March 31st, 2015 / 12:17 PM
    Reply

    hi, thank you for the article.
    My case is the layout in pdf different with the html. Is that related with css? because that is exacly the same text. Please help.

  • Frank
    July 31st, 2015 / 3:38 PM
    Reply

    How do I get all the variables from yii available in my mpdf document, like:

    $mpdf=new mPDF(”,’A4′);
    $html = ‘

    Your name is ‘.name.’

    Your adress is ‘.adress.’

    ‘;
    $mpdf->WriteHTML($html);
    $mpdf->Output();

    My function in the controller is:

    public function actionMpdfgenerator($id) {
    $model = $this->findModel($id);
    $pdf = new Pdf([
    $content = $this->renderPartial(‘mpdf’), [
    ‘model’ => $model,
    ‘mode’ => Pdf::MODE_UTF8,
    ‘format’ => Pdf::FORMAT_A4,
    ‘orientation’ => Pdf::ORIENT_PORTRAIT,
    ‘destination’ => Pdf::DEST_BROWSER,
    ]
    ]);
    return $pdf->render();
    }

    that doesn’t work, all that is in the displayed pdf is like:
    Your name is ‘.name.’
    Your adress is ‘.adress.’

    So how do I get the variables from yii available in my mpdf document?

    Any ideas? Thx 4 your help.

  • Iqra Ubaid
    September 1st, 2015 / 7:47 AM
    Reply

    Hi, mpdf is really easy to use but I am facing a problem. My code for generating pdf is working fine when I open it using localhost/xampp but the problem is that I cannot open it through browser. When I click the tab/hyperlink in my website to open this pdf, it shows me the php code instead of it’s pdf version. Can someone please help me? Thank you.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. Cookies are only used for statistical purposes.

Close