How do you generate and download a PDF from an HTML div in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you generate and download a PDF from an HTML div in JavaScript?

message-square
0

To generate and download a PDF from a specific HTML <div> in JavaScript, capture and render the element into a PDF document using a client-side library—such as html2pdf.js (which combines html2canvas rendering with jsPDF output), jsPDF + html2canvas, or pdfmake / server-side rendering when exact typography, vector text, or multi-page pagination control matters—and trigger a browser download via an object URL or library save helper. Pure browser DOM APIs do not provide a single built-in div.toPdf() method, so choosing the right approach depends on whether you want quick visual DOM capture or crisp selectable text and predictable page breaks.


1. Quick Client-Side DOM-to-PDF Export with html2pdf.js

For straightforward UI snapshots or receipts inside a <div>, html2pdf.js renders the target DOM element to a canvas and writes it into a downloadable PDF in one pipeline while letting you configure margins, filename, and page-break rules:

// Download an HTML <div> as a PDF using html2pdf.js (loaded via bundler or script tag)
async function downloadDivAsPdf(divElement, fileName = "report.pdf") {
  if (!(divElement instanceof HTMLElement)) {
    throw new TypeError("Expected a valid HTMLElement for divElement.");
  }

  if (typeof fileName !== "string" || fileName.trim() === "") {
    throw new TypeError("Expected a non-empty fileName string.");
  }

  if (typeof html2pdf !== "function") {
    throw new Error("html2pdf is not available in the current scope.");
  }

  const safeName = fileName.toLowerCase().endsWith(".pdf") ? fileName : `${fileName}.pdf`;

  const options = {
    margin: 10,
    filename: safeName,
    image: { type: "jpeg", quality: 0.98 },
    html2canvas: { scale: 2, useCORS: true },
    jsPDF: { unit: "mm", format: "a4", orientation: "portrait" },
    pagebreak: { mode: ["avoid-all", "css", "legacy"] }
  };

  await html2pdf().set(options).from(divElement).save();
}

// Example usage:
// const invoiceDiv = document.querySelector("#invoice-box");
// downloadDivAsPdf(invoiceDiv, "invoice-2026");
  • Image-based fidelity vs. selectable text: Canvas-based DOM capture preserves CSS layout closely, but text inside the resulting PDF is typically rasterized rather than selectable/searchable vector text.
  • CORS and external images: Enable useCORS: true when rendering external images, and ensure remote image servers send proper Access-Control-Allow-Origin headers so the canvas does not become tainted.

2. Explicit Control with html2canvas + jsPDF (and Manual Download Trigger)

When you want finer control over canvas scaling, multi-page slicing, or triggering a file download manually from a generated Blob using URL.createObjectURL() and a temporary <a> click, pair html2canvas with jsPDF (or trigger a Blob download cleanly):

// Helper to trigger a browser download from any Blob or PDF Blob
function triggerBlobDownload(blob, fileName = "document.pdf") {
  if (!(blob instanceof Blob)) {
    throw new TypeError("Expected a Blob instance.");
  }

  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = fileName;
  document.body.appendChild(link);
  link.click();
  link.remove();

  setTimeout(() => {
    URL.revokeObjectURL(url);
  }, 1000);
}

// Render a <div> with html2canvas + jsPDF and download via Blob URL
async function exportDivWithJsPdf(divElement, fileName = "summary.pdf") {
  if (!(divElement instanceof HTMLElement)) {
    throw new TypeError("Expected a valid HTMLElement.");
  }

  const canvas = await html2canvas(divElement, {
    scale: 2,
    backgroundColor: "#ffffff"
  });

  const { jsPDF } = window.jspdf;
  const pdf = new jsPDF({
    orientation: "portrait",
    unit: "mm",
    format: "a4"
  });

  const pageWidthMm = pdf.internal.pageSize.getWidth();
  const pageHeightMm = (canvas.height * pageWidthMm) / canvas.width;
  const imgData = canvas.toDataURL("image/png");

  pdf.addImage(imgData, "PNG", 0, 0, pageWidthMm, pageHeightMm);
  const pdfBlob = pdf.output("blob");
  triggerBlobDownload(pdfBlob, fileName);
}
  • Clean up object URLs: Always call URL.revokeObjectURL(url) after downloading so memory is released.
  • Hide interactive controls before capture: Temporarily hide buttons, toolbars, or inputs inside the <div> (or clone and style a print-ready container) so UI chrome does not appear inside the PDF.

3. When to Use Server-Side / Vector PDF Generation Instead

DOM-to-canvas PDFs can split lines awkwardly across page boundaries or produce large image-heavy files; for multipage reports, tables, or crisp selectable text, generate the PDF on a backend service (for example, using Playwright / Puppeteer or a native PDF generator like PDFKit / pdf-lib) and return it with Content-Type: application/pdf and Content-Disposition: attachment:

// Fetch a pre-rendered PDF from a backend endpoint and download it
async function downloadServerGeneratedPdf(endpointUrl, payload, fileName = "report.pdf") {
  const response = await fetch(endpointUrl, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload)
  });

  if (!response.ok) {
    throw new Error(`Failed to generate PDF (HTTP ${response.status}).`);
  }

  const pdfBlob = await response.blob();
  triggerBlobDownload(pdfBlob, fileName);
}
  • Consistent cross-device output: Server rendering avoids differences in local user fonts, screen DPI scaling, and browser extensions.
  • Better for long documents: Headless browser print/PDF engines handle CSS @page rules, headers/footers, and page breaks more reliably than raw canvas slicing.

TL;DR: Generate and download a PDF from a <div> in JavaScript by rendering the element with html2pdf.js or html2canvas + jsPDF (cleaning up URL.createObjectURL() with URL.revokeObjectURL() and hiding UI controls during capture), or fetch a server-generated PDF Blob when you need crisp selectable text and strict multi-page formatting.