Long Image that will fit in multiple pages
First set doc instance to accept unit as 'pt'. Post this the next step would be to check if image is greater than page size, if so, image will span over multiple pages, as we have docHeight with us, we would be able to get part of the image that would be contained in current page. Now, repeat this for next page (remaining image is say larger again for next page). Code would like below (Here, I wanted image to only occupy 0.8 of page width, height is adjusted accordingly):
//Read Canvas to be exported
const appRolesElement = document.getElementById('app-roles-element');
const appRolesCanvas = await html2canvas(appRolesElement, { onclone: function (document) {
//Different style requirement for export
document.querySelectorAll('.right-wrapper').forEach(el => {
el.style.marginLeft = '0px';
})
}});
const doc = new jsPDF({
compress: true,
orientation: 'p',
unit: 'pt',
format: 'a4'
});
var docWidth = doc.internal.pageSize.getWidth();
var docHeight = doc.internal.pageSize.getHeight();
let heightInPlace = 0;
let appRolesImageDisplayHeight = getDisplayHeight(appRolesCanvas.height, appRolesCanvas.width, docWidth*0.8);
let appRolesIterationCounter = 0;
let appRolesSourceClipStartY = 0;
//Keep checking if a new page is required
while(appRolesImageDisplayHeight > 0) {
if(appRolesIterationCounter > 0) {
doc.addPage();
heightInPlace = 10;
}
++appRolesIterationCounter;
const remainingHeightInPage = docHeight - heightInPlace;
const sourceHeightToBeDisplayed = getSourceHeight(remainingHeightInPage, appRolesCanvas.width, docWidth);
const clippedImage = await convertURIToImageData(appRolesImage, appRolesCanvas.width, sourceHeightToBeDisplayed, appRolesSourceClipStartY);
doc.addImage(clippedImage, 'JPEG', 10, heightInPlace, docWidth * 0.8, remainingHeightInPage * 0.8);
heightInPlace += (remainingHeightInPage * 0.8) + 5;
appRolesImageDisplayHeight = appRolesImageDisplayHeight - remainingHeightInPage;
appRolesSourceClipStartY += sourceHeightToBeDisplayed;
}
doc.save("export.pdf");
const getDisplayHeight = (sourceHeight, sourceWidth, displayWidth) => {
return (displayWidth/sourceWidth)*sourceHeight;
};
const getSourceHeight = (displayHeight, sourceWidth, displayWidth) => {
return displayHeight*(sourceWidth/displayWidth);
}
Additionally, please use attribute data-html2canvas-ignore for ignoring contents from exports.