You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jsPDF将两个指定DIV内容分别导出至PDF不同页面

Solution: Render Multiple Divs to Separate PDF Pages with jsPDF

Got it, let's figure this out! The basic text() method in jsPDF only handles plain text, so to render rich HTML content from your divs, you'll need to use jsPDF's html() utility (which works with html2canvas under the hood to convert HTML to a canvas, then add it to the PDF). Here's a straightforward implementation:

Step 1: Load Required Libraries

First, make sure you have both jsPDF and html2canvas available in your project (you can use CDNs or local files):

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>

Step 2: Your HTML Setup

Assuming your divs have the IDs you mentioned:

<div id="DIV_ID_1">
  <h2>First Page Content</h2>
  <p>This is the content from your first div, with <strong>formatted text</strong>, images, or any other HTML elements.</p>
</div>

<div id="DIV_ID_2">
  <h2>Second Page Content</h2>
  <ul>
    <li>List item one</li>
    <li>List item two</li>
  </ul>
</div>

<button onclick="createPDF()">Generate & Save PDF</button>

Step 3: The JavaScript Function

Here's the code to generate a PDF where each div gets its own page:

async function createPDF() {
  // Initialize a jsPDF instance (portrait orientation, A4 size, mm units)
  const pdfDoc = new jspdf.jsPDF({
    orientation: 'p',
    unit: 'mm',
    format: 'a4'
  });

  // Grab your two div elements
  const divPage1 = document.getElementById('DIV_ID_1');
  const divPage2 = document.getElementById('DIV_ID_2');

  // Render first div to the initial page
  await pdfDoc.html(divPage1, {
    callback: (doc) => {
      // Add a new blank page after the first div is rendered
      doc.addPage();
    },
    x: 10, // Left margin
    y: 10, // Top margin
    width: 190 // Content width (A4 total width is 210mm, minus 10mm left/right margins)
  });

  // Render second div to the new page, then save the PDF
  await pdfDoc.html(divPage2, {
    callback: (doc) => {
      doc.save('example.pdf');
    },
    x: 10,
    y: 10,
    width: 190
  });
}

Quick Notes:

  • The html() method is asynchronous, so we use await to make sure each div finishes rendering before we add a new page or save the PDF.
  • Adjust the x, y, and width values to tweak margins and content sizing to match your needs.
  • If a div's content is longer than one page, jsPDF will automatically split it — but if you strictly want one div per page, just ensure each div's content fits within an A4 page (or adjust the page format).

内容的提问来源于stack exchange,提问作者Jose

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:14:29