import html2canvas from "html2canvas";
import jsPDF from "jspdf";
async function getPdfDownload() {
const content = document.getElementById("contents");
if (!content) return;
const scale = 2;
const canvas = await html2canvas(content, {
scale: scale,
useCORS: true,
logging: false,
windowWidth: content.scrollWidth,
windowHeight: content.scrollHeight,
});
const imgData = canvas.toDataURL("image/png");
const pdf = new jsPDF({
unit: "px",
format: "a4",
orientation: "portrait",
});
const pageWidth = pdf.internal.pageSize.getWidth();
const pageHeight = pdf.internal.pageSize.getHeight();
const widthRatio = pageWidth / canvas.width;
const heightRatio = pageHeight / canvas.height;
const ratio = Math.min(widthRatio, heightRatio);
const canvasWidth = canvas.width * ratio;
const canvasHeight = canvas.height * ratio;
const marginX = (pageWidth - canvasWidth) / 2;
const marginY = (pageHeight - canvasHeight) / 2;
pdf.addImage(imgData, "PNG", marginX, marginY, canvasWidth, canvasHeight);
const pagesNeeded = Math.ceil(canvasHeight / pageHeight);
for (let i = 1; i < pagesNeeded; i++) {
pdf.addPage();
pdf.addImage(
imgData,
"PNG",
marginX,
marginY - pageHeight * i,
canvasWidth,
canvasHeight
);
}
pdf.save("quote.pdf");
}
Now the problem is that on that component I tried both selecting the dom getElementById and by the ref also, this code is also working fine, but when the pdf is generated all the text is just slided downward may be by 10px, and all the other styles remain the same.
New contributor
Ali Ahmad is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.