[php] Convert HTML + CSS to PDF

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?

This question is related to php html css pdf pdf-generation

The answer is


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.


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/).


I suggest DocRaptor (which uses PrinceXML as the "engine")


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:

Original HTML

Converting HTML to PDF


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.


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.


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.


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.


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!


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.


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.


I recommend TCPDF or DOMPDF, in that order.


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.


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.


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.


Web API

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.

Check it here


Although there are many solutions offered already, I recommend the following two:

  1. 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
  2. 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.


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.


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.


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:

https://rotativahq.com


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.


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.


Web API

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.

Check it here


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.


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:

Original HTML

Converting HTML to PDF


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!


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


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.


1) use MPDF !

a) extract in yourfolder

b) create file.php in yourfolder and insert such code:

<?php
include('../mpdf.php');
$mpdf=new mPDF();
$mpdf->WriteHTML('<p style="color:red;">Hallo World<br/>Fisrt sentencee</p>');
$mpdf->Output();   exit;
 ?>

c) open file.php from your browser




2) Use pdfToHtml !

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):

<?php
$source="example.pdf";
$output_fold="FinalFolder";

    if (!file_exists($output_fold)) { mkdir($output_fold, 0777, true);}
$result= passthru("pdftohtml $source $output_fold/new_filename",$log);
//var_dump($result); var_dump($log);
?>

3) enter FinalFolder, and there will be the converted files (as many pages, as the source PDF had..)


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.


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.


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.


1) use MPDF !

a) extract in yourfolder

b) create file.php in yourfolder and insert such code:

<?php
include('../mpdf.php');
$mpdf=new mPDF();
$mpdf->WriteHTML('<p style="color:red;">Hallo World<br/>Fisrt sentencee</p>');
$mpdf->Output();   exit;
 ?>

c) open file.php from your browser




2) Use pdfToHtml !

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):

<?php
$source="example.pdf";
$output_fold="FinalFolder";

    if (!file_exists($output_fold)) { mkdir($output_fold, 0777, true);}
$result= passthru("pdftohtml $source $output_fold/new_filename",$log);
//var_dump($result); var_dump($log);
?>

3) enter FinalFolder, and there will be the converted files (as many pages, as the source PDF had..)


I suggest DocRaptor (which uses PrinceXML as the "engine")


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:

https://rotativahq.com


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


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.


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.


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.


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:

Original HTML

Converting HTML to PDF


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


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.


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.


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.

  1. pdflayer.com - Cost: $ - Quality: ????
  2. docraptor.com - Cost: $$$ - Quality: ?????
  3. 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.


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:

Original HTML

Converting HTML to PDF


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.


Checkout TCPDF. It has some HTML to PDF functionality that might be enough for what you need. It's also free!


I recommend TCPDF or DOMPDF, in that order.


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


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.


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.


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.


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.


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! ^_^


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.


Checkout TCPDF. It has some HTML to PDF functionality that might be enough for what you need. It's also free!


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.


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.


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.


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! ^_^


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/).


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!


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.


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.


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.

  1. pdflayer.com - Cost: $ - Quality: ????
  2. docraptor.com - Cost: $$$ - Quality: ?????
  3. 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.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to pdf

ImageMagick security policy 'PDF' blocking conversion How to extract table as text from the PDF using Python? Extract a page from a pdf as a jpeg How can I read pdf in python? Generating a PDF file from React Components Extract Data from PDF and Add to Worksheet How to extract text from a PDF file? How to download PDF automatically using js? Download pdf file using jquery ajax Generate PDF from HTML using pdfMake in Angularjs

Examples related to pdf-generation

How to convert HTML to PDF using iTextSharp Convert canvas to PDF HTML to PDF with Node.js Save multiple sheets to .pdf how to save DOMPDF generated content to file? Python PDF library Convert Word doc, docx and Excel xls, xlsx to PDF with PHP ITextSharp insert text to an existing pdf What are the minimum margins most printers can handle? Best C# API to create PDF