eKoopmans / html2pdf.js

Client-side HTML-to-PDF rendering using pure JS.
MIT License
4.07k stars 1.38k forks source link

Background Color Not Applied on Last Page in PDF Generation #658

Open ajmal-pidilite10 opened 1 year ago

ajmal-pidilite10 commented 1 year ago

Helllo @drbeat ,

Description: I am using the html2pdf.js version "0.9.3" library to generate PDFs from dynamic content in my web application. However, I have encountered an issue where the background color is not applied on the last page of the generated PDF when the content does not fill the entire page.

Expected Behavior: I expected the last page of the PDF to have the background color applied, regardless of whether the dynamic content fills the entire page or not.

Actual Behavior: The background color is not being applied to the last page of the PDF when the content does not fully occupy the page. As a result, the last page appears without the desired background color.

Code Snippets:

import html2pdf from "html2pdf.js";

export const getPDF = async (containerID, fileName) => { let opt = { margin: [15, 0, 25, 0], filename: fileName, image: { type: "jpeg", quality: 0.98 }, html2canvas: { scale: 1.1, dpi: 191, removeContainer: true, }, jsPDF: { orientation: "portrait", unit: "px", hotfixes: ["px_scaling"], putOnlyUsedFonts: true, }, }; const contentContainer = document.getElementById(containerID); if (contentContainer) { const pdf = html2pdf() .from(contentContainer) .set(opt) .toPdf() .get("pdf") .then((pdf) => { var totalPages = pdf.internal.getNumberOfPages(); for (let i = 2; i <= totalPages; i++) { console.log(pdf.internal.pageSize.getHeight()); pdf.setPage(i); pdf.setFontSize(10); pdf.setTextColor("#000"); pdf.text( i + " of " + totalPages, pdf.internal.pageSize.getWidth() - 410, pdf.internal.pageSize.getHeight() - 20, { align: "center", } ); } }); return pdf.outputPdf("blob", fileName); } };

export const generatePDF = async (containerID, quotationName) => { try { const pdfBlob = await getPDF(containerID, ${quotationName}.pdf); return new File([pdfBlob], ${quotationName}.pdf, { type: "application/pdf", }); } catch (error) { console.error("Error generating PDF:", error); } };

export const generatePDFOnMount = async ( containerID, decodedQuotationName, setQuotationBlob, setIsDisabledButton ) => { try { const quotationFile = await generatePDF(containerID, decodedQuotationName); setQuotationBlob(quotationFile); setIsDisabledButton(false); } catch (error) { console.error("Error generating PDF:", error); } finally { setIsDisabledButton(false); } };

gezichenshan commented 1 year ago

YES, any solutions? it is because it first converts html to canvas and then pdf so there is no solution?