Skip to content

ES6 - 页面打印

JavaScript 提供了一种简单的方法,允许用户使用 window.print() 方法打印当前网页的内容。该方法会打开浏览器的标准打印对话框,允许用户选择打印机并配置打印设置。

window.print() 函数可以很容易地通过按钮点击或其他用户交互触发。

以下 HTML 代码演示了如何添加一个按钮,当点击该按钮时,将调用当前页面的打印对话框。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Page Printing Example</title>
<style>
/* Basic styling for the page */
body { font-family: Arial, sans-serif; margin: 20px; }
.printable-content { border: 1px solid #eee; padding: 15px; }
.no-print { margin-top: 20px; }
/* CSS for print media */
@media print {
body { margin: 0; font-size: 12pt; }
.no-print { display: none; } /* Hide elements not meant for printing */
.printable-content { border: none; }
h1 { color: black; }
}
</style>
</head>
<body>
<h1>Web Page Content</h1>
<div class="printable-content">
<p>This is the main content of the page that will be printed.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
<div class="no-print">
<button id="printButton">Print this Page</button>
</div>
<script>
document.getElementById('printButton').addEventListener('click', () => {
window.print();
});
</script>
</body>
</html>

当您在浏览器中打开此 HTML 文件并点击“打印此页”按钮时,浏览器会弹出打印对话框。带有 printable-content 类的 div 中的内容将包含在打印预览中。按钮本身(位于带有 no-print 类的 div 中)由于 @media print CSS 规则而在打印输出中被隐藏。

使用 CSS 进行打印样式设置(@media print)

Section titled “使用 CSS 进行打印样式设置(@media print)”

通常需要为打印页面设置与屏幕显示不同的样式。您可以使用 CSS 的 @media print 规则在打印页面时应用特定的样式。常见的用例包括:

  • 隐藏非必要元素,如导航栏、页脚或按钮(如示例中 .no-print 类所示)。
  • 更改字体大小、颜色和布局,以提高在纸上的可读性。
  • 确保背景和图像(如果需要)能正确打印。
  • 展开可折叠内容或显示链接的 URL。

通过将 window.print() 与精心设计的 CSS 打印样式结合使用,您可以为打印网页提供良好的用户体验。