简体   繁体   中英

Print a pdf created with jsPDF in all browsers

So, I have dynamically created a pdf, and now i want to print it:

var doc = new jsPDF();
var name = "Doe, John"
doc.setFontType("normal");
doc.setFontSize(12);
doc.text(20,20,'Name: '+ name);

//do something that prints the pdf...

So, how do I take this doc variable and print it. Everywhere else I found uses the url of the pdf. Do I need to create a url for it first?

So, the solution I am currently going with is to show the pdf in a new tab/window, from which the pdf can be printed.

window.open(doc.output('datauristring'));

Unfortunately, this only works in Chrome. Anyone know how to get it working in IE, Firefox, Safari, etc.?

I still wonder if there is a way to skip this step (of opening the pdf and then requiring another button to be pushed).

There is a method autoPrint() provided by jsPDF library. You can use that as shown below

var doc = new jsPDF();
var name = "Doe, John"
doc.setFontType("normal");
doc.setFontSize(12);
doc.text(20,20,'Name: '+ name);
doc.autoPrint();
//This is a key for printing
doc.output('dataurlnewwindow');

Try this:

window.open(doc.output('bloburl'), '_blank');

This can have problems with adblock sometimes.

So, in conclusion, for Chrome and Safari, use

window.open(doc.output('datauristring'));

but for IE and Firefox, use

doc.save();

These will both allow you to open the pdf in a new window, from which it can be printed. For those who have taken the time to figure out what is necessary on other browsers, feel free to add your research here...

All you need is to add this

doc.save('Test.pdf');

(I suppose you already have all the above written code inside the button trigger which user clicks to get pdf)

You better implement "printjs" from npm, convert jspdf document to blob and print it like this

 const data = PDF.output('blob') const blobUrl = URL.createObjectURL(data); printJS(blobUrl);

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