Create printable PDF from html dom

15,824
var doc = new jsPDF();
doc.text(20, 20, 'Hello world!');
doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');
doc.addPage();
doc.text(20, 20, 'Do you like that?');
// Output as Data URI
doc.output('datauri');

https://parall.ax/products/jspdf , I think this will help you

Share:
15,824
Jonny
Author by

Jonny

Updated on August 10, 2022

Comments

  • Jonny
    Jonny over 1 year

    I have a web page in which a fair amount of the content is dynamically built up (jquery ajax etc) and have a requirement to present a printable version of it.

    I'm coming across all the usual issues re html / printing, which I can probably (given time) get round, but it got me thinking - is there a way of taking the DOM and generating a PDF out of it using javascript. It's probably a bit of a daft question - it sounds a bit tricky, and I'm not too sure even if I could build up a PDF file using javascript, how I would then present it to the user.

    What do people think?

  • Jonny
    Jonny about 12 years
    Hi, thanks - looks really good. Was hoping I could get away with basically taking what was already built up in the DOM and just giving a few more details (page size and the like).
  • Jonny
    Jonny about 12 years
    Hmm, interesting. I will have a play around with this idea. I have a problem in that I have some graphs on the page that are built up in javascript (zingcharts), so I would need to somehow get the pictures back to the server to build up a PDF (or regenerate the graphs in php). Ultimately I am trying to be lazy - I have a nice representation of what I want on the screen (html) at the client. Just can't get all the browsers to play ball when it comes to printing.
  • Milindu Sanoj Kumarage
    Milindu Sanoj Kumarage about 12 years
  • Jonny
    Jonny about 12 years
    I'm going to attempt to see if I can get dompdf to work for me. I should be able to refactor my server side code around a bit so I can rebuild the html that is showing client side on the server. I should be able to send my generated charts back to the server as images (hopefully avoiding path traversal and the like). Couple all this with Nicks suggestion above and in theory I may be able to get a PDF back similar to what I have on the screen. Phew. Thanks for all the help.
  • Jonny
    Jonny about 12 years
    Am going to use both suggested answers. Thanks for your help.
  • Milindu Sanoj Kumarage
    Milindu Sanoj Kumarage over 8 years
    You can't style with CSS, you have to use their API. ( eg: doc.setTextColor(100); )