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

如何使用printThis将两个选择器分别打印到不同页面?

How to Print Separate Elements to Different Pages with printThis

Got it! I’ve used printThis a fair bit, and splitting your two elements onto distinct print pages is totally achievable—here are a couple of reliable approaches:

1. Use CSS Page Breaks (Simplest Method)

The easiest way is to leverage CSS's built-in page break properties, which printThis will respect when you include your print styles.

First, add a print-specific CSS rule:

@media print {
  .print-page-break {
    page-break-after: always;
    /* Ensure it's a block element to work reliably */
    display: block;
    height: 0;
    visibility: hidden;
  }
}

Then, insert this page break element between your two target elements (or adjust the selector to target the second element directly with page-break-before: always):

<div id="pdf">Your first element content here</div>
<div class="print-page-break"></div>
<div id="pdf2">Your second element content here</div>

Now, update your printThis call to include the page break element (or just target both elements—since the CSS will handle the split):

$("#pdf, #pdf2").printThis({
  importCSS: true, // Critical: ensures your print styles are loaded
  loadCSS: "/path/to/your/print-styles.css" // Optional: if your styles are in a separate file
});

2. Dynamically Add Page Breaks (No HTML Modifications)

If you don’t want to alter your original DOM, you can clone the elements and inject a page break between them before printing:

// Clone the elements to avoid modifying the live page
const $printClone = $("#pdf").clone();
const $pageBreak = $("<div class='print-page-break'></div>");
const $secondClone = $("#pdf2").clone();

// Combine them into a single set of content
const $printContent = $printClone.add($pageBreak).add($secondClone);

// Print the combined content
$printContent.printThis({
  importCSS: true,
  base: "", // Keep this empty if your styles are relative to the current page
  debug: false // Set to true if you need to troubleshoot the print preview
});

Quick Notes

  • Make sure your page break element isn’t hidden by other styles (the visibility: hidden keeps it from showing in the page but lets the page break work).
  • Test in different browsers—Chrome, Firefox, and Edge all handle page breaks slightly differently, so a quick preview will confirm it works as expected.
  • If your elements have complex layouts (like floats or flexbox), add print-specific styles to reset them to block layout if needed, as this can help page breaks work reliably.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 14:48:11