Untitled
unknown
plain_text
3 years ago
2.4 kB
10
Indexable
async function convertHtmlToPdf(htmlElements, options = {}) {
// Create a new PDF document
const pdf = new jsPDF(options.orientation || 'portrait', options.unit || 'mm', options.format || 'a4');
const pageHeight = pdf.internal.pageSize.height - 10;
let currentPage = 1;
let lastYPos = 10;
for (const element of htmlElements) {
// Use HTML2Canvas to create an image of the element
const canvas = await html2canvas(element);
// Calculate the height of the element and how many pages it will span
const elementHeight = canvas.height * 72 / 96; // Convert px to pt
let numPages = Math.ceil(elementHeight / pageHeight);
// Adjust the page height based on the remaining height of the element
let remainingHeight = elementHeight;
while (numPages > 1 && (currentPage + numPages - 1) * pageHeight > lastYPos + remainingHeight) {
numPages--;
}
const pageHeightAdjusted = remainingHeight / numPages;
// Add the element to the PDF document, splitting it into multiple pages if necessary
let yPos = lastYPos;
for (let i = 0; i < numPages; i++) {
if (lastYPos + pageHeightAdjusted > currentPage * pageHeight) {
pdf.addPage();
currentPage++;
yPos = 10;
}
const height = Math.min(pageHeightAdjusted, (currentPage * pageHeight) - lastYPos - 10);
const imgData = canvas.toDataURL('image/png');
pdf.addImage(imgData, 'PNG', 10, yPos, pdf.internal.pageSize.width - 20, height);
remainingHeight -= height;
yPos += height + 10;
lastYPos = yPos;
}
}
// Save the PDF document
pdf.save(options.filename || 'converted.pdf');
}
const htmlElements = [
document.querySelector('.page1'),
document.querySelector('.page2'),
document.querySelector('.page3'),
document.querySelector('.page4'),
document.querySelector('.page5'),
document.querySelector('.page6'),
document.querySelector('.page7'),
document.querySelector('.page8')];
function getPdf3(){
convertHtmlToPdf(htmlElements, { orientation: 'portrait', unit: 'mm', format: 'a4', filename: 'converted.pdf' });
}Editor is loading...