跳至页脚内容
PDF 工具

如何在 JavaScript 中创建 PDF 文件

在文档共享领域,由Adobe公司开创的便携文档格式(PDF)在保存文本丰富和视觉吸引内容的完整性方面起着至关重要的作用。 在线访问PDF文件通常需要专用程序。 在当今的数字环境中,PDF文件已成为多种重要出版物不可或缺的部分。 许多企业依赖PDF文件来创建专业文档和发票。 此外,开发人员通常利用PDF创建库来满足特定的客户需求。 随着现代库的出现,PDF的生成流程已经简化。 在选择用于涉及PDF生成的项目的最合适的库时,必须考虑构建、读取和转换能力等因素,以确保无缝集成和最佳性能。

JavaScript库

例如,考虑我们希望客户能够轻松下载和打印我们的PDF发票的情景。 此外,我们必须保持发票的精确布局并确保完美的打印质量。

在本节中,我们将深入探讨一系列在转换和创建HTML到PDF文档方面表现卓越的高度评价的JavaScript库,为我们提供高效和准确的文档生成和转换的多功能工具。

1. PDFKit

PDFKit是首批推出的PDF库之一,进入了庞大的JavaScript库生态系统。 自2012年首次发布以来,它的受欢迎度显著增长,截至2021年,它仍在进行定期升级。

使用Webpack,PDFKit同时支持Node库和网络浏览器,支持自定义字体和图像嵌入。

然而,正如我们将在比较中看到的,一些PDF库实际上只是PDFKit的包装器,可能比PDFKit更易于使用。

PDFKit没有可用的高级API。 文档常常也是比较困难的。 如您所料,它需要一些适应,您可能会发现使用JavaScript生成PDF并不总是最简单的任务。

// Requiring the necessary modules for file system and PDF document creation.
const fs = require('fs');
const PDFDocument = require('pdfkit');

// Create a new PDF document instance
const doc = new PDFDocument();

// Add text content to the PDF document
doc.text('Hello world!');

// Define the output file location and start writing the PDF content to it
doc.pipe(fs.createWriteStream('Demo.pdf'));

// Finalize the PDF file
doc.end();
// Requiring the necessary modules for file system and PDF document creation.
const fs = require('fs');
const PDFDocument = require('pdfkit');

// Create a new PDF document instance
const doc = new PDFDocument();

// Add text content to the PDF document
doc.text('Hello world!');

// Define the output file location and start writing the PDF content to it
doc.pipe(fs.createWriteStream('Demo.pdf'));

// Finalize the PDF file
doc.end();
JAVASCRIPT

2. pdfmake

与使用传统命令式方法生成某物的PDFKit不同,pdfmake使用声明式方法。 因此,使用pdfmake库可以更容易地专注于PDF生产的预期功能,而不是浪费时间教库如何实现某个结果。

需要牢记的是,尽管某些解决方案可能看起来很有希望,但它们可能并不完美。 一个这样的例子是在使用Webpack时与pdfmake集成自定义字体,这可能会导致问题。 可惜的是,关于这个特定问题的在线文档有限。 然而,如果您不使用Webpack,可以轻松克隆Git存储库并执行字体嵌入脚本以克服与自定义字体集成相关的潜在障碍。

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.56/pdfmake.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.56/vfs_fonts.js"></script>
</head>
<body>
    <script type="text/javascript">
        // Function to create and print a PDF document
        function CreatePdf() {
            // Define document content and styles
            var docDefinition = {
                content: [
                    { text: "Hello world" } // Text content to be included in the PDF
                ],
                defaultStyle: {}
            };
            // Create and print the PDF using pdfMake library
            pdfMake.createPdf(docDefinition).print();
        }
    </script>
    <!-- Button to trigger PDF creation and printing -->
    <button onclick="CreatePdf()">Print pdf</button>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.56/pdfmake.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.56/vfs_fonts.js"></script>
</head>
<body>
    <script type="text/javascript">
        // Function to create and print a PDF document
        function CreatePdf() {
            // Define document content and styles
            var docDefinition = {
                content: [
                    { text: "Hello world" } // Text content to be included in the PDF
                ],
                defaultStyle: {}
            };
            // Create and print the PDF using pdfMake library
            pdfMake.createPdf(docDefinition).print();
        }
    </script>
    <!-- Button to trigger PDF creation and printing -->
    <button onclick="CreatePdf()">Print pdf</button>
</body>
</html>
HTML

如何在JavaScript中创建PDF文件:图1

3. IronPDF

通过IronPDF,开发人员可以更轻松地创建、浏览和编辑PDF文档。 它作为强大的PDF转换器,提供了用于创建、编辑和处理PDF文件的基础API。

IronPDF for Node.js简化了以编程方式创建和自定义PDF文档的过程。 由提供高性能文档处理库的可信赖供应商Iron Software开发,IronPDF为Node.js环境中的PDF生成提供了强大的解决方案。 它与Node.js项目无缝集成,为开发人员提供了强大的工具以轻松生成、格式化和编辑PDF。

IronPDF库具有广泛的功能,包括将页面拆分和组合到新的或现有的PDF文档中,读取和编辑现有的PDF文件,从PDF文件中提取图像,向PDF文件添加文本、图形、书签、水印、页眉和页脚,所有这些都不需要Acrobat Reader。 可以从CSS和CSS媒体文件生成PDF文档。 IronPDF允许用户创建、上传和更新新的和现有的PDF表单。

IronPDF for Node.js的关键特性:

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

下面的代码演示了如何使用JavaScript将HTML渲染为精确匹配的PDF文件:

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

(async () => {
    // HTML content containing JavaScript to be executed upon rendering
    const htmlWithJavaScript = `<h1>This is HTML</h1>
    <script>
        document.write('<h1>This is JavaScript</h1>');
        window.ironpdf.notifyRender(); // Notify IronPDF when rendering is done
    </script>`;

    // Rendering options to enable JavaScript
    const renderOptions = {
        enableJavaScript: true,
    };

    // Render HTML content to a PDF
    const pdf = await PdfDocument.fromHtml(htmlWithJavaScript, { renderOptions });

    // Save the PDF to a file
    await pdf.saveAs("javascript-in-html.pdf");
})();
import { PdfDocument } from "@ironsoftware/ironpdf";

(async () => {
    // HTML content containing JavaScript to be executed upon rendering
    const htmlWithJavaScript = `<h1>This is HTML</h1>
    <script>
        document.write('<h1>This is JavaScript</h1>');
        window.ironpdf.notifyRender(); // Notify IronPDF when rendering is done
    </script>`;

    // Rendering options to enable JavaScript
    const renderOptions = {
        enableJavaScript: true,
    };

    // Render HTML content to a PDF
    const pdf = await PdfDocument.fromHtml(htmlWithJavaScript, { renderOptions });

    // Save the PDF to a file
    await pdf.saveAs("javascript-in-html.pdf");
})();
JAVASCRIPT

您还可以执行自定义JavaScript,从而轻松修改HTML内容的外观:

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

(async () => {
    // JavaScript code to change the text color of header tags to red
    const javascriptCode = "document.querySelectorAll('h1').forEach(function(el){ el.style.color = 'red'; })";

    // HTML content which will be affected by the custom JavaScript
    const htmlContent = "<h1>Happy New Year!</h1>";

    // Rendering options to enable and apply the custom JavaScript
    const renderOptions = {
        enableJavaScript: true,
        javascript: javascriptCode,
    };

    // Render HTML content to a PDF
    const pdf = await PdfDocument.fromHtml(htmlContent, { renderOptions });

    // Save the PDF with the applied JavaScript effects
    await pdf.saveAs("executed_js.pdf");
})();
import { PdfDocument } from "@ironsoftware/ironpdf";

(async () => {
    // JavaScript code to change the text color of header tags to red
    const javascriptCode = "document.querySelectorAll('h1').forEach(function(el){ el.style.color = 'red'; })";

    // HTML content which will be affected by the custom JavaScript
    const htmlContent = "<h1>Happy New Year!</h1>";

    // Rendering options to enable and apply the custom JavaScript
    const renderOptions = {
        enableJavaScript: true,
        javascript: javascriptCode,
    };

    // Render HTML content to a PDF
    const pdf = await PdfDocument.fromHtml(htmlContent, { renderOptions });

    // Save the PDF with the applied JavaScript effects
    await pdf.saveAs("executed_js.pdf");
})();
JAVASCRIPT

如何在JavaScript中创建PDF文件:图2

当我们点击下载按钮时,它将下载PDF文件,就像在上图的PDF页面上所示。 创建的PDF文件将如下面所示。

如何在JavaScript中创建PDF文件:图3

IronPDF的C#创建PDF教程中可以找到更详细的教程。

结论

应该提到的是,当其他人使用时,上述JavaScript代码有可能被滥用和引发安全问题。 在网页或网站上放置这样代码时,考虑诸如未经授权访问和数据安全漏洞的风险是至关重要的。此外,还需要考虑支持可能不具备所有必要功能的过时浏览器,以及与各个系统和浏览器的兼容性问题。

IronPDF is not only available for Node.js but also for other popular platforms including .NET, Java, and Python. 这种跨平台可用性确保了在不同技术堆栈中工作的开发人员的一致性和灵活性。 凭借其丰富的功能集、无缝集成和优异性能,IronPDF是希望在Node.js项目中简化PDF生成的开发人员的宝贵工具。

To accommodate various developer demands, the library provides a variety of licensing options, including a free trial license and additional developer licenses that are available for purchase. $799 Lite 包含永久许可、30天退款保证、一年的软件支持和升级选项。 除了初始购买,没有进一步的费用。

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

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

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

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