Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.1 kB
2
Indexable
Never
// Import required libraries
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';

// Define function to convert HTML to PDF
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');
}

// Call the function with an array of HTML elements
const htmlElements = [document.getElementById('div1'), document.getElementById('div2'), document.getElementById('div3')];
convertHtmlToPdf(htmlElements, { orientation: 'portrait', unit: 'mm', format: 'a4', filename: 'converted.pdf' });