如何使用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: hiddenkeeps 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

