如何触发浏览器使用 window.print() 将 HTML 转换为 PDF

2025-06-04

如何触发浏览器使用 window.print() 将 HTML 转换为 PDF

以下是如何在客户端通过 html/css 创建 PDF(无需后端或外部库)。我们将利用window.print()和一些特定的 CSS。

不幸的是,这在移动浏览器上不起作用(正如评论中指出的那样)。

该功能所需的样式window.print()



* {
    font-family: Arial, Helvetica, sans-serif;
    color: rgb(65, 65, 65);
    -webkit-print-color-adjust: exact !important;
    color-adjust: exact !important;
    print-color-adjust: exact !important;
}

@media print {
   @page {
     margin-left: 0.8in;
     margin-right: 0.8in;
     margin-top: 0;
     margin-bottom: 0;
   }
}

#container {
    width: 800px;
    margin: 0 auto;
}



Enter fullscreen mode Exit fullscreen mode

当然,您可以为font-familycolor和设定其他值#container。为您的自定义 PDF 添加其余样式。

接下来,我们需要触发window.print()浏览器原生的功能。因此,请在script标签中添加以下 js。



document.addEventListener("DOMContentLoaded", () => {
    let printLink = document.getElementById("print");
    let container = document.getElementById("container");

    printLink.addEventListener("click", event => {
        event.preventDefault();
        printLink.style.display = "none";
        window.print();
    }, false);

    container.addEventListener("click", event => {
        printLink.style.display = "flex";
    }, false);

}, false);


Enter fullscreen mode Exit fullscreen mode

这是一个基本的 html:



<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Add here the styles and script we described up -->
    <title>This will be the title of the pdf file</title>
</head>

<body id="container">

    <a href="#" id="print">GENERATE PDF!</a>

    <h1>Super cool custom pdf</h1>

    <p>This pdf is generated from the client side without any external libraries!</p>

</body>

</html>



Enter fullscreen mode Exit fullscreen mode

而且...就是这样!

以下是我们所做的工作的运作方式:

生成 PDF-GIF

文章来源:https://dev.to/climentea/simple-way-to-generate-pdf-from-html-21mh
PREV
Um júnior e um teste técnico:战斗。目录 目的 初步设计和设计项目 问题分析 问题结论
NEXT
泡沫与捕获的最终结论