HTML 轉 PDF NodeJS

Darrius Serrant
Darrius Serrant
2022年12月28日
已更新 2025年1月16日
分享:
This article was translated from English: Does it need improvement?
Translated
View the article in English

IronPDF最強大且最受歡迎的功能是能夠從原始HTML、CSS和JavaScript創建高保真度的PDF。 本教程是一份全面的入門指南,旨在幫助Node開發者利用IronPDF將HTML到PDF生成整合到他們自己的項目中。

IronPDF 是一個高階 API 函式庫,可幫助開發人員快速且容易地在軟件應用程式中實現強大且穩固的 PDF 處理功能。 IronPDF 支援多種程式語言。 如需有關如何在.NETJavaPython 中創建 PDF 的詳細說明,請查閱官方文檔頁面。 本教程涵蓋了它在 Node.js 項目中的應用。

請提供您要翻譯的內容。

請提供您要翻譯的內容。

入門

立即在您的專案中使用IronPDF,並享受免費試用。

第一步:
green arrow pointer

安裝 IronPDF Library for Node.js

在您選定的 Node 項目中,執行以下的 NPM 命令來安裝 IronPDF Node.js 套件:

npm install @ironsoftware/ironpdf

您也可以手動下載並安裝 IronPDF 套件。

手動安裝 IronPDF 引擎(可選)

IronPDF for Node.js 目前需要一個 IronPDF Engine 二進位檔 才能正常運作。

通過安裝適合您操作系統的軟體包來安裝IronPDF Engine的二進位檔案:

請注意
安裝 IronPDF 引擎是可選的,因為 @ironpdf 會在第一次執行時自動從 NPM 下載並安裝適合您的瀏覽器和操作系統的二進位檔。 然而,當網絡訪問受限、減少或不希望時,顯式安裝此二進位文件將非常重要。

應用授權金鑰(可選)

IronPDF 預設將會在其生成或修改的所有文件上添加帶有標題的背景浮水印。

圖 1

在 ironpdf.com/nodejs/licensing/ 獲取授權金鑰,以便生成沒有浮水印的 PDF 文件。

若要使用 IronPDF 而不帶有額外的浮水印品牌,您必須在全域 IronPdfGlobalconfig 物件上設定 licenseKey 屬性為有效的授權金鑰。 下面提供了實現此功能的源代碼:

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

var config = IronPdfGlobalConfig.getConfig();
config.licenseKey = "{YOUR-LICENSE-KEY-HERE}";
NODE.JS

從我們的授權頁面購買授權金鑰,或者聯繫我們獲取免費試用授權金鑰

[{i:(應在使用其他庫函數之前設置許可證密鑰和其他全域設定,以確保最佳性能和正確功能。

接下來的教程部分將假設我們擁有一個許可證密鑰,並且我們已將其設置在一個名為_config.js_的獨立JavaScript文件中。 我們在任何需要使用IronPDF功能的地方導入此腳本:

import {PdfDocument} from "@ironsoftware/ironpdf";
import('./config.js');
// ...
NODE.JS

將HTML轉換為PDF

IronPDF庫的Node版本提供了三種從HTML內容創建PDF文件的方法:

  1. 從一串HTML代碼

  2. 從本地 HTML 檔案

  3. 從一個線上網站

    這一節將詳細解釋所有三種方法。

從HTML字符串創建PDF文件

PdfDocument.fromHtml 是一種方法,可讓您從原始網頁標記字串生成 PDF。

此方法在三種方法中提供最大的靈活性。 這是因為HTML字符串中的數據可以來自幾乎任何地方:文本文件、數據流、HTML模板、生成的HTML數據等。

以下程式碼範例演示了如何實際使用PdfDocument.fromHtml方法:

import {PdfDocument} from "@ironsoftware/ironpdf";
import('./config.js');

// Create a PDF from the HTML String "Hello world!"
const pdf = await PdfDocument.fromHtml("<h1>Hello from IronPDF!</h1>");

// Save the PDF document to the file system.
await pdf.saveAs("html-string-to-pdf.pdf");
NODE.JS

如上所示,我們調用PdfDocument.fromHtml 方法,其中包含一個包含標記代碼的字串,用於一級標題元素。

PdfDocument.fromHtml 返回一個 Promise,該 Promise 會解析為 PdfDocument 類的一個實例。 PdfDocument 代表了圖書館從某些來源內容生成的 PDF 檔案。 此類別是IronPDF大部分核心功能的基石,推動了大量PDF創建和編輯的使用案例。

最後,我們使用 saveAs 方法在 PdfDocument 上將文件保存到磁碟。 以下顯示的是已保存的PDF文件。

圖2

從 HTML 字串 "<h1>Hello from IronPDF!</h1>" 生成的 PDF。 PdfDocument.fromHtml 生成的 PDF 文件看起來就像網頁內容一樣。

從 HTML 檔案建立 PDF 檔案

PdfDocument.fromHtml 不僅僅適用於 HTML 字串。 此方法也接受指向本地HTML文件的路徑。

在下一個範例中,我們將使用這個範例網頁

圖3

我們的範例HTML頁面在Google Chrome中的顯示效果。 下載此頁面和類似的頁面從文件樣本網站:https://filesamples.com/samples/code/html/sample2.html

以下代码行将整个示例文档转换为PDF。 我們使用有效的文件路徑來調用PdfDocument.fromHtml,而不是 HTML 字串,以訪問我們的範例檔案:

import {PdfDocument} from "@websiteironsoftware/ironpdf";
import('./config.js');

// Render a PDF from an HTML File
const pdf = await PdfDocument.fromHtml("./sample2.html");

// Save the PDF document to the same folder as our project.
await pdf.saveAs("html-file-to-pdf-1.pdf");
NODE.JS

我們已在下方包括了生成的PDF內容。 請注意,IronPDF 不僅保留了原始 HTML 文檔的外觀,還保留了鏈接、表單和其他常見互動元素的功能。

圖4

此 PDF 是從之前的代碼示例生成的。 將其外觀與前一張圖片進行比較,注意其顯著的相似之處!

如果您已經檢查了範例頁面的源代碼,您會注意到它更複雜。 它使用更多類型的 HTML 元素(段落、無序列表、換行、水平線、超連結、圖像等),並且還包含一些腳本(用於設置 cookie)。

IronPDF 能夠渲染比我們迄今使用的更為複雜的網頁內容。 要演示這一點,讓我們考慮以下頁面:

圖 5

一篇關於Puppeteer的文章,這是一個因其能使用無頭瀏覽器實例以程式化方式控制Chrome而受歡迎的Node庫

上面所描述的頁面是關於Puppeteer Node Library的文章。 Puppeteer 執行無頭瀏覽器會話,Node 開發人員使用它在伺服器端或客戶端自動化許多瀏覽器任務(其中之一包括伺服器端 HTML PDF 生成)。

新頁面引用了許多資源(CSS文件、圖像、腳本文件等),並採用了更為複雜的佈局。 在下一個範例中,將把保存的這個頁面的副本(以及其來源資產)轉換成完美的 PDF。

以下的程式碼片段假設該頁面與我們的項目保存在同一個目錄中,名為 "sample4.html":

// Render a from even more complex HTML code.
PdfDocument.fromHtml("./sample4.html").then((pdf) async {
    return await pdf.saveAs("html-file-to-pdf-2.pdf");
});
NODE.JS

以下圖片顯示了上述程式碼片段的結果。

圖6

如果在 Google Chrome 中看起來不錯,那麼轉換為 PDF 時也會看起來不錯。 這包括大量使用CSS和JavaScript的頁面設計。

從網址建立一個 PDF 檔案

IronPDF 可以轉換任何大小和複雜性的 HTML 字串和 HTML 檔案。 您不僅限於僅使用來自字符串和文件的原始標記。 IronPDF 也可以從 URL 請求 HTML。

請考慮位於https://en.wikipedia.org/wiki/PDF的維基百科文章。

圖 7

在符合標準的網絡瀏覽器中顯示的關於PDF格式的維基百科文章。

使用這個源代碼將這篇維基百科文章轉換成PDF:

import {PdfDocument} from "@ironsoftware/ironpdf";
import('./config.js');

// Convert the Web Page to a pixel-perfect PDF file.
const pdf = await PdfDocument.fromUrl("https://en.wikipedia.org/wiki/PDF");

// Save the document.
await pdf.saveAs("url-to-pdf.pdf");
NODE.JS

在上面,我們使用PdfDocument.fromUrl在幾行程式碼內將網頁轉換為 PDF。 IronPDF 將為您抓取網址的 HTML 代碼並無縫呈現。 不需要 HTML 檔案或文字字串!

圖8

**從呼叫PdfDocument.fromUrl於維基百科文章上生成的PDF。 注意其與原始網頁的相似之處。

從Zip存檔建立PDF檔案

使用PdfDocument.fromZip將壓縮檔 (zip) 中的特定 HTML 檔案轉換為 PDF。

例如,假設我們在專案目錄中有一個Zip檔案,其內部結構如下:

html-zip.zip
├─ index.html
├─ style.css
├─ logo.png

index.html 文件包含以下代码:

<!DOCTYPE html>

<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Hello world!</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <h1>Hello from IronPDF!</h1>
    <a href="https://ironpdf.com/nodejs/">
      <img src="logo.png" alt="IronPDF for Node.js">
    </a>
  </body>
</html>
<!DOCTYPE html>

<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Hello world!</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <h1>Hello from IronPDF!</h1>
    <a href="https://ironpdf.com/nodejs/">
      <img src="logo.png" alt="IronPDF for Node.js">
    </a>
  </body>
</html>
HTML

style.css 宣告了五個 CSS 規則:

@font-face {
font-family: 'Gotham-Black';
src: url('gotham-black-webfont.eot?') format('embedded-opentype'), url('gotham-black-webfont.woff2') format('woff2'), url('gotham-black-webfont.woff') format('woff'), url('gotham-black-webfont.ttf') format('truetype'), url('gotham-black-webfont.svg') format('svg');
font-weight: normal;
font-style: normal;
font-display: swap;
}

body {
    display: flex;
    flex-direction: column;
    justify-content: center;
    margin-left: auto;
    margin-right: auto;
    margin-top: 200px;
    margin-bottom: auto;
    color: white;
    background-color: black;
    text-align: center;
    font-family: "Helvetica"
}

h1 {
    font-family: "Gotham-Black";
    margin-bottom: 70px;
    font-size: 32pt;
}

img {
    width: 400px;
    height: auto;
}

p {
    text-decoration: underline;
    font-size: smaller;
}

最後,logo.png 顯示了我們的產品標誌:

圖 9

假設的 HTML 壓縮檔案中的範例圖片。

當呼叫fromZip方法時,請在第一個參數中指定壓縮檔的有效路徑,並設置mainHtmlFile屬性的 JSON 物件,該屬性應包含我們要轉換之壓縮檔中 HTML 檔案的名稱。

我們以類似的方式轉換 zip 文件夾中的 index.html 文件:

import {PdfDocument} from "@ironsoftware/ironpdf";
import('./config.js');

// Render the HTML string
PdfDocument.fromZip("./html-zip.zip", {
    mainHtmlFile: "index.html"
}).then(async (pdf) => {
    return await pdf.saveAs("html-zip-to-pdf.pdf");
});
JAVASCRIPT

圖 10

**使用PdfDocument.fromZip函數創建PDF。 此函式成功地渲染 ZIP 檔案中包含的 HTML 代碼,連同其中的資產。

進階 HTML 轉 PDF 生成選項

ChromePdfRenderOptions 介面允許 Node 開發人員修改程式庫的 HTML 呈現行為。 所公開的屬性可在PDF呈現之前進行PDF外觀的細緻自訂。 此外,它們還能夠處理特定的HTML-PDF轉換邊緣情況。

IronPDF最初使用一些預設的ChromePdfRenderOptions值來渲染新的PDF。 您可以通過調用defaultChromePdfRenderOptions函數來自行輪詢這些預設值:

// Retrieve a ChromePdfRenderOptions object with default settings.
var options = defaultChromePdfRenderOptions();
NODE.JS

本節將輕鬆瀏覽最受歡迎的 HTML 到 PDF 呈現用例,這些用例需要使用 ChromePdfRenderOptions 介面。

每個子節將從預設值開始,並根據需要進行修改以達到目標結果。

自訂 PDF 生成輸出

添加自定義頁首和頁尾

使用 textHeadertextFooter 屬性,您可以將自定義的頁首和/或頁尾內容附加到新生成的 PDF。

以下示例創建了一個PDF版本的Google搜索首頁,並添加了自定義的頁眉和頁腳。 我們使用分隔線來區分此內容與頁面主體。 我們還在頁眉和頁腳中使用不同的字體,以使區別更加明顯。

import {PdfDocument, defaultChromePdfRenderOptions, AffixFonts} from "@ironsoftware/ironpdf";
import('./config.js');

var options = defaultChromePdfRenderOptions();

// Build a Custom Text-Based Header
options.textHeader = {
    centerText: "https://www.adobe.com",
    dividerLine: true,
    font: AffixFonts.CourierNew,
    fontSize: 12,
    leftText: "URL to PDF"
};

// Build a custom Text-Based Footer
options.textFooter = {
    centerText: "IronPDF for Node.js",
    dividerLine: true,
    fontSize: 14,
    font: AffixFonts.Helvetica,
    rightText: "HTML to PDF in Node.js"
};

// Render a PDF from an HTML File
PdfDocument.fromUrl("https://www.google.com/", {renderOptions: options}).then(async (pdf) => {
    return await pdf.saveAs("add-custom-headers-footers-1.pdf");
});
NODE.JS

源代碼生成此PDF:

圖11

**一個新的頁面已經創建為PDF格式,從Google主頁生成。 注意包含額外的頁眉和頁腳。

為了更進一步控制頁眉和頁腳的布局、定位和內容,您也可以使用原始HTML代替文字來定義它們。

在隨後的代碼塊中,我們使用 HTML 在頁首和頁尾加入更豐富的內容。 在標頭中,我們將頁面 URL 加粗並置中對齊; 在頁尾中,我們嵌入並置中一個標誌。

import {PdfDocument, defaultChromePdfRenderOptions} from "@ironsoftware/ironpdf";
import('./config.js');

var options = defaultChromePdfRenderOptions();
options.htmlHeader = {
    htmlFragment: "<strong>https://www.google.com/</strong>",
    dividerLine: true,
    dividerLineColor: "blue",
    loadStylesAndCSSFromMainHtmlDocument: true,
};
options.htmlFooter = {
    htmlFragment: "<img src='logo.png' alt='IronPDF for Node.js' style='display: block; width: 150px; height: auto; margin-left: auto; margin-right: auto;'>",
    dividerLine: true,
    loadStylesAndCSSFromMainHtmlDocument: true
};

// Render a PDF from an HTML File
await PdfDocument.fromUrl("https://www.google.com/", {renderOptions: options}).then(async (pdf) => {
    return await pdf.saveAs("add-html-headers-footers.pdf");
});
NODE.JS

下面的圖片顯示了這些變更的結果。

圖 12

IronPDF for Node.js 可以在將 HTML 頁面轉換為 PDF 時進行自訂。

設置邊距、頁面大小、頁面方向和顏色。

IronPDF支持額外設置,用於為新轉換的PDF定義自訂頁邊距、頁面大小和頁面方向。

import {PdfDocument, defaultChromePdfRenderOptions, PaperSize, FitToPaperModes, PdfPaperOrientation} from "@ironsoftware/ironpdf";
import('./config.js');

var options = defaultChromePdfRenderOptions();

// Set top, left, right, and bottom page margins in millimeters. 
options.margin = {
    top: 50,
    bottom: 50,
    left: 60,
    right: 60
};
options.paperSize = PaperSize.A5;
options.fitToPaperMode = FitToPaperModes.FitToPage;
options.paperOrientation = PdfPaperOrientation.Landscape;
options.grayScale = true;

// Create a PDF from the Google.com Home Page
PdfDocument.fromUrl("https://www.google.com/", {renderOptions: options}).then(async (pdf) => {
    return await pdf.saveAs("set-margins-and-page-size.pdf");
});
NODE.JS

在上述程式碼區塊中,我們配置IronPDF以灰階模式生成我們的Google首頁PDF,使用橫向佈局並至少留出50毫米的邊距空間。 我們還將其設定為適合A5紙張尺寸的內容。

從動態網頁生成 PDF 文件

對於包含非即時可用且在頁面加載時未立即呈現的內容的網頁,可能需要暫停該頁面內容的呈現,直到滿足特定條件為止。

例如,開發人員可能希望生成一個PDF,其中包含頁面加載後15秒才顯示的內容。 在另一種情況下,這相同的內容可能只有在一些複雜的客戶端代碼執行後才會出現。

為了處理這兩種邊緣情況(以及更多情況),Node 版本的 IronPDF 定義了WaitFor機制。 開發人員可以在其 ChromePdfRenderOptions 設定中包含此屬性,以指示 IronPDF 的 Chrome Rendering 引擎在特定事件發生時轉換頁面內容。

以下程式碼塊設置IronPDF等待20秒後再抓取我們首頁的內容作為PDF:

import {PdfDocument, defaultChromePdfRenderOptions, WaitForType} from "@ironsoftware/ironpdf";
import('./config.js');

// Configure the Chrome Renderer to wait until 20 seconds has passed
// before rendering the web page as a PDF.
var options = defaultChromePdfRenderOptions();
options.waitFor = {
    type: WaitForType.RenderDelay,
    delay: 20000
}
PdfDocument.fromUrl("https://ironpdf.com/nodejs/", {renderOptions: options}).then(async (pdf) => {
    return await pdf.saveAs("waitfor-renderdelay.pdf");
});
NODE.JS

下一個代碼塊配置 IronPDF 以等待直到可以成功選擇一個流行的SEO 文本編輯器上的元素。

import {PdfDocument, defaultChromePdfRenderOptions, WaitForType} from "@ironsoftware/ironpdf";
import('./config.js');

// Configure the Chrome Renderer to wait up to 20 seconds for a specific element to appear
options.waitFor = {
    type: WaitForType.HtmlElement,
    htmlQueryStr: "div.ProseMirror",
    maxWaitTime: 20000,
}
PdfDocument.fromUrl("https://app.surferseo.com/drafts/s/V7VkcdfgFz-dpkldsfHDGFFYf4jjSvvjsdf", {renderOptions: options}).then(async (pdf) => {
    return await pdf.saveAs("waitfor-htmlelement.pdf");
});
NODE.JS

從HTML模板生成PDFs

在本教程的最後一部分,我們將運用前幾節介紹的所有知識來完成一項非常實用的自動化任務:使用 HTML 模板生成一個或多個 PDF。

我們將在此部分使用的範本如下所示。 它是從此公開可訪問的發票模板修改而來,以包含佔位符標籤(例如 {COMPANY-NAME}、{FULL-NAME}、{INVOICE-NUMBER} 等)以替換內容。

圖13

**範本發票模板。 我們將撰寫其他的 JavaScript 程式碼,在將此範本生成為 PDF 之前,將動態數據新增至其中。

在繼續之前,您可以下載此HTML模板,並在您偏好的IDE中檢查它。

在下一段源代碼中,我們將把 HTML 模板加載到一個新的 PdfDocument 對象中,將我們定義的佔位符替換為一些測試數據,然後將 PdfDocument 對象保存到文件系統。

import {PdfDocument} from "@ironsoftware/ironpdf";
import('./config.js');

/**
 * Loads an HTML template from the file system.
 */
async function getTemplateHtml(fileLocation) {
    // Return promise for loading template file
    return PdfDocument.fromFile(fileLocation);
}

/**
 * Save the PDF document at a given location.
 */
async function generatePdf(pdf, location) {
    return pdf.saveAs(location);
}

/**
 * Use the PdfDocument.replaceText method to replace 
 * a specified placeholder with a provided value.
 */
async function addTemplateData(pdf, key, value) {
    return pdf.replaceText(key, value);
}

const template = "./sample-invoice.html";
getTemplateHtml(template).then(async (doc) => { // load HTML template from file
    await addTemplateData(doc, "{FULL-NAME}", "Lizbeth Presland");
    await addTemplateData(doc, "{ADDRESS}", "678 Manitowish Alley, Portland, OG");
    await addTemplateData(doc, "{PHONE-NUMBER}", "(763) 894-4345");
    await addTemplateData(doc, "{INVOICE-NUMBER}", "787");
    await addTemplateData(doc, "{INVOICE-DATE}", "August 28, 2023");
    await addTemplateData(doc, "{AMOUNT-DUE}", "13,760.13");
    await addTemplateData(doc, "{RECIPIENT}", "Celestyna Farmar"),
    await addTemplateData(doc, "{COMPANY-NAME}", "BrainBook");
    await addTemplateData(doc, "{TOTAL}", "13,760.13");
    await addTemplateData(doc, "{AMOUNT-PAID}", "0.00");
    await addTemplateData(doc, "{BALANCE-DUE}", "13,760.13");
    await addTemplateData(doc, "{ITEM}", "Training Sessions");
    await addTemplateData(doc, "{DESCRIPTION}", "60 Minute instruction");
    await addTemplateData(doc, "{RATE}", "3,440.03");
    await addTemplateData(doc, "{QUANTITY}", "4");
    await addTemplateData(doc, "{PRICE}", "13,760.13");
    return doc;
}).then(async (doc) => await generatePdf(doc, "html-template-to-pdf.pdf"));
NODE.JS

上述源碼定義了三個非同步輔助函數:

  • getTemplateHtml:使用PdfDocument.fromHtml方法將HTML模板載入到一個新的PdfDocument對象中。
  • addTemplateData:使用PdfDocument.replaceText方法,以替換提供的佔位符(稱為鍵)為其替換數據值。
  • generatePdf:將 PdfDocument 儲存在指定的檔案位置。

    此外,我們宣告一個 const template 變數來保存我們的 HTML 範本文件的位置。從上述原始碼生成的 PDF 如下所示。

    圖14

    從在 HTML 模板中以真實數據替換佔位符後創建的新 PDF 文檔。 如果從未發生這種替換,本文件保留我們所期望的 CSS 樣式和佈局。**

進一步閱讀

本教程僅初步介紹了使用IronPDF高級API功能的可能性。 請考慮學習這些相關主題以增進您的知識與理解。

  1. PdfGenerator 類別:這是一個專用的工具類,用於從 HTML、URL、Zip 存檔和其他來源媒體創建 PdfDocument 對象。 此類別提供了一個可行的替代方案,用於使用定義在PdfDocument類別上的PDF渲染功能。

  2. HttpLoginCredentials:如果您需要從需要特定 Cookie 或受密碼保護的網頁生成 PDF,這個參考將非常有用。
Darrius Serrant
全端軟體工程師(WebOps)

Darrius Serrant 擁有邁阿密大學的計算機科學學士學位,目前擔任 Iron Software 的全端 WebOps 行銷工程師。自幼對編程產生興趣,他認為計算機既神秘又易於接觸,使其成為創造力和解決問題的完美媒介。

在 Iron Software,Darrius 享受創造新事物並簡化複雜概念使其更易理解的過程。作為我們的其中一位常駐開發人員,他也自願教導學生,將他的專業知識傳授給下一代。

對 Darrius 來說,他的工作之所以令人滿足,是因為它受到重視並且產生了真正的影響。