跳過到頁腳內容
PDF工具

如何在 JavaScript 中創建 PDF 文件

在文件共享領域中,由Adobe領導的可攜式文檔格式(PDF)在保持文本豐富和視覺吸引力內容的完整性方面發揮著關鍵作用。 在線訪問PDF文件通常需要一個專用程序。 在當今的數位環境中,PDF文件已經成為各種重要出版物不可或缺的工具。 許多企業依靠PDF文件創建專業文件和發票。 此外,開發人員經常利用PDF創建庫來滿足特定客戶需求。 隨著現代庫的出現,生成PDF的過程已被精簡。 選擇涉及PDF生成的項目中最合適的庫時,必須考慮構建、讀取和轉換功能等因素,以確保無縫整合和最佳性能。

JavaScript 庫

考慮例如希望客戶能夠輕鬆下載和打印我們PDF發票的副本的情況。 此外,對我們而言,維護發票的精確佈局和確保完美的打印質量至關重要。

在本節中,我們將深入探討一系列備受推崇的JavaScript庫,這些庫在將HTML轉換為PDF文檔方面表現卓越,為我們提供了高效且準確的文件生成和轉換的多功能工具。

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,開發人員可以從各種來源生成PDF,包括HTML、CSS、JavaScript、圖像和其他文件類型。這種靈活性使得能夠根據特定需求創建動態和視覺上吸引的PDF文檔。
  • 高級文件定制:IronPDF使開發人員能夠增強PDF文檔,具有例如頁眉、頁腳、附件、數字簽名、水印和書籤等功能。 這使得能夠創建具有豐富內容和互動元素的專業級PDF。
  • 安全功能:IronPDF提供強大的安全功能,以保護PDF不被未經授權的訪問。 開發人員可以實施安全措施,如密碼、數字簽名、元數據和其他安全設置,以保護PDF文檔中包含的敏感信息。
  • 優化性能:IronPDF設計優化性能,具有完全多線程和異步支持。 這確保了高效的PDF生成,使其適用於性能至關重要的關鍵應用。
  • 全面功能集:擁有超過50種功能,用於創建、格式化和編輯PDF文檔,IronPDF提供了一個全面的解決方案,滿足所有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 來說,工作令人滿意因為它被重視且有實際影響。