跳過到頁腳內容
PDF工具

如何在 JavaScript 中打印 PDF 文件

1.0 引言

便攜式文件格式 (PDF) 由 Adobe 開發,用於共用包含文字和圖形的文件。 若要線上開啟PDF文檔,需要額外的程序。 PDF文件對於當今社會的重要資訊至關重要。 許多企業使用PDF文件建立文件和發票。 為了滿足客戶需求,開發人員會製作PDF文件。 由於現代庫,創建 PDF 文件從未如此簡單。

要為使用此類庫的專案選擇理想的庫,我們必須權衡許多因素,包括建置、讀取和轉換能力。
在本教程中,我們將介紹各種用於產生 PDF 的 JavaScript 程式庫。 我們將分析 JS 函式庫和實際應用場景,並專注於以下三個面向:

  • 運行配置
  • 用於簡化輸入和自訂字體的模組
  • 易用性

閱讀本文後,您將能夠為您的 JavaScript 應用程式選擇理想的 PDF 程式庫。 最後,我們還將介紹 IronPDF,這是一個實用且高效的 PDF 庫。

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 檔案。它表明,列印時會列印 ID 為"print-area"的 HTML 元素內的所有 HTML 字串。

如何在 JavaScript 中列印 PDF 檔案:圖 2 - 列印這些字串

2.3 IronPDF - Node.js PDF 庫

IronPDF是一個功能全面的 Node.js PDF 庫,在準確性、易用性和速度方面表現出色。 它提供了豐富的功能,可以直接在 React 中從 HTML、URL 和圖像生成、編輯和格式化 PDF。 IronPDF 支援包括 Windows、MacOS、Linux、Docker 以及 Azure 和 AWS 等雲端平台在內的各種平台,確保跨平台相容性。 它易於使用的 API 使開發人員能夠快速將 PDF 生成和處理整合到他們的 Node.js 專案中。

IronPDF for Node.js 的主要功能:

  • 多功能 PDF 產生:IronPDF 支援開發者從多種來源產生 PDF,包括 HTML、CSS、JavaScript、映像和其他文件類型。這種靈活性使得創建動態且美觀的 PDF 文件成為可能,並可根據特定需求進行客製化。
  • 進階文件自訂:IronPDF 使開發人員能夠透過頁首、頁尾、附件、數位簽章、浮水印和書籤等功能來增強 PDF 文件。 這樣就可以建立具有豐富內容和互動式元素的專業級 PDF 檔案。
  • 安全功能:IronPDF 提供強大的安全功能,以保護 PDF 檔案免受未經授權的存取。 開發人員可以實施密碼、數位簽章、元資料和其他安全性設定等安全措施,以保護 PDF 文件中包含的敏感資訊。
  • 最佳化效能:IronPDF 旨在實現最佳效能,具有完整的多執行緒和非同步支援。 這確保了高效的 PDF 生成,使其適用於對效能要求極高的關鍵任務應用。
  • 功能齊全:IronPDF 提供 50 多種功能,用於建立、格式化和編輯 PDF 文檔,為所有與 PDF 相關的任務提供全面的解決方案。 從基本文件產生到進階自訂和安全,IronPDF 提供廣泛的功能來滿足開發人員的需求。

以下範例示範如何從HTML 文件、HTML 字串和URL產生並儲存 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");
})();
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 構建的框架和庫的簡單集成流程、出色的Node.js 文件和示例代碼,以及響應迅速的技術支持,開發人員可以立即上手使用,使其成為在 Node.js 相關應用程序中生成和打印專業級 PDF 的首選。

IronPDF 提供Node.js 的免費試用版,因此您可以在做出明智的決定之前測試其全部功能。 它也支援其他語言,如C# .NETJavaPython 。 請造訪IronPDF 網站以了解更多詳情。 從IronPDF Node.js 下載頁面下載 IronPDF for Node.js。

Darrius Serrant
全棧軟件工程師 (WebOps)

Darrius Serrant 擁有邁阿密大學計算機科學學士學位,目前任職於 Iron Software 的全栈 WebOps 市場營銷工程師。從小就迷上編碼,他認為計算既神秘又可接近,是創意和解決問題的完美媒介。

在 Iron Software,Darrius 喜歡創造新事物,並簡化複雜概念以便於理解。作為我們的駐場開發者之一,他也自願教學生,分享他的專業知識給下一代。

對 Darrius 來說,工作令人滿意因為它被重視且有實際影響。