February 19, 2024 5:02 am

How to Convert HTML to PDF in PHP with fpdf

HTML to PDF conversion is always a problem for PHP Programmers and all the time they search for suitable solutions so after reviewing this article you will not take more than 10 minutes to configure HTML to PDF, I have used a library fpdf open source and very useful library for developers here is a simple tutorial on how to convert How to Convert HTML to PDF with fpdf.

convert-html-to-pdf

[wpdm_file id=58]DEMO

You have to download fpdf library and  include it in your PHP file below settings and how to show tags, fonts and images in your pdf file. With fpdf library we used HTMLparser library contributed by programmers and all other libraries available here you can download and use as per your requirement.

index.html

In this file I have created a simple contact form data on submit it show that submitted data on PDF format:

<html>
<head>
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<title>How to create Contact Form using Bootstrap  | PGPGang.com</title>
</head>

<body>
<h2>How to create Contact Form using Bootstrap example.&nbsp;&nbsp;&nbsp;=> <a href="https://www.phpgang.com/">Home</a> | <a href="http://demo.phpgang.com/">More Demos</a></h2>
<div class="container">
      <form class="contact-us form-horizontal" action="actionpdf.php" method="post">
        <legend>Fill Form and submit to generate PDF</legend>        
        <div class="control-group">
            <label class="control-label">Name</label>
            <div class="controls">
                <div class="input-prepend">
                <span class="add-on"><i class="icon-user"></i></span>
                    <input type="text" class="input-xlarge" name="name" placeholder="Name">
                </div>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">Email</label>
            <div class="controls">
                <div class="input-prepend">
                <span class="add-on"><i class="icon-envelope"></i></span>
                    <input type="text" class="input-xlarge" name="email" placeholder="Email">
                </div>
            </div>    
        </div>
        <div class="control-group">
            <label class="control-label">Url</label>
            <div class="controls">
                <div class="input-prepend">
                <span class="add-on"><i class="icon-globe"></i></span>
                    <input type="text" id="url" class="input-xlarge" name="url" placeholder="http://www.example.com">
                </div>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">Comment</label>
            <div class="controls">
                <div class="input-prepend">
                <span class="add-on"><i class="icon-pencil"></i></span>
                    <textarea name="comment" class="span4" rows="4" cols="80" placeholder="Comment (Max 200 characters)"></textarea>
                </div>
            </div>
        </div>
        <div class="control-group">
          <div class="controls">
            <button type="submit" class="btn btn-primary">Submit</button>
            <button type="button" class="btn">Cancel</button>
          </div>    
        </div>
      </form>
</div>
</body>
</html>

actionpdf.php

This file contain PHP code to generate pdf file and show your submitted data on that file.

<?php
require('WriteHTML.php');

$pdf=new PDF_HTML();

$pdf->AliasNbPages();
$pdf->SetAutoPageBreak(true, 15);

$pdf->AddPage();
$pdf->Image('logo.png',18,13,33);
$pdf->SetFont('Arial','B',14);
$pdf->WriteHTML('<para><h1>PHPGang Programming Blog, Tutorials, jQuery, Ajax, PHP, MySQL and Demos</h1><br>
Website: <u>www.phpgang.com</u></para><br><br>How to Convert HTML to PDF with fpdf example');

$pdf->SetFont('Arial','B',7); 
$htmlTable='<TABLE>
<TR>
<TD>Name:</TD>
<TD>'.$_POST['name'].'</TD>
</TR>
<TR>
<TD>Email:</TD>
<TD>'.$_POST['email'].'</TD>
</TR>
<TR>
<TD>URl:</TD>
<TD>'.$_POST['url'].'</TD>
</TR>
<TR>
<TD>Comment:</TD>
<TD>'.$_POST['comment'].'</TD>
</TR>
</TABLE>';
$pdf->WriteHTML2("<br><br><br>$htmlTable");
$pdf->SetFont('Arial','B',6);
$pdf->Output(); 
?>

In this file we add page and auto page break true if your content increase single page area then it will automatically add 2nd page and process.

$pdf->Image('logo.png',18,13,33);
$pdf->SetFont('Arial','B',14);

These lines used to add a logo and select font size for heading.

$pdf->SetFont('Arial','B',7);

Select small font then heading for inner content.

$pdf->WriteHTML2("<br><br><br>$htmlTable");
$pdf->Output();

Write HTML to pdf file and output that file on the web browser.

Support

If you need any help regarding its configuration please feel free to comment we love to help you.

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.


Tutorial Categories:

130 responses to “How to Convert HTML to PDF in PHP with fpdf”

  1. atul kumar sharma says:

    to good

  2. Sudhir Gupta says:

    unable to download

  3. Shahbaz Ahmed Bhatti says:

    can php gang plz start some tutorial on funtion to add edit delete record using call function, so i can understood the function use in html to pdf demo file
    thanks

  4. skouta says:

    Thanks for this scrip. amazing,
    But why this script did not support the Arabic language ?

  5. filluup says:

    unable to download for me also. gave a error “http/1.0 503 service unavailable”

  6. Muhammad Sajjad says:

    also subscribe to it but unable to download, plz reply solution

  7. Mohammed says:

    Thanks for this scrip
    but the output display
    FPDF error: Some data has already been output, can’t send PDF file

  8. Abhishek says:

    where to find writeHTML.php ? i am a newbeee..?

  9. binil billu says:

    Hi,

    How to generate the pdf with file name ex:samplereport.pdf

  10. raj says:

    good script..

  11. Yongz says:

    also subscribe to it but unable to download, plz reply solution

  12. alexc says:

    I also can’t download the code even subscribed.

  13. sridevi says:

    I also can’t download the code

  14. Anwar says:

    how can i do this in cakephp….plz help me…thanks in advance.

  15. PANKAJ KUMAR SINHA says:

    i have subscribed but unable to download … please help ….

  16. klyptonic says:

    same…unable to download after subscribing…it still says no email found after subscribing three days ago…please help

  17. GeoStil says:

    Hi, I have subscribed, unable to dowlnoad… Can you help me please ?

  18. Raj says:

    hi sir how i implement the external css in pdf. b/c i want to create my own design on pdf page ?

  19. jack says:

    I cant download the code even I already completed subscription
    plz help

  20. Pranab says:

    amazing tutorial !!! i have some problem .. please tell me how to increase width each cell when pdf is generated ? Thanks.

  21. Kasia D'Aquino says:

    Hi,

    I get the following errors:

    Warning: Division by zero in /convert-pdf/WriteHTML.php on line 323
    FPDF error: Some data has already been output, can’t send PDF file

    Any ideas??

  22. Kasia D'Aquino says:

    How do you save to pdf instead of displaying in browser?

    • Lamjing Khomba says:

      put the following code at bottom of your page
      header(“Content-type:application/pdf”);

      // It will be called downloaded.pdf
      header(“Content-Disposition:attachment;filename=’filename.pdf'”);

  23. Crown Angel says:

    hello i have problem with utf-8 how i can edit to change lang arabic ..

  24. Lionheart says:

    Even after subscribing i cant down, i still cant download

  25. Zalakpatel says:

    Subscribed, but not able to download

  26. Antonio Leonardo says:

    Excelent tutorial, I’m curious to apply!

  27. Sonia says:

    thanx 🙂

  28. Sonia says:

    thanx 🙂

  29. mark says:

    how to change the size of the page??

  30. how can i write this 0) { ?> to the variable $htmlTable

  31. Adstyle says:

    hello, how can i resize the column table in that php? i have tried width=”50%” but it didnt work

  32. prakash says:

    hi, img tag can not convert into pdf

  33. sivaraman says:

    How to increase the TD width..Output is look like shrinked table

  34. Aaminan says:

    How to convert whole html file into pdf ?

  35. Allen says:

    hi, how can i set colspan for TD in TABLE

  36. jeyakanth says:

    hello sir i have a error

    Class ‘PDF_HTML’ not found in E:xampphtdocspdfactionpdf.php on line 3

  37. Harish Kumar says:

    Class ‘PDF_HTML’ not found,

  38. Ataul Islam says:

    This script is running perfectly. Thanks a lot
    Can you help me how can i save the pdf in my local folder instead of showing the pdf in page? Please advice me.

    • rinoj says:

      $filename=provide any name;
      //eg: $filename= “doc.pdf”;
      $filelocation = “Your folder Location “;
      $fileNL = $filelocation.”/”.$filename;
      $pdf->output($fileNL,’F’);

    • rinoj says:

      $filename=provide any name;
      //eg: $filename= “doc.pdf”;
      $filelocation = “Your folder Location “;
      $fileNL = $filelocation.”/”.$filename;
      $pdf->output($fileNL,’F’);

  39. Benito Montero says:

    Is Chinese character supported?

  40. James Momoh says:

    THE IMAGE UPLOADED IN THE FORM IS NOT DISPLAYING IN THE PDF……can anybody help me please help…please help me please

  41. James Momoh says:

    THE IMAGE UPLOADED IN THE FORM IS NOT DISPLAYING IN THE PDF……can anybody help me please help…please help me please…….

  42. shahnawaz says:

    how can i save this pdf file in my database

  43. Prashant bhatt says:

    if me put all code in one file than it’s not working..

  44. Lamjing Khomba says:

    how can i use colspan and rowspan?

  45. rinoj says:

    i have subscribed successfully,but i can’t download it.pls help me..
    Where the file writeHTML.php

  46. rinoj says:

    how can i remove the line on top of the every page?

  47. Amrendra mourya says:

    How can we include whole html ??

  48. Amrendra mourya says:

    When i am using two table then this library only create one table and second table will not generate . Have you any solution regarding this issue??

  49. Amrendra mourya says:

    How we can include css in pdf , Because css is not working Please give me solution regarding to this issue ??

  50. jagdish sonic says:

    i have pdf complete but pdf not view my help

  51. Chrystopher Pius Ndugo Gaucho says:

    thank you very much…love this gang

  52. anil says:

    I subscribe with [email protected] and click on activate link also but its saying you are not subs. What’s wrong while download any example

  53. swathi says:

    i like add a table within another table

  54. swathi says:

    how to do colspan and rowspan in actionpdf.php

  55. SHABNAM ASLAM says:

    hi, can u plz help me to do rowspan in the pdf

  56. erfan says:

    Hi , Thanks , It’s great . But how can i user for utf-8 encoding

  57. erfan says:

    Hi , Thanks , It’s great . But how can i use for utf-8 encoding

    • Huzoor Bux says:

      Don’t use UTF-8 encoding. Standard FPDF fonts use ISO-8859-1 or Windows-1252. It is possible to perform a conversion to ISO-8859-1 with utf8_decode(): $str = utf8_decode($str); But some characters such as Euro won’t be translated correctly. If the iconv extension is available, the right way to do it is the following: $str = iconv(‘UTF-8’, ‘windows-1252’, $str);

      source: http://stackoverflow.com/questions/6334134/fpdf-utf-8-encoding-how-to

      • Muhammad Asif says:

        Deprecated: Function get_magic_quotes_runtime() is deprecated in C:wampwwwconvert-html-to-pdf-with-fpdffpdf.php on line 1054
        FPDF error: Some data has already been output, can’t send PDF file

  58. Muhammad Asif says:

    Deprecated: Function get_magic_quotes_runtime() is deprecated in C:wampwwwconvert-html-to-pdf-with-fpdffpdf.php on line 1054
    FPDF error: Some data has already been output, can’t send PDF file

    Please help

  59. katmac23 says:

    HI
    Love your example…
    I have a php script that finds out the current user, queries the database and displays a completed form based on that information.
    When I add this code at the top of the php script to create a pdf (as shown above), I’m getting no output.

    See attached screenshot.

    What did I do wrong?

  60. katmac23 says:

    HI
    Love your example…
    I have a php script that finds out the current user, queries the database and displays a completed form based on that information.
    When I add this code at the top of the php script to create a pdf (as shown above), I’m getting no output.

    See attached screenshot.

    What did I do wrong?

  61. Rizwan Gill says:

    I am using following lines of code in

    actionpdf.php

    //$pdf->Output();
    header(“Content-type:application/pdf”);
    // It will be called downloaded.pdf
    header(“Content-Disposition:attachment;filename=doc.pdf”);
    ?>

    means i have commented out put and added lines for download but i am getting error and empty pdf file

    please see attached image and guide me where i am making mistake. Thank you soo much for your favour in advance.

  62. Rizwan Gill says:

    I am using following lines of code in

    actionpdf.php

    //$pdf->Output();
    header(“Content-type:application/pdf”);
    // It will be called downloaded.pdf
    header(“Content-Disposition:attachment;filename=doc.pdf”);
    ?>

    means i have commented out put and added lines for download but i am getting error and empty pdf file

    please see attached image and guide me where i am making mistake. Thank you soo much for your favour in advance.

  63. Varun Kumar Palisetti says:

    Thanks Bhai . Im learning how to generate invoice generation and converting it into pdf. This article helped me a lot.

  64. Varun Kumar Palisetti says:

    Hi Bhai,tried your code,everything works fine. Now instead of comment section in your form, i tried a “tinymce editor” looks like this. The problem is,whenever i align the text to center. The “ALIGN” in WriteHTML.php is showing error as “Undefined index: ALIGN in WriteHTML.php on line 62”.
    I tried as much as i can to change it from ALIGN to align, did some other silly changes, but none worked out. Help me out here. Dont tell me the entire solution, tell what i have to check.

  65. Rhej Padilla says:

    Fatal error: Class ‘PDF_HTML’ not found.

  66. Krunal says:

    how to download after converting the file

  67. Krunal says:

    how to download after converting the file plz reply fast

  68. Krunal says:

    while i run actionpdf.php then download file but pdf content does not load

  69. Dinesh Kumar says:

    sir, how to clear this? 31-01-2016=’1454194800′ and 31-01-2016=’145426500′ the same values denotes same date .which one is correct?

  70. chie says:

    Hie , i like the script, working fine , however i need your help , if i
    want to send the form on the submit button as a that outcome pdf to
    email(as an attachement). Please help.

  71. Carlos M Gomez says:

    does not let me download, show a message saying i am not registered, but i already confirm from my email

  72. Qamar says:

    I want to design table in actionpdf.php using css. So how can I do?

  73. Kim Young says:

    Hi Huzoor, Are you available for freelance work? I need help to create a dynamic pdf (using php) that meets web accessibility standards (PDF/UA and WCAG 2.0). Is that difficult to do?

  74. Shubham Rathod says:

    Hello,
    i am trying to give 100% width to table by applying rule but however it is not applied in PDF.
    can you please suggest me what to do to give 100% width to table

    Thank you.

  75. daywalker says:

    where have you used index.html in action.php ????

  76. Bob says:

    Why do I get the following error, what am I missing : /

    Fatal error: Call to undefined method FPDF::WriteHTML2()

  77. Anil Kumar says:

    Sir I have included my html file, pdf conversion is well in my case but the same design of html is not appearing in my converted pdf , like no logos, no lines etc. pls help

  78. Karthik Saravanan says:

    how to save this pdf created file,
    i tried with this code
    file_put_contents(“/pdf/file.pdf”, $output);

  79. Raj says:

    how to send this pdf file after creating that

  80. Raj says:

    how to send Email this PDF file after creating that

  81. mbarki chadi says:

    how to usea whole html page with css ?
    Any help here?

  82. Vishal Deshmukh says:

    i have edited that demo form with Unicode language so it’s not display properly. so how we can display it is there any other way with fpdf

  83. Shailu Mehta says:

    How to Created PDF File is Direcly Open in Default client email?(mailto:)

  84. Asif Khan says:

    Is there any way where we can display line number in generated pdf?

  85. Jefri says:

    download file link is not working

  86. Wesley Montaigne says:

    trash!!

  87. Aliya Pandey says:

    how the save generated pdf file in a folder as well as it path in db.Please reply as sson as possible

  88. dipalip says:

    how can i get WriteHTML.php file?

  89. vivek kumar says:

    bhai adha adhura kaam kyu karte ho jo bhi kro pura karo… mention kar diya writehtml.php. kaha se laaye ye file….aur download link kha hai…..n

  90. Halim Khatri says:

    what is writeHTML.php ? and how i have to create it ?

  91. Deepak Sekhar says:

    Thanks for your tutorial sir. where to find WriteHtml.php.

  92. Service Indians says:

    Hi sir,Where is WriteHtml.php?

  93. Coevote says:

    Nice Article About How to Convert HTML to Php . Its save time who need it .

Leave a Reply

Your email address will not be published. Required fields are marked *