Can I use html() multiple times in a PDF
I want to export a PDF in a function.
At the same time, the content inside is generated by using .html() many times.
If only once .html() there is no problem at all.
But I found that I used it twice, and the content of the second time would not be generated in PDF.
So I want to know,.html() Only once?
this is code
async getPdfByJSPDF(){
// console.log(this.$refs.ProjectDesignReport.changeHeightToA4(),"这里在执行子组件的改变高度函数")
const { width:A4W, height: A4H } = {width:960,height:1362};
const { unit, orientation, format } = {unit:"px", orientation:"p", format:[A4H,A4W]} // optionPDF(A4W,A4H);
// console.log(unit, orientation, format,"unit, orientation, format")
let thePDF = new JsPDF({ orientation, unit, format });
thePDF = addSelfFont(thePDF, MyFont, "Alibaba-PuHuiTi-Regular-normal" ); // 增加字体
const pdfBody = document.querySelector("#export");
await thePDF.html(pdfBody,{x:0,y:0});
await thePDF.html(pdfBody,{x:0,y:1362*3});
const num = thePDF.internal.getNumberOfPages(); // 可以获得页数
for(let i = 0; i < num; i+=1) {
thePDF.setPage(i);
thePDF.setTextColor("red");
thePDF.setFontSize(32);
thePDF.text(`${thePDF.internal.getCurrentPageInfo().pageNumber }/${ num}`,40,40, );
}
thePDF.save();
}
By the way, we've dealt with this problem in other ways, so now we're just a little curious.
At the same time, if I continue to use html() in html() callback, I can write the content into PDF, but in the way of covering the previous one.
version 2.3.0
Can confirm. Calling html a second time has no effect.
Yes, but if you call html again in the callback function, you can override the last time. That's more interesting 😀 So we finally adopted the window.print to deal with pdf
Yeah, I thought I could use .addPage() after .html() and call .html() again to insert anoter DOM element into a new page. Turns out I can't. Is there a differrent way to go about doing this?
Interesting. So then I'm stuck and wondering if someone can help: I have a document where I'd like to print html twice. Once at the following coordinates: {x: 15, y: 100} and the second time slightly lower (depending on the size of a table in between, generated with autotable), for example at {x: 15, y: 150}. I achieved this previously with the deprecated function fromHtml
How can I achieve this with the latest version of jspdf (v2.3.0) and the html function?
Another interesting, (maybe related?) issue is the font size of the html - I tried to use inline styling on the div that wraps the text with a fixed width (as described in #3088 ), and tried forcing the font-size. Regardless of what I enter though, I always get the same font size (nothing smaller).
I've attached an illustration of my current struggle. Here is my code snippet to generate the pdf,
document.html(
`<div style="width: 180px !important; font-size: 14px; font-family: Arial, Helvetica, sans-serif; line-height: 1.2 !important;">${text}</div>`,
{
// eslint-disable-next-line object-shorthand, func-names
callback: function () {
doc.save();
},
x,
y,
}
);

This is a duplicate of #2899, which contains two more examples to reproduce this bug.
I'd be willing to create a pull request with a fix. Any clue where I should look first would be appreciated. It seems html2canvas is executed correctly for subsequent html() calls, but the result does not end up in the pdf document.
Some workarounds:
- Use
html2canvasdirectly - Use
html-to-imageif your users can use Chrome/Firefox(Safari is not well supported). This library is using SVG and I personally think it's better thanhtml2canvas.
Using html2canvas directly has the disadvantage that text will be converted to an image, whereas using doc.html() preserves text as text. And html-to-image is not an option because of the Safari limitations.
Using
html2canvasdirectly has the disadvantage that text will be converted to an image, whereas usingdoc.html()preserves text as text. Andhtml-to-imageis not an option because of the Safari limitations.
Yes, that's why they are workarounds.
BTW: If server side rendering is activated, HTML element transformed by html-to-image will be more accurate than html2canvas does(css shadow, position, ... or any other things Canvas can't do). I'm now using both html-to-image & html2canvas with jsPDF to create complicate worksheets for user. And I do hope the text could be copied. :)
@helsonxiao that is a very interesting workaround suggestion. The goal of my PDF to create not too complicated reports with a few charts and some minimal text. Copying text is not a "requirement".
So this might be worth looking into...
Would you be able to share some examples how you are using html-to-image with jsPDF to create a pdf?
@helsonxiao that is a very interesting workaround suggestion. The goal of my PDF to create not too complicated reports with a few charts and some minimal text. Copying text is not a "requirement".
So this might be worth looking into...
Would you be able to share some examples how you are using
html-to-imagewithjsPDFto create a pdf?
Sure! Just turn html into image then call addImage API.
import html2canvas from 'html2canvas';
import * as htmlToImage from 'html-to-image';
// using svg
image = await htmlToImage.toPng(element, {
// cacheBust: true,
// fontEmbedCss,
});
// or canvas
image = await html2canvas(element, {
// useCORS: true,
});
doc.addImage(
image,
imgX,
imgY,
scaledImgW,
scaledImgH,
undefined,
comporession,
);
Closing this in favor of #2899.
Hey hi, Try with Timeout functions with 5 seconds delay. It works great!
const createPDF = async (index) => {
let pdf = new jsPDF("portrait", "pt", "a4");
let data = await document.querySelector(#reportCardPdf_${index});
pdf.html(data).then(() => {
pdf.save(ExamReportCard_${index + 1}.pdf);
}
);
};
const handlePdfGeneration = () => {
const delay = 2; //please add delay minimum of 2 seconds to avoid white pages in pdf
const limit = state.data.length;
let i = 0;
const limitedInterval = setInterval(() => {
createPDF(i++);
if (i > limit) {
clearInterval(limitedInterval);
}
}, delay * 1000);
}
Didnt work for me :(
I've found a workaround for generating multipage PDF using .html() method,
const doc = new jsPDF("p", "pt", "a4");
let pageHeight = doc.internal.pageSize.getHeight();
doc.html(document.getElementById("Page1"), {
callback: function (pdf) {
pdf.addPage("a4", "l");
pdf.html(document.getElementById("Page2"), {
callback: function (pdf2) {
pdf2.addPage("a4", "l");
pdf2.html(document.getElementById("Page3"), {
callback: function (pdf3) {
pdf3.save("multipage.pdf")
},
x: 0,
y: 2 * pageHeight,
});
},
x: 0,
y: pageHeight,
});
},
x: 0,
y: 0,
});
I've tried your solution and it renders only the first element(Page 1). The rest of the pages (with elements Page2 and Page3) are empty. Can you maybe provide a JSFiddle working example? Thanks.
I've tried your solution and it renders only the first element(Page 1). The rest of the pages (with elements Page2 and Page3) are empty. Can you maybe provide a JSFiddle working example? Thanks.
U can try this: https://codesandbox.io/s/a11y-tabs-forked-rr814c?file=/src/App.js
I found an answer to this question (refrencing)
Just use await and make sure to return doc inside the callback
something like this
var doc = new jspdf.jsPDF({
orientation: 'p',
unit: 'pt',
format: 'letter'
});
var field = "<b>html test </b>";
doc.text(10, 10, "test");
//add first html
await doc.html(field, {
callback: function (doc) {
return doc;
},
width: 210,
windowWidth: 210,
html2canvas: {
backgroundColor: 'lightyellow',
width: 210,
height: 150
},
backgroundColor: 'lightblue',
x: 10,
y: 50,
autoPaging: 'text'
});
window.open(doc.output('bloburl'));
now you can call doc.html as many times as you want for that same document
I've found a workaround for generating multipage PDF using .html() method,
const doc = new jsPDF("p", "pt", "a4"); let pageHeight = doc.internal.pageSize.getHeight(); doc.html(document.getElementById("Page1"), { callback: function (pdf) { pdf.addPage("a4", "l"); pdf.html(document.getElementById("Page2"), { callback: function (pdf2) { pdf2.addPage("a4", "l"); pdf2.html(document.getElementById("Page3"), { callback: function (pdf3) { pdf3.save("multipage.pdf") }, x: 0, y: 2 * pageHeight, }); }, x: 0, y: pageHeight, }); }, x: 0, y: 0, });
@prasheel888 Thank you for this. Working as expected.
I've found a workaround for generating multipage PDF using .html() method,
const doc = new jsPDF("p", "pt", "a4"); let pageHeight = doc.internal.pageSize.getHeight(); doc.html(document.getElementById("Page1"), { callback: function (pdf) { pdf.addPage("a4", "l"); pdf.html(document.getElementById("Page2"), { callback: function (pdf2) { pdf2.addPage("a4", "l"); pdf2.html(document.getElementById("Page3"), { callback: function (pdf3) { pdf3.save("multipage.pdf") }, x: 0, y: 2 * pageHeight, }); }, x: 0, y: pageHeight, }); }, x: 0, y: 0, });
Thank You mate!
I've found a workaround for generating multipage PDF using .html() method,
const doc = new jsPDF("p", "pt", "a4"); let pageHeight = doc.internal.pageSize.getHeight(); doc.html(document.getElementById("Page1"), { callback: function (pdf) { pdf.addPage("a4", "l"); pdf.html(document.getElementById("Page2"), { callback: function (pdf2) { pdf2.addPage("a4", "l"); pdf2.html(document.getElementById("Page3"), { callback: function (pdf3) { pdf3.save("multipage.pdf") }, x: 0, y: 2 * pageHeight, }); }, x: 0, y: pageHeight, }); }, x: 0, y: 0, });
saved me Thanks