I am currently utilizing HTML2Canvas and jsPDF to export a PDF document. When the browser viewport width is 1280 pixels, the resulting PDF displays the UI as intended. However, I have encountered an issue where the UI becomes distorted when viewPort is greater than 1280px. I would appreciate any assistance in resolving this matter to ensure the PDF maintains its intended appearance across all screen sizes.
here’s my code
const pdfExport = async (sections: any[]) => {
dispatch(setIsexporting(true));
let doc = new jsPDF("p", "mm");
let metaTag = document.getElementById('viewport');
metaTag?.setAttribute("content", "width=1280");
const pageHeight = 292; // Height of the page
for (let index = 0; index < sections.length; index++) {
const section = sections[index];
const divToPrint = section.current;
// Check if the section's height is greater than 10 pixels
if (divToPrint.clientHeight > 20) {
await html2canvas(divToPrint).then((canvas) => {
let imgData = canvas.toDataURL("image/jpeg", 1);
let imgWidth = 206; // Reduced width to accommodate padding
let imgHeight = (canvas.height * imgWidth) / canvas.width;
let positionX = 2; // Padding from left side
let positionY = 2; // Padding from top
// Add a new page if it's not the first section
if (index > 0) {
doc.addPage();
}
// Adding page image
doc.addImage(
imgData,
"PNG",
positionX,
positionY,
imgWidth,
imgHeight
);
// Calculate remaining space after adding the image
let remainingSpace = pageHeight - (positionY + imgHeight) + 4;
// If there is remaining space, fill it with a background color
if (remainingSpace > 0) {
doc.setFillColor(
247,
248,
250
);
doc.rect(
positionX,
positionY + imgHeight,
imgWidth,
remainingSpace,
"F"
);
}
// gray border with padding
doc.setDrawColor(247, 248, 250);
doc.setLineWidth(5);
doc.rect(0, 0, 210, 298);
if (index === sections.length - 1) {
doc.save("exhibitors_statistics.pdf");
let metaTag = document.getElementById('viewport');
metaTag?.setAttribute(
"content",
"width=device-width, initial-scale=1"
);
}
});
}
}
dispatch(setIsexporting(false));
};
for small devices its changes the viewport to 1280 but on big screen i dont know why but its not working..
Rishav Singh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.