How To Create Pdf File In Php Code
Walk through the entire process of building PDF files dynamically using PHP. Experiment with open source tools, such as the Free PDF library (FPDF) or PDFLib-Lite, and PHP code for control of the PDF format of your content.
Previous | Table of Contents | Next |
An Overview of PHP | Commenting PHP Code |

Purchase and download the full PDF and ePub versions of this PHP eBook for only $8.99 |
In the previous chapter we looked at how PHP works. No technology book would be complete without including the obligatory simple example, and PHP Essentials is no exception to this rule.
In this chapter we will look at constructing the most basic of PHP examples, and in so doing we will take two approaches to creating PHP powered web content. Firstly we will look at embedding PHP into an HTML page. Secondly, we will look at a reverse example whereby we embed the HTML into the PHP. Both are perfectly valid approaches to using PHP.
The PHP Code Delimiters
The first thing to understand is the need to use PHP code delimiters to mark the areas of PHP code within the web page. By default, the opening delimiter is <?php and the closing delimiter is ?>. You can insert as many or as few blocks of PHP into a web page as you need as long as each block is marked by the opening and closing delimiters.
A sample PHP script block would, therefore, appear in an HTML file as follows: Tiggzi mobile app builder free download without payment.
Testing the PHP Installation

Before embarking on even the simplest of examples, the first step on the road to learning PHP is to verify that the PHP module is functioning on your web server. To achieve this, we will create a small PHP script and upload it to the web server. To do this start up your favorite editor and enter the following PHP code into it:
This PHP script calls the built-in PHP phpInfo() function, the purpose of which to output information about the PHP pre-processing module integrated into your web server.Save this file as phpInfo.php and upload it to a location on your web server where it will be accessible via a web browser. Once you have done this open a browser and go to the URL for this file. If all is well with your PHP installation you will see several pages of detailed information about your PHP environment covering topics such as how and when the PHP module was built, the version of the module and numerous configuration settings.
If you do not see this information it is possible you do not have the PHP module integrated into your web server. If you use a web hosting company, check with them to see if your particular hosting package includes PHP support (sometimes PHP support is only provided with premium hosting packages so you may need to upgrade). If you run your own web server consult the documentation for your particular type of server (Apache, Microsoft IIS etc) for details on integrating the PHP module. There are vastly superior resources available on the internet to assist in installing PHP than we could never match in this book.
A healthy PHP installation should result in output similar to the following:
Embedding PHP into an HTML File
As you may have realized, by testing the PHP module on your web server you have already crafted your first PHP script. We will now go on to create another script that is embedded into an HTML page. Open your editor and create the following HTML file:
Save this file as example.php and upload it to your web server. When you load this page into your browser you should see something like the following:
If you see something like the above in your browser then you have successfully created and executed your first embedded HTML script.
If you do not see the expected output in your browser window then go back and check your file. Something as simple as a missing character can result in no content being generated by the PHP module. As you will learn with experience, problems are almost always the result of subtle mistakes in entering the PHP code.
Embedding HTML into a PHP Script
In the previous example we embedded some PHP scripts into an HTML web page. We can reverse this by putting the HTML tags into the PHP commands. The following example contains a PHP script which is designed to output the HTML necessary to display a simple page. As with the previous examples, create this file, upload it to your web server and load it into a web browser:
When you load this into your browser it will be as if all that was in the file was HTML, and if you use the view page source feature of your browser the HTML is, infact, all you will see. This is because the PHP pre-processor simply created the HTML it was told to create when it executed the script:
Summary
In this chapter we have looked at how to test that the PHP module is installed into the web server and functioning correctly. We then went on to look at how to add PHP scripts to a web page. In the next chapter we will look at the all important, but all too frequently neglected, topic of adding comments to PHP code.
Purchase and download the full PDF and ePub versions of this PHP eBook for only $8.99 |
I have an HTML (not XHTML) document that renders fine in Firefox 3 and IE 7. It uses fairly basic CSS to style it and renders fine in HTML.
I'm now after a way of converting it to PDF. I have tried:
- DOMPDF: it had huge problems with tables. I factored out my large nested tables and it helped (before it was just consuming up to 128M of memory then dying--thats my limit on memory in php.ini) but it makes a complete mess of tables and doesn't seem to get images. The tables were just basic stuff with some border styles to add some lines at various points;
- HTML2PDF and HTML2PS: I actually had better luck with this. It rendered some of the images (all the images are Google Chart URLs) and the table formatting was much better but it seemed to have some complexity problem I haven't figured out yet and kept dying with unknown node_type() errors. Not sure where to go from here; and
- Htmldoc: this seems to work fine on basic HTML but has almost no support for CSS whatsoever so you have to do everything in HTML (I didn't realize it was still 2001 in Htmldoc-land..) so it's useless to me.
I tried a Windows app called Html2Pdf Pilot that actually did a pretty decent job but I need something that at a minimum runs on Linux and ideally runs on-demand via PHP on the Webserver.
What am I missing, or how can I resolve this issue?
closed as off-topic by meagar♦Oct 19 '16 at 18:25
This question appears to be off-topic. The users who voted to close gave this specific reason:
- 'Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.' – meagar
30 Answers
Important:Please note that this answer was written in 2009 and it might not be the most cost-effective solution today in 2019. Online alternatives are better today at this than they were back then.
Here are some online services that you can use:
Have a look at PrinceXML.
It's definitely the best HTML/CSS to PDF converter out there, although it's not free (But hey, your programming might not be free either, so if it saves you 10 hours of work, you're home free (since you also need to take into account that the alternative solutions will require you to setup a dedicated server with the right software)
Oh yeah, did I mention that this is the first (and probably only) HTML2PDF solution that does full ACID2 ?
Have a look at wkhtmltopdf
. It is open source, based on webkit and free.
We wrote a small tutorial here.
EDIT( 2017 ):
If it was to build something today, I wouldn't go that route anymore.
But would use http://pdfkit.org/ instead.
Probably stripping it of all its nodejs dependencies, to run in the browser.
After some investigation and general hair-pulling the solution seems to be HTML2PDF. DOMPDF did a terrible job with tables, borders and even moderately complex layout and htmldoc seems reasonably robust but is almost completely CSS-ignorant and I don't want to go back to doing HTML layout without CSS just for that program.
HTML2PDF looked the most promising but I kept having this weird error about null reference arguments to node_type. I finally found the solution to this. Basically, PHP 5.1.x worked fine with regex replaces (preg_replace_*) on strings of any size. PHP 5.2.1 introduced a php.ini config directive called pcre.backtrack_limit. What this config parameter does is limits the string length for which matching is done. Why this was introduced I don't know. The default value was chosen as 100,000. Why such a low value? Again, no idea.
A bug was raised against PHP 5.2.1 for this, which is still open almost two years later.
What's horrifying about this is that when the limit is exceeded, the replace just silently fails. At least if an error had been raised and logged you'd have some indication of what happened, why and what to change to fix it. But no.
So I have a 70k HTML file to turn into PDF. It requires the following php.ini settings:
- pcre.backtrack_limit = 2000000; # probably more than I need but that's OK
- memory_limit = 1024M; # yes, one gigabyte; and
- max_execution_time = 600; # yes, 10 minutes.
Now the astute reader may have noticed that my HTML file is smaller than 100k. The only reason I can guess as to why I hit this problem is that html2pdf does a conversion into xhtml as part of the process. Perhaps that took me over (although nearly 50% bloat seems odd). Whatever the case, the above worked.
Now, html2pdf is a resource hog. My 70k file takes approximately 5 minutes and at least 500-600M of RAM to create a 35 page PDF file. Not quick enough (by far) for a real-time download unfortunately and the memory usage puts the memory usage ratio in the order of 1000-to-1 (600M of RAM for a 70k file), which is utterly ridiculous.
Unfortunately, that's the best I've come up with.
Why don’t you try mPDF version 2.0? I used it for creating PDF a document. It works fine.
Meanwhile mPDF is at version 5.7 and it is actively maintained, in contrast to HTML2PS/HTML2PDF
But keep in mind, that the documentation can really be hard to handle. For example, take a look at this page: https://mpdf.github.io/.
Very basic tasks around html to pdf, can be done with this library, but more complex tasks will take some time reading and 'understanding' the documentation.
a) extract in yourfolder
b) create file.php in yourfolder
and insert such code:
c) open file.php from your browser
1) extract pdftohtml.exe to your root folder:
2) inside that folder, in anyfile.php file, put this code (assuming, there is a source example.pdf too):
3) enter FinalFolder, and there will be the converted files (as many pages, as the source PDF had.)
Checkout TCPDF. It has some HTML to PDF functionality that might be enough for what you need. It's also free!
I suggest DocRaptor (which uses PrinceXML
as the 'engine')
Just to bump the thread, I've tried DOMPDF and it worked perfectly. I've used DIV
and other block level elements to position everything, I kept it strictly CSS 2.1 and it played very nicely.
Good news! Snappy!!
Snappy is a very easy open source PHP5 library, allowing thumbnail, snapshot or PDF generation from a url or a html page. And.. it uses the excellent webkit-based wkhtmltopdf
Enjoy! ^_^
It's already been mentioned, but I'd just like to confirm that mpdf is the easiest, most powerful and most free HTML to pdf converter out there. The sky's really the limit. You can even generate pdf of dynamic, user-generated data.
For instance, a client wanted a CMS system so he could update the tracklist of the music he played at his club. That was no problem, but he also wanted users to be able to download a .pdf of the playlist, and so this downloadable pdf had to be updated by the cms too. Thanks to mpdf, with some simple loops and interspersed variables I could do just that. Something that I thought would take me weeks literally took me minutes.
Great article that helped me get started.
Well if you want to find a perfect XHTML+CSS to PDF converter library, forget it. It's far from possible. Because it's just like finding a perfect browser (XHTML+CSS rendering engine). Do we have one? IE or FF?
I have had some success with DOMPDF. The thing is that you have to modify your HTML+CSS code to go with the way the library is meant to work. Other than that, I have pretty good results.
See below:
The HTML2PDF and HTML2PS that was originally mentioned in opening post was talking about a 2009 package with this link
But there is a better HTML2PDF
It is based on TCPDF though it is partly in French.
You can have table headers or footers that repeat on the pages and have page numbers and total pages. See its examples. I have been using it for over three years and recommend it.
There's a tutorial on Zend's devzone on generating pdf from php (part 1, part 2) without any external libraries. I never implemented this sort of solution, but since it's all php, you might find it more flexible to implement and debug.
I am using fpdf to produce PDF files using PHP. It's working well for me so far to produce simple outputs.
Try grabbing the latest nightly dompdf build - I was using an older version that was a terrible resource hog and took forever to render my pdf. After grabbing a nightly from here.
It only took a few seconds to generate the PDF - AND it was just as nicely rendered as with PrinceXML / Docraptor. Seems like they've seriously optimized the dompdf code since I last used it!

Darryl Hein's mention above of TCPDF is likely a great idea. Nicola Asuni's code is pretty handy and powerful. The only killer is if you ever plan on merging PDF files with your generated PDF it doesn't have those features. You would have to create the PDF and then merge it using something like PDFTK by Sid Steward (www.pdflabs.com/tools/pdftk-the-pdf-toolkit/).
In terms of cost, using a web-service (API) may in many cases be the more sensible approach. Plus, by outsourcing this process you unburden your own infrastructure/backend and - provided you are using a reputable service - ensure compatibility with adjusting web standards, uptime, short processing times and quick content delivery.
I've done some research on most of the web services currently on the market, please find below the APIs that I feel are worth mentioning on this thread, in an order based on price/value ratio. All of them are offering pre-composed PHP classes and packages.
- pdflayer.com - Cost: $ - Quality: ☆☆☆☆
- docraptor.com - Cost: $$$ - Quality: ☆☆☆☆☆
- pdfcrowd.com - Cost: $$ - Quality: ☆☆☆
Quality:
Having the high-quality engine PrinceXML
as a backbone, DocRaptor clearly offers the best PDF quality, returning highly polished and well converted PDF documents. However, the pdflayer API service gets pretty close here. Pdfcrowd does not necessarily score with quality, but with processing speed.
Cost:
pdflayer.com - As indicated above, the most cost-effective option here is pdflayer.com, offering an entirely free subscription plan for 100 monthly PDFs and premium subscriptions ranging between $9.99-$119.99. The price for 10,000 monthly PDF documents is $39.99.
docraptor.com - Offering a 7-Day Free Trial period. Premium subscription plans range from $15-$2250. The price for 10,000 monthly PDF documents is ~ $300.00.
pdfcrowd.com - Offering 100 PDFs once for free. Premium subscription plans range from $9-$89. The price for 10,000 monthly PDF documents is ~ $49.00.
I've used all three of them and this text is supposed to help anyone decide without having to pay for all of them. This text has not been written to endorse any one product and I have no affiliation with any of the products.
If you have access to the command line it's possible to use PhantomJS to create the PDF
from an URL
(remote or local).
It works really well, and is a free solution.
Take a look at this example script made for this exact problem.
This question is pretty old already, but haven't seen anyone mentioning CutyCapt so I will :)
CutyCapt
CutyCapt is a small cross-platform command-line utility to capture WebKit's rendering of a web page into a variety of vector and bitmap formats, including SVG, PDF, PS, PNG, JPEG, TIFF, GIF, and BMP
Perhaps you might try and use Tidy before handing the file to the converter. If one of the renderer chokes on some HTML problem (like unclosed tag), it might help it.
I dont think a php class will be the best for render an xHtml page with css.
What happen when a new css rule come out? (soon css 3.0..)
The best way to render an html page is, obvisiuly, a browser.Firefox 3.0 can natively 'print' in pdf format, torisugary developed an extension (command line print) to use it. Here you'll find it.
Anyway, there are still many problmes runninr firefox just as a pdf converter..
At the moment, i think that wkhtmltopdf is the best (that is the one used by the safari browser), fast, quick, awesome.Yes, opensource as well.. Give it a look
I developed a public API to build PDF files from web pages. It has a nice PHP client class that makes it super easy to use. It uses wkhtmltopdf to render the PDF in the cloud.
No need for anything special in the HTML. No need for absolute URLS in images/css/js links. Works on localhost (dev machine) too.
Currently the service has endpoints in 4 Azure regions: US East, US West, EU North, Southeast Asia.
It's fast since it uses a proprietary protocol to send the web page contents to the API for conversion to PDF.
It's reliable because all endpoints are load balanced.
Free account available for testing or low usage. Details on the web site:
Fine rendering doesn't mean anything. Does it validate?
All browsers do the most they can to just show something on the screen, no matter how bad the input. And of course they do not do the same thing. If you want the same rendering as FireFox, you could use its rendering engine. There are pdf generators for it. It is an awful lot of work, though.
Although there are many solutions offered already, I recommend the following two:
- HTM2PDF - offers an API to convert HTML to PDF and also has a PHP SDK, which makes it very easy to implement in PHP; It offers a choice of server locations in Europe, Asia and the USA
- PDFmyURL - offers an API that does URL and HTML to PDF as well, with roughly the same functionality as HTM2PDF, but works on a load balanced landscape and has been around a little longer
The thing that's different about these two APIs from all the previously mentioned solutions, is that - besides converting HTML to PDF with CSS and JavaScript - it also offers PDF rights management, watermarking and encryption. Therefore it's an all-in-one solution for those who want to hit the ground running.
Disclaimer: I work for Kaiomi, a company that operates both of these websites.
Does the HTML to PDF conversion really need to occur server-side using PHP?
I just came across jsPDF, a client-side solution using HTML5/JavaScript. The MIT-licensed code is on GitHub, too.
TCPDF works fine, no dependencies, is free and constantly bugfixed. It has reasonable speed if supplied HTML/CSS contents is well formated. I normally generate from 50 - 300 kB of HTML input (including CSS) and get PDF output within 1-3 secs with 10 - 15 PDF pages.
I strongly recommend using tidy library as HTML pretty formatter before sending anything to TCPDF.
I've tried a lot of different libraries for PHP. All the listed I've tried. In my opinion TCPDF library is the best compromise performance/usability.It's very simply to install and use, also good performance in small medium application.If you need high performance and very big PDF document, use Zend_PDF module, but get ready to coding hard!
How To Create Dynamic Pdf File In Php Code
If there is people who always search for this kind of stuff, there is a free website which allow you to convert html code & pages to pdf. There is also a (very small) api which allow you to get pdf file from url.
not PHP, but a Java library, which does the thing:
Flying Saucer takes XML or XHTML and applies CSS 2.1-compliant stylesheets to it, in order to render to PDF
It is usable from PHP via system()
or a similar call. Although it requires XML well-formedness of the input
.