简体   繁体   中英

Create printable PDF from html dom

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?

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

This is a question I asked a few days ago regarding a similar kind of site/problem.

My solution has been: (1) in Javascript, to set a cookie and then call a PHP script using location.href = ...; (not AJAX) and then (2) have the PHP script access the cookie to determine the sort of report required, and then echo a form which prompts the user to download a file using the correct headers. The PHP was something like the following:

header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=test.doc");

echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
echo "Testing-2-3!";
echo "</body>";
echo "</html>";

It proved impossible to get what I wanted to happen using AJAX because AJAX never allows you to prompt the user.

You could use this method do something similar, but in your case you'd generate a PDF rather than a .doc file (or download one that is pre-prepared).

One advantage of this method, of course, is that it involves no page reloads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM