在 Node.js 中將 HTML 轉換為 PDF

HTML to PDF NodeJS

This article was translated from English: Does it need improvement?
Translated
View the article in English

從原始的 HTML、CSS 和 JavaScript 創建高保真 PDF 的能力是 IronPDF 最強大且最受歡迎的功能。 本教程是幫助 Node 開發人員利用 IronPDF 將 HTML 轉換為 PDF 生成功能集成到他們自己的項目中的全面入門指南.

IronPDF 是一個高級 API 庫,可以幫助開發人員快速輕鬆地將強大而穩健的 PDF 處理功能實現到軟體應用程式中。 IronPDF 可在多種編程語言中使用。 For detailed coverage on how to create PDFs in .NET, Java, and Python, consult the official doc pages. 本教程涵蓋了它在 Node.js 項目中的應用.


class="hsg-featured-snippet">

如何在 Node.js 中將 HTML 轉換為 PDF

  1. 透過 NPM 安裝 HTML 到 PDF Node 庫:npm install @ironsoftware/ironpdf
  2. @ironsoftware/ironpdf 包中導入 PdfDocument 類。
  3. 從 HTML 字符串、文件或網絡 URL 進行轉換。
  4. (可選)添加頁眉和頁腳、更改頁面大小、方向和顏色。
  5. 調用 PdfDocument.saveAs 以保存生成的 PDF

入門指南

立即開始在您的項目中使用 IronPDF 並免費試用。

第一步:
green arrow pointer

為 Node.js 安裝 IronPDF 庫

在所選的 Node 項目中,執行以下 NPM 命令安裝 IronPDF Node.js 包:

npm install @ironsoftware/ironpdf
npm install @ironsoftware/ironpdf
SHELL

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

手動安裝 IronPDF 引擎(可選)

IronPDF for Node.js 目前需要IronPDF 引擎二進製文件才能正常工作。

通過為您的操作系統安裝相應的包來安裝 IronPDF Engine 二進製文件:

[{i:(安裝 IronPDF 引擎是可選的,因為 @ironpdf 在第一次執行時將自動從 NPM 下載並安裝與您的瀏覽器和操作系統匹配的二進制文件。 不過,在訪問互聯網受到限制、減少或不受歡迎的情況下,明確安裝此二進製文件將非常重要。)}]

應用許可證金鑰(可選)

默認情況下,IronPDF 會在其生成或修改的所有文檔中添加一個帶有標題背景水印的品牌標記。

圖 1 在 ironpdf.com/nodejs/licensing/ 取得許可證金鑰,以生成沒有水印的 PDF 文檔。

要在不帶有添加水印品牌標記的情況下使用 IronPDF,您必須在全局 IronPdfGlobalConfig 對象上設置 licenseKey 屬性,並提供有效的許可證金鑰。 以下給出了促成此事的源代碼:

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

// Get the global config object
var config = IronPdfGlobalConfig.getConfig();

// Set the license key for IronPDF
config.licenseKey = "{YOUR-LICENSE-KEY-HERE}";
import { IronPdfGlobalConfig } from "@ironsoftware/ironpdf";

// Get the global config object
var config = IronPdfGlobalConfig.getConfig();

// Set the license key for IronPDF
config.licenseKey = "{YOUR-LICENSE-KEY-HERE}";
JAVASCRIPT

Purchase a license key from our licensing page, or contact us to 獲得免費試用許可證金鑰

[{i:(許可證金鑰和其他 全球設置,在使用其他庫功能之前應設置,以確保最佳性能和正確功能。)}]

本教程的後續部分將假設我們有一個許可證金鑰,並且我們已在名為 config.js 的單獨 JavaScript 文件中設置了它。 我們在使用 IronPDF 功能時的任何地方都會導入此腳本:

import { PdfDocument } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script
// ...
import { PdfDocument } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script
// ...
JAVASCRIPT

將 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'; // Import the configuration script

// 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");
import { PdfDocument } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// 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");
JAVASCRIPT

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

PdfDocument.fromHtml 返回一個 Promise,該 Promise 解析為PdfDocument 類的實例。 PdfDocument 代表某一來源內容生成的 PDF 文件。 該類構成了IronPDF大多數核心功能的基石,推動了大量的PDF創建和編輯使用案例。

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

圖 2 The PDF generated from the HTML string "<h1>Hello from IronPDF!</h1>". 由 PdfDocument.fromHtml 生成的 PDF 文件的外觀與網頁內容的外觀相同.

從 HTML 文件創建 PDF 文件

PdfDocument.fromHtml 不僅適用於HTML字符串。 該方法還接受本地 HTML 文檔的路徑。

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

圖 3 我們的示例 HTML 頁面在 Google Chrome 中的外觀。 從文件示例網站下載此頁面及類似頁面:https://filesamples.com/samples/code/html/sample2.html

以下代碼行將整個示例文檔轉換為 PDF。 在 HTML 字符串的位置,我們使用有效的文件路徑調用 PdfDocument.fromHtml

import { PdfDocument } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// 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");
import { PdfDocument } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// 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");
JAVASCRIPT

我們在下面包括了結果 PDF 的內容。 注意:IronPDF 不僅保留了原始 HTML 文檔的外觀,還保留了鏈接、表單和其他常見交互元素的功能。

圖 4 這是從前面代碼示例中生成的 PDF。 比較其外觀與前一張圖像,注意其卓越的相似性!

如果您已檢查示例頁面的源代碼,您會發現它更為複雜。 它使用了更多類型的 HTML 元素(段落、無序列表、換行、水平分隔線、超鏈接、圖片等),並且還包括一些腳本(用於設置 Cookie)。

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

圖 5 關於 Puppeteer 的一篇文章,這是一個因能夠透過無頭瀏覽器實例以編程方式控制 Chrome 而流行的 Node 庫

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

這個新頁面需要加載許多資產(CSS 文件、圖像、腳本文件等),並且使用了更複雜的佈局。 在這個案例中,我們將轉換這個頁面的已保存副本(以及其源資產),並將其轉換為精確的像素級 PDF。

下面的代碼片段假設頁面保存在與我們的項目相同的目錄中,名為“sample4.html”:

import { PdfDocument } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// Render a PDF from even more complex HTML code.
PdfDocument.fromHtml("./sample4.html").then(async (pdf) => {
    return await pdf.saveAs("html-file-to-pdf-2.pdf");
});
import { PdfDocument } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

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

以下圖片顯示了前述代碼片段的結果。

圖 6 如果它在 Google Chrome 中看起來很好,那麼把它轉換為 PDF 時也會很好。 這包括使用大量 CSS 和 JavaScript 的頁面設計.

從 URL 創建 PDF 文件

IronPDF 可以轉換任意大小和複雜度的 HTML 字符串和 HTML 文件。 然而,您不僅限於使用來自字符串和文件的原始標記。 IronPDF 還可以從 URL 請求 HTML。

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

圖 7 關於 PDF 格式的維基百科文章,在符合標準的網頁瀏覽器中顯示的外觀。

使用以下源代碼將此維基百科文章轉換為 PDF:

import { PdfDocument } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// 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");
import { PdfDocument } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// 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");
JAVASCRIPT

上面,我們使用 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 zip 文件中的示例圖片。

在調用 fromZip 方法時,請在第一個參數中指定 zip 的有效路徑,並提供一個 JSON 對象,其中設置 mainHtmlFile 屬性為我們希望從 zip 中轉換的 HTML 文件的名稱。

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

import { PdfDocument } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// Render the HTML from a zip archive
PdfDocument.fromZip("./html-zip.zip", {
  mainHtmlFile: "index.html"
}).then(async (pdf) => {
  return await pdf.saveAs("html-zip-to-pdf.pdf");
});
import { PdfDocument } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// Render the HTML from a zip archive
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 函數獲取這些預設值:

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

// Retrieve a ChromePdfRenderOptions object with default settings.
var options = defaultChromePdfRenderOptions();
import { defaultChromePdfRenderOptions } from "@ironsoftware/ironpdf";

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

本節將快速介紹使用 ChromePdfRenderOptions 接口進行 HTML 到 PDF 渲染的最受歡迎的使用案例。

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

自定義 PDF 生成輸出

添加自定義頁眉和頁腳

使用 textHeadertextFooter 屬性,您可以為新渲染的 PDF 添加自定義頁眉和/或頁腳內容。

下面的示例創建了 Google 搜索主頁的 PDF 版本,其中包含由文本內容製作的自定義頁眉和頁腳。 我們使用分隔線將這些內容與頁面主體分開。 我們還在頁眉和頁腳中使用不同的字體,以便更清晰地區分這些內容。

import { PdfDocument, defaultChromePdfRenderOptions, AffixFonts } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// Initialize render options with default settings
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 a URL
PdfDocument.fromUrl("https://www.google.com/", { renderOptions: options }).then(async (pdf) => {
  return await pdf.saveAs("add-custom-headers-footers-1.pdf");
});
import { PdfDocument, defaultChromePdfRenderOptions, AffixFonts } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// Initialize render options with default settings
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 a URL
PdfDocument.fromUrl("https://www.google.com/", { renderOptions: options }).then(async (pdf) => {
  return await pdf.saveAs("add-custom-headers-footers-1.pdf");
});
JAVASCRIPT

源代碼生成了此 PDF:

圖 11 在 PDF 格式下創建的新頁面,它是從 Google 主頁生成的。 注意額外頁眉和頁腳的包含.

為了更好地控制標題和頁腳中包含的佈局、定位和內容,您還可以使用原始 HTML 而不是文本來定義它們。

在後續的代碼塊中,我們使用 HTML 將更豐富的內容納入頁眉和頁腳。 在頁眉中,我們將頁面 URL 置中; 在頁腳中,我們插入了一個居中的標誌。

import { PdfDocument, defaultChromePdfRenderOptions } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// Initialize render options with default settings
var options = defaultChromePdfRenderOptions();

// Define a rich HTML header
options.htmlHeader = {
  htmlFragment: "<strong>https://www.google.com/</strong>",
  dividerLine: true,
  dividerLineColor: "blue",
  loadStylesAndCSSFromMainHtmlDocument: true,
};

// Define a rich HTML footer
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 a URL
await PdfDocument.fromUrl("https://www.google.com/", { renderOptions: options }).then(async (pdf) => {
  return await pdf.saveAs("add-html-headers-footers.pdf");
});
import { PdfDocument, defaultChromePdfRenderOptions } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// Initialize render options with default settings
var options = defaultChromePdfRenderOptions();

// Define a rich HTML header
options.htmlHeader = {
  htmlFragment: "<strong>https://www.google.com/</strong>",
  dividerLine: true,
  dividerLineColor: "blue",
  loadStylesAndCSSFromMainHtmlDocument: true,
};

// Define a rich HTML footer
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 a URL
await PdfDocument.fromUrl("https://www.google.com/", { renderOptions: options }).then(async (pdf) => {
  return await pdf.saveAs("add-html-headers-footers.pdf");
});
JAVASCRIPT

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

圖 12 IronPDF for Node.js 可在將 HTML 頁面轉換為 PDF 時應用自定義。

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

IronPDF 支持其他設定,用於為新轉換的 PDF 定制頁面邊界、頁面大小和頁面方向。

import { PdfDocument, defaultChromePdfRenderOptions, PaperSize, FitToPaperModes, PdfPaperOrientation } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// Initialize render options with default settings
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");
});
import { PdfDocument, defaultChromePdfRenderOptions, PaperSize, FitToPaperModes, PdfPaperOrientation } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// Initialize render options with default settings
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");
});
JAVASCRIPT

在上面的代碼塊中,我們將 IronPDF 配置為用灰色模式、橫向生成我們 Google 主頁 PDF,並至少保留 50 毫米的邊界空間。 我們還將其設置為適應 A5 紙張大小的內容。

從動態網頁生成 PDF

對於包含非直接可用且在頁面加載時未渲染的內容的網頁,需要在某些條件達成之前暫停該頁面的內容渲染。

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

為了處理這些邊界情況(以及更多情況),IronPDF 的 Node 版本定義了 WaitFor 機制。 開發人員可以在他們的 ChromePdfRenderOptions 設定中包含該屬性,指示 IronPDF 的 Chrome 渲染引擎在一定事件發生時轉換頁面的內容。

以下代碼塊設置 IronPDF 等待 20 秒,以在抓取我們主頁的內容為 PDF:

import { PdfDocument, defaultChromePdfRenderOptions, WaitForType } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// 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");
});
import { PdfDocument, defaultChromePdfRenderOptions, WaitForType } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// 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");
});
JAVASCRIPT

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

import { PdfDocument, defaultChromePdfRenderOptions, WaitForType } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// Configure the Chrome Renderer to wait up to 20 seconds for a specific element to appear
var options = defaultChromePdfRenderOptions();
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");
});
import { PdfDocument, defaultChromePdfRenderOptions, WaitForType } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// Configure the Chrome Renderer to wait up to 20 seconds for a specific element to appear
var options = defaultChromePdfRenderOptions();
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");
});
JAVASCRIPT

從 HTML 模板生成 PDF

在本教程的最後一節中,我們將應用之前各部分中介紹的知識,以完成一個非常實用的自動化:使用 HTML 模板生成一個或多個 PDF。

本節中將使用的模板如下所示。 它是由這個公開可訪問的發票模板改編而來,並包含可替換內容的佔位標籤(例如 {COMPANY-NAME}、{FULL-NAME}、{INVOICE-NUMBER} 等)。

圖 13 一個發票模板示例。 我們將編寫額外的 JavaScript 代碼,以在生成 PDF 之前向此模板中添加動態數據.

在下一個源代碼塊中,我們將 HTML 模板加載到新 PdfDocument 對象中,替換定義的佔位符,並將 PdfDocument 對象保存到文件系統。

import { PdfDocument } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

/**
 * 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);
}

// Path to the template file
const template = "./sample-invoice.html";

// Load the template, replace placeholders, and save the PDF
getTemplateHtml(template).then(async (doc) => {
    // Replace placeholders with real data
    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"));
import { PdfDocument } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

/**
 * 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);
}

// Path to the template file
const template = "./sample-invoice.html";

// Load the template, replace placeholders, and save the PDF
getTemplateHtml(template).then(async (doc) => {
    // Replace placeholders with real data
    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"));
JAVASCRIPT

以上源代碼定義了三個異步輔助函數:

  • 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,那麼此參考將非常有用。

常見問題解答

如何在Node.js中將HTML轉換為PDF而不遺失格式?

在 Node.js 中,您可以使用 IronPDF 將 HTML 轉換為 PDF,而不會遺失格式,方法是採用PdfDocument.fromHtml等方法,該方法支援將 HTML 字串和檔案精確渲染為 PDF 格式。

安裝適用於Node.js的IronPDF需要哪些步驟?

若要在 Node.js 專案中安裝 IronPDF,請執行指令npm install @ironsoftware/ironpdf 。這會將 IronPDF 套件新增到專案的依賴項中,使您能夠使用它的 PDF 處理功能。

如何在Node.js中根據網頁URL產生PDF檔?

在 IronPDF 中,您可以使用PdfDocument.fromUrl方法,透過提供網頁的 URL 將網頁直接轉換為 PDF。此方法會取得網頁內容並將其渲染為 PDF 格式。

IronPDF中有哪些自訂PDF輸出的選項?

IronPDF 提供ChromePdfRenderOptions接口,讓使用者自訂 PDF 輸出。您可以透過此介面調整頁面大小、方向、邊距等設置,並新增動態內容。

如何使用 IronPDF 為我的 PDF 文件添加頁首和頁尾?

若要在 IronPDF 中為 PDF 新增頁首和頁尾,請使用ChromePdfRenderOptions中提供的textHeadertextFooter屬性。這樣就可以在每頁的頂部和底部添加自訂文字。

是否可以使用Node.js將zip壓縮套件中的HTML檔案轉換為PDF檔案?

是的,IronPDF 支援使用PdfDocument.fromZip方法將 zip 壓縮套件中的 HTML 檔案轉換為 PDF,因此可以批次處理多個 HTML 檔案。

如何移除使用 IronPDF 產生的 PDF 檔案中的浮水印?

若要從使用 IronPDF 建立的 PDF 檔案中移除浮水印,您必須在應用程式中套用有效的許可證金鑰。這可以透過IronPdf.License.LicenseKey方法完成。

將非同步網頁內容轉換為 PDF 時,我該如何處理?

IronPDF 提供WaitFor機制來管理非同步內容,確保所有動態元素在 PDF 渲染過程開始之前完全載入。

IronPDF 能否將受密碼保護的網頁轉換為 PDF 檔案?

是的,您可以使用ChromePdfRenderOptions中的HttpLoginCredentials ,輸入必要的憑證來存取和將受密碼保護的網頁轉換為 PDF。

如果我的 HTML 轉 PDF 轉換後無法保持正確的佈局,我該怎麼辦?

請確保您使用的ChromePdfRenderOptions設定符合佈局要求。調整頁面大小、方向和邊距等設定有助於在轉換後的 PDF 中保持所需的佈局。

IronPDF 是否完全支援 .NET 10 中的 HTML 轉 PDF 轉換?

是的-IronPDF 支援 .NET 10,可使用ChromePdfRenderer等類別將 HTML 轉換為 PDF,包括RenderHtmlAsPdfRenderHtmlFileAsPdfRenderUrlAsPdf方法,並支援 CSS3、JavaScript、映像和外部資源。 IronPDF 的 .NET PDF 庫功能文件中對此有明確說明。

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

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

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

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

準備好開始了嗎?
版本: 2025.11 剛剛發布