跳至页脚内容
PDF 工具

如何在 JavaScript 中打印 PDF 文件

1.0 介绍

便携式文档格式(PDF)由Adobe开发,目的是用于共享带有文本和图形的文档。 在线打开PDF文档需要额外的程序。PDF文件对当今社会的关键信息非常重要。 许多企业使用PDF文件创建文档和发票。 为了满足客户需求,开发人员制作PDF文档。 多亏了现代库,创建PDF变得从未如此简单。

要为使用此类库的项目选择理想库,我们必须权衡多个因素,包括构建、读取和转换能力。
在本教程中,我们将介绍各种JavaScript库,用于生成PDF。 我们将分析JS库和实际应用场景,同时重点关注三大要点:

  • 运行配置
  • 促进输入和自定义字体的模块
  • 使用的便利性

阅读完本文后,您将能够为您的JavaScript应用程序选择理想的PDF库。 最后,我们还将介绍IronPDF,一个有用且高效的PDF库。

class="hsg-featured-snippet">

如何在JavaScript中打印PDF文件

  1. 将PDF嵌入iframe标签中
  2. 访问iframe带有的PDF查看器中的打印选项
  3. 使用JavaScript打印当前页面的PDF
  4. 调用printJS方法并将元素ID传递给可打印属性
  5. 使用替代库通过.NET C#中的Print方法进行打印

2.0 库

考虑我们希望客户能够下载并打印我们的发票副本的情景。我们需要这张发票能够准确并合适地打印。 在这里,我们将仔细研究一些可用来将该发票从HTML文件格式转换为PDF的众多库。

2.1 纯JavaScript代码

通常,要打印PDF文件的内容,我们将其下载到计算机上,打开并选择打印选项。 另一方面,JavaScript可以让我们直接从网页上轻松打印PDF文件。 您需要的只是网站上的一个iframe或动态构建iframe的能力,添加文档并打印。 我将演示如何使用JavaScript打印PDF文件。使用iframe显示嵌套网页。 为了网页显示,iframe需要知道其来源。

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript Print PDF</title>
</head>
<body>
    <!-- Embedding the PDF in an iframe -->
    <iframe 
        src="Demo.pdf" id="myFrame" 
        frameborder="0" style="border:0;" 
        width="300" height="300">
    </iframe>
    <p>
        <!-- Button to trigger the print function -->
        <input type="button" id="bt" onclick="printPdf()" value="Print PDF" />
    </p>

    <script>
        // JavaScript function to print the PDF inside the iframe
        let printPdf = () => {
            // Access the iframe
            let objFra = document.getElementById('myFrame');
            // Focus the iframe's window
            objFra.contentWindow.focus();
            // Trigger the print dialog
            objFra.contentWindow.print();
        }
    </script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
    <title>JavaScript Print PDF</title>
</head>
<body>
    <!-- Embedding the PDF in an iframe -->
    <iframe 
        src="Demo.pdf" id="myFrame" 
        frameborder="0" style="border:0;" 
        width="300" height="300">
    </iframe>
    <p>
        <!-- Button to trigger the print function -->
        <input type="button" id="bt" onclick="printPdf()" value="Print PDF" />
    </p>

    <script>
        // JavaScript function to print the PDF inside the iframe
        let printPdf = () => {
            // Access the iframe
            let objFra = document.getElementById('myFrame');
            // Focus the iframe's window
            objFra.contentWindow.focus();
            // Trigger the print dialog
            objFra.contentWindow.print();
        }
    </script>
</body>
</html>
HTML

为了打印PDF,可以使用iframe显示文档的内容,然后使用JavaScript打印内容。 在这两种情况下,iframe都是必需的。 在上面的例子中,有一个源为PDF的iframe。 还有一个按钮类型的输入元素。

按钮的onclick属性将调用printPdf方法。

如何在JavaScript中打印PDF文件:图1 - 打印

2.2 Print.js

Print.js主要是为了让我们能够在应用程序内打印PDF文件,而无需离开、导入并从用户界面打印或使用嵌入。 这是用于用户只需要打印PDF文件而不需要打开或下载它们的特殊情况。

例如,当用户请求打印服务器端生成的报告时,这可能会很有用。 这些报告以PDF文档的形式返回给您。 这些文件可以无需打开就进行打印。 在我们的应用程序中,Print.js提供了一种方便的方法来打印这些文件。

<!DOCTYPE html>
<html>
<head>
    <title>Print.js Example</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.js"></script>
    <script src="https://printjs-4de6.kxcdn.com/print.min.js"></script>
    <link href="https://printjs-4de6.kxcdn.com/print.min.css" rel="stylesheet">   
</head>
<body>
    <!-- Area to be printed -->
    <div id="print-area" class="print-main">
        <table>
            <tr>
                <th>Name</th>
                <th>Age</th>
            </tr>
            <tr>
                <td>AAA</td>
                <td>25</td>
            </tr>
            <tr>
                <td>BBB</td>
                <td>24</td>
            </tr>
        </table>
    </div>
    <!-- Button to trigger Print.js -->
    <button id="btnPrint">Print</button>

    <script>
        $(document).ready(function(){
            // When the print button is clicked
            $("#btnPrint").on("click", function(){
                // Use Print.js to print the content of #print-area
                printJS({
                    printable: 'print-area',
                    type: 'html'
                });
            });
        });
    </script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
    <title>Print.js Example</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.js"></script>
    <script src="https://printjs-4de6.kxcdn.com/print.min.js"></script>
    <link href="https://printjs-4de6.kxcdn.com/print.min.css" rel="stylesheet">   
</head>
<body>
    <!-- Area to be printed -->
    <div id="print-area" class="print-main">
        <table>
            <tr>
                <th>Name</th>
                <th>Age</th>
            </tr>
            <tr>
                <td>AAA</td>
                <td>25</td>
            </tr>
            <tr>
                <td>BBB</td>
                <td>24</td>
            </tr>
        </table>
    </div>
    <!-- Button to trigger Print.js -->
    <button id="btnPrint">Print</button>

    <script>
        $(document).ready(function(){
            // When the print button is clicked
            $("#btnPrint").on("click", function(){
                // Use Print.js to print the content of #print-area
                printJS({
                    printable: 'print-area',
                    type: 'html'
                });
            });
        });
    </script>
</body>
</html>
HTML

以上代码可用于直接从网站打印PDF文件。它显示了打印操作将打印HTML元素ID为“print-area”的元素内的所有HTML字符串。

如何在JavaScript中打印PDF文件:图2 - 打印这些字符串

2.3 IronPDF - Node.js PDF库

IronPDF 是一个全面的Node.js PDF库,在准确性、易用性和速度上表现出色。 它提供了广泛的功能,可以直接从HTML、URL和React中的图像生成、编辑和格式化PDF。 支持包括 Windows、MacOS、Linux、Docker 和像 Azure 和 AWS 这样的云平台,IronPDF 确保跨平台兼容性。 其用户友好的 API 允许开发人员快速将 PDF 生成和处理集成到他们的 Node.js 项目中。

IronPDF for Node.js的关键特性:

  • 多功能 PDF 生成:使用 IronPDF,开发人员可以从包括 HTML、CSS、JavaScript、图像和其他文件类型在内的不同来源生成 PDF。这种灵活性使得创建根据特定需求量身定制的动态和吸引人的 PDF 文档成为可能。
  • 高级文档自定义:IronPDF 使开发人员能够利用页眉、页脚、附件、数字签名、水印和书签等功能增强 PDF 文档。 这允许创建具有丰富内容和交互元素的专业级PDF。
  • 安全功能:IronPDF 提供强大的安全功能,以保护 PDF 不受未经授权的访问。 开发人员可以实施安全措施,如密码、数字签名、元数据和其他安全设置,以保护PDF文档中包含的敏感信息。
  • 性能优化:IronPDF 旨在实现最佳性能,具有完整的多线程和异步支持。 这确保了高效的PDF生成,使其适合对性能有至关重要要求的应用程序。
  • 全面的功能集:IronPDF 拥有超过 50 个功能,用于创建、格式化和编辑 PDF 文档,为所有 PDF 相关任务提供全面的解决方案。 从基本文档生成到高级自定义和安全性,IronPDF提供了一系列功能以满足开发人员的需求。

Here is an example of generating and saving a PDF document from HTML File, HTML String, and URL to preserve formatting for printing:

import { PdfDocument } from "@ironsoftware/ironpdf";

// An async function to demonstrate how to generate PDF documents
(async () => {
    // Create a PDF from a URL
    const pdfFromUrl = await PdfDocument.fromUrl("https://getbootstrap.com/");
    // Save it to a file
    await pdfFromUrl.saveAs("website.pdf");

    // Create a PDF from a local HTML file
    const pdfFromHtmlFile = await PdfDocument.fromHtml("design.html");
    // Save it to a file
    await pdfFromHtmlFile.saveAs("markup.pdf");

    // Create a PDF from an HTML string
    const pdfFromHtmlString = await PdfDocument.fromHtml("<p>Hello World</p>");
    // Save it to a file
    await pdfFromHtmlString.saveAs("markup_with_assets.pdf");
})();
import { PdfDocument } from "@ironsoftware/ironpdf";

// An async function to demonstrate how to generate PDF documents
(async () => {
    // Create a PDF from a URL
    const pdfFromUrl = await PdfDocument.fromUrl("https://getbootstrap.com/");
    // Save it to a file
    await pdfFromUrl.saveAs("website.pdf");

    // Create a PDF from a local HTML file
    const pdfFromHtmlFile = await PdfDocument.fromHtml("design.html");
    // Save it to a file
    await pdfFromHtmlFile.saveAs("markup.pdf");

    // Create a PDF from an HTML string
    const pdfFromHtmlString = await PdfDocument.fromHtml("<p>Hello World</p>");
    // Save it to a file
    await pdfFromHtmlString.saveAs("markup_with_assets.pdf");
})();
JAVASCRIPT

有关更多PDF相关任务的代码示例,请访问此IronPDF Node.js 代码示例页面。

如何在JavaScript中打印PDF文件:图3 - IronPDF

3.0 结论

用户可以看到上面的JavaScript代码,但它可能被他人滥用。 以这种方式使用源代码是可能的。 此外,在网站上添加危害通过它发送的数据安全的代码并不困难。 不同的浏览器对上述JavaScript库的看法不同。 因此,代码必须在多个系统上运行才能发布。 因为某些新功能不被旧版浏览器支持,我们还需要查看那些的浏览器兼容性。 上述库可以生成PDF文件。 用户还必须对他们正在使用的脚本有一些了解。

通过IronPDF在JavaScript中构建的框架和库的简单集成过程,优质的IronPDF Node.js 文档和示例代码示例,以及响应迅速的技术支持,开发人员可以快速上手,使其成为在Node.js相关应用程序中生成和打印专业级PDF的首选。

IronPDF为Node.js提供免费试用,因此您可以在做出明智决策前测试其完整功能。 It is also available for other languages like C# .NET, Java and Python. 访问IronPDF网站了解更多详细信息。 从IronPDF Node.js 下载页面下载IronPDF for Node.js。

Darrius Serrant
全栈软件工程师(WebOps)

Darrius Serrant 拥有迈阿密大学的计算机科学学士学位,目前在 Iron Software 担任全栈 WebOps 市场工程师。从小就被编码吸引,他认为计算机既神秘又易于接触,使其成为创意和问题解决的理想媒介。

在 Iron Software,Darrius 喜欢创造新事物,并简化复杂概念以使其更易理解。作为我们常驻的开发者之一,他还自愿教授学生,与下一代分享他的专业知识。

对于 Darrius 来说,他的工作令人满意,因为它被重视并产生真正的影响。