3

While using browsers like Chrome and Firefox, there is an option to print the page to PDF (that is saving the webpage as a PDF file).

<a href="JavaScript:window.print();">Print this page</a>

This code opens up the print page from where the user should manually choose print to PDF. Can this be done automatically? If so please help.

evotopid
  • 5,288
  • 2
  • 26
  • 41
Preets
  • 117
  • 1
  • 2
  • 9

3 Answers3

2

You can not print page to pdf with Javascript. You have to use server side script to print page to pdf. In PHP, you can use 3rd party PDF library like http://www.tcpdf.org .

Aurelio De Rosa
  • 21,856
  • 8
  • 48
  • 71
Thein Hla Maw
  • 685
  • 1
  • 9
  • 28
2

There is not much available to print to PDF in Javascript.

The most supported option is indeed to generate it server-side using a library such as tcpdf (as shown by Thein Hla Maw).

I don't think Mark's solution is the correct one, since it requires the users to have some software installed.

For pure javascript PDF generation, there is this.

NB : thanks SO :-)

Community
  • 1
  • 1
Florian Margaine
  • 58,730
  • 15
  • 91
  • 116
0

Yes... provided that your users have a few things installed.

  1. They need a PDF print driver, such as PrimoPDF
  2. If you want to automatically print to this driver, they need to have a plugin installed, such as JS Print Setup (for Firefox) or MeadCo ScriptX for IE

Then, using the API of said plugin, you can choose which driver to print to. You can even skip the print dialog.

A better option, however, would be the generate the PDF server-side, stream it to them, and then use JavaScript inside the PDF to automatically open the print dialog as soon as they view it. This way they don't need any plugins.

mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • If the users are running Linux it's pretty easy :-) – Pointy Nov 13 '11 at 17:23
  • 1
    @Pointy: Why's that? Do they come with a PDF printer pre-installed? – mpen Nov 13 '11 at 17:24
  • @Mark i have tried using html2pdf and dompdf as well.. while they seem as good options they actually are not.They don print tables rendering takes too long and image size is fixed and very erratic.... – Preets Nov 13 '11 at 17:27
  • Yes, printing to PDF is available more-or-less natively in Linux. At least it is in the Ubuntu distributions, since basically forever. – Pointy Nov 13 '11 at 17:28
  • @Preets: Well, you're welcome to go with my first suggestion, but it works best if you have a very controlled user base. Or try TC PDF as Thein suggested. I'm having some troubles with dompdf as well, but I think it beats the troubles of cross-browser compatibilities and teaching your 50+ y/o user base to install stuff. – mpen Nov 13 '11 at 17:41