I am trying to export visible parts of a webpage to PDF using JavaScript. My content includes elements like tables and charts that often have scrolled views. I’ve attempted to use both html2canvas and dom-to-image to capture the content, but both libraries reset scroll positions to the top-left corner (0, 0) instead of capturing the content as it is visible on the user’s screen.What I export
What I get exported
What I Tried:
html2canvas: I tried passing scrollX and scrollY parameters adjusted to match the current scroll position of the content. Despite this, the resulting image still captures the content from the top, ignoring the actual scroll position.
html2canvas(content, {
scrollX: -content.scrollLeft,
scrollY: -content.scrollTop,
width: content.clientWidth,
height: content.clientHeight
});
dom-to-image: I used dom-to-image with similar parameters, hoping it might handle dynamic content better. However, the issue persisted with similar results.
domtoimage.toPng(content, {
height: content.clientHeight,
width: content.clientWidth
});
Full function code:
export const exportAsPDFSingleReport = async (
content,
fileName,
fileType,
screenWidth
) => {
const MAX_IMAGE_WIDTH = 2000;
const MAX_IMAGE_WIDTH_HALF_SCREEN = 1000;
const IMAGE_WIDTH_OFFSET = 100;
const childDiv = content.querySelector("div");
const reportType = childDiv ? childDiv.dataset.reporttype : null;
let currentWidth;
if ((reportType !== reportTypes.PieChart && reportType !== reportTypes.CreatedVsResolved) || screenWidth <= 1149) {
currentWidth = Math.min(MAX_IMAGE_WIDTH, screenWidth - IMAGE_WIDTH_OFFSET);
} else {
currentWidth = Math.min(MAX_IMAGE_WIDTH_HALF_SCREEN, screenWidth / 2 - 5);
}
content.setAttribute("style", `width: ${currentWidth}px`);
try {
const canvas = await html2canvas(content, {
scrollX: -content.scrollLeft,
scrollY: -content.scrollTop,
width: content.clientWidth,
height: content.clientHeight,
windowWidth: content.scrollWidth,
windowHeight: content.scrollHeight,
backgroundColor: null,
useCORS: true
});
const imgData = canvas.toDataURL("image/png");
const img = new Image();
img.src = imgData;
img.onload = function () {
const imageWidth = img.width;
const imageHeight = img.height;
const orientation = imageHeight > imageWidth ? "p" : "l";
const pdf = new jsPDF({
orientation,
unit: "px",
format: [imageWidth, imageHeight]
});
pdf.addImage(imgData, "PNG", 0, 0, imageWidth, imageHeight);
pdf.save(`${fileName}.${fileType}`);
};
} catch (error) {
console.error("Error exporting as PDF:", error);
}
};
Expected Results: The libraries should capture the part of the webpage that is currently visible to the user, respecting the current scroll position in both vertical and horizontal directions.
Actual Results: The captured image resets to the top-left corner of the content area, ignoring any user-applied scroll, thus not reflecting the visible area intended for export.