在Node.js中將HTML轉換為PDF

將HTML轉換為Node.js中的PDF

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

IronPDF最強大和最受歡迎的功能是能夠從原始HTML、CSS和JavaScript建立高保真PDF。 本教程引導Node.js開發者通過每種實用方法將HTML內容轉換為PDF,從單行字串轉換到動態模板驅動的文件生成。

IronPDF是一個高級API程式庫,幫助開發者快速將強大的PDF處理功能整合到軟體應用中。 IronPDF在多種編程語言中可用。 有關建立PDF的詳細資訊,請參閱.NETJavaPython的官方文件頁面。 本教程涵蓋了其在Node.js項目中的應用。

快速入門:將HTML轉換為Node.js中的PDF

目錄

如何開始使用IronPDF for Node.js?

今天就使用IronPDF開始專案,免費試用。

第一步:
green arrow pointer

安裝IronPDF程式庫

在您選擇的Node.js項目中運行以下NPM命令來安裝IronPDF Node.js包:

 npm i @ironsoftware/ironpdf

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

如何安裝IronPDF引擎?

Node.js的IronPDF需要IronPDF引擎二進制文件才能運行。

請注意安裝IronPDF引擎是可選的。 @ironsoftware/ironpdf包在首次執行時會自動下載並安裝適合您操作系統的二進制文件。 在互聯網存取受限或不可用的環境中,建議明確安裝。

通過安裝適合您操作系統的包來安裝IronPDF引擎二進制文件。

如何應用授權金鑰?

預設情況下,IronPDF會將其生成或修改的所有文件用水印進行標記。 要移除水印,將有效的授權金鑰設置到全域licenseKey屬性中:

:path=/static-assets/ironpdf-nodejs/content-code-examples/tutorials/html-to-pdf/config.js
import { IronPdfGlobalConfig } from "@ironsoftware/ironpdf";

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

// Set a valid license key to remove watermarks
config.licenseKey = "{YOUR-LICENSE-KEY-HERE}";
JAVASCRIPT

獲取免費試用授權金鑰或從授權頁面購買授權金鑰

請注意設置授權金鑰和其他全域配置設置在調用其他庫函式之前。 這可確保應用程式的最佳性能和正確行為。

本教程中剩餘的程式碼範例假設授權金鑰已經在一個單獨的config.js文件中應用,並在每個腳本的頂部導入:

:path=/static-assets/ironpdf-nodejs/content-code-examples/tutorials/html-to-pdf/config-import.js
import { PdfDocument } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script
// ...
JAVASCRIPT

IronPDF水印顯示在沒有授權金鑰的情況下生成的PDF文件 獲取授權金鑰,請參訪ironpdf.com/nodejs/licensing/,以生成不含水印的PDF文件。

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

IronPDF Node.js庫提供了四種從HTML內容建立PDF文件的方法:

  1. 從HTML程式碼字串建立
  2. 從本地HTML文件建立
  3. 從線上URL建立
  4. 從壓縮的ZIP存檔建立

每種方法都以PdfDocument類作為基礎。 PdfDocument代表由某些源內容生成的PDF文件,驅動著IronPDF的主要建立和編輯功能。

如何從HTML字串建立PDF?

PdfDocument.fromHtml從原始HTML標記字串生成PDF。這種方法在四種方法中提供了最大的靈活性,因為HTML字串幾乎可以來自任何地方——文字文件、資料流、HTML模板引擎或動態構建的標記。

:path=/static-assets/ironpdf-nodejs/content-code-examples/tutorials/html-to-pdf/html-string-to-pdf.js
import { PdfDocument } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// Create a PDF from an HTML string
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類實例的Promise。 獲得該實例後,調用saveAs並提供一個目標文件路徑,將PDF寫入磁盤。 保存的PDF文件會將HTML渲染得與標準瀏覽器顯示完全一致。

由 HTML 字串產生的 PDF 文件,內含一級標題「Hello from IronPDF!」 The PDF generated from the HTML string <h1>Hello from IronPDF!</h1>. 由PdfDocument.fromHtml生成的PDF文件看起來就像網頁內容一樣。

如何從HTML文件建立PDF?

PdfDocument.fromHtml也接受本地HTML文件的路徑。 將有效的文件路徑作為第一個參數傳遞,而不是標記字串。 這是在處理引用本地CSS、JavaScript和圖片資產的保存網頁時的首選方法。

以下範例將範例網頁轉換為PDF:

:path=/static-assets/ironpdf-nodejs/content-code-examples/tutorials/html-to-pdf/html-file-to-pdf.js
import { PdfDocument } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

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

// Save the PDF document to the project directory
await pdf.saveAs("html-file-to-pdf-1.pdf");
JAVASCRIPT

在Google Chrome中轉換為PDF之前顯示的樣本HTML頁面 在Google Chrome中顯示的樣本HTML頁面。 從文件樣本網站下載此頁面及類似頁面:https://filesamples.com/samples/code/html/sample2.html

IronPDF保留了原始HTML文件的外觀,並保留了連結、表單和其他交互元素的功能。 這種保真度延伸到包含段落、列表、圖片、超連結和客戶端腳本的復雜頁面。

從範例HTML文件中生成的PDF文件,展示對原始頁面佈局的忠實再現 這個PDF是從上述HTML文件範例生成的。 將其外觀與前一張圖片進行比較——IronPDF用高保真度保留了佈局。

IronPDF處理的不只是簡單標記的頁面。以下範例將一個功能豐富的頁面轉換為源自多個外部CSS文件、圖片和腳本資產的內容:

:path=/static-assets/ironpdf-nodejs/content-code-examples/tutorials/html-to-pdf/html-complex-file-to-pdf.js
import { PdfDocument } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

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

從包含豐富CSS樣式和由JavaScript渲染的內容的複雜HTML頁面生成的PDF 如果它在Google Chrome中看起來不錯,那麼在轉換為PDF時也會不錯。 這包括包含大量CSS和JavaScript渲染頁面設計。

提示如果頁面引用來自本地文件路徑的資產,確保在HTML文件位置下存在所有引用的CSS文件、圖片和腳本。 IronPDF的Chrome渲染引擎會像瀏覽器一樣解析這些路徑。

如何從URL建立PDF?

PdfDocument.fromUrl獲取並渲染實時網頁為PDF。 將任何公開可存取的URL作為參數傳遞。 IronPDF的Chrome渲染引擎檢索該頁面,載入所有資產,並產生像素級完美的PDF——不需要手動下載HTML。

:path=/static-assets/ironpdf-nodejs/content-code-examples/tutorials/html-to-pdf/url-to-pdf.js
import { PdfDocument } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// Convert a live web page to a PDF
const pdf = await PdfDocument.fromUrl("https://en.wikipedia.org/wiki/PDF");

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

在標準瀏覽器中顯示的有關PDF格式的維基百科文章 在標準網頁瀏覽器中顯示的有關PDF格式的維基百科文章。

從維基百科PDF文章頁面調用PdfDocument.fromUrl生成的PDF文件 從調用PdfDocument.fromUrl上的維基百科文章相應生成的PDF。 注意其與原始網頁的接近程度。

重要基於URL的轉換要求目標伺服器從運行IronPDF的機器可存取。 需要額外配置頁面後的身份驗證、VPN或防火牆。使用ChromePdfRenderOptions

如何從Zip存檔建立PDF?

PdfDocument.fromZip將ZIP歸檔中的特定HTML文件轉換為PDF。 當分發將HTML、CSS和圖片資產捆綁在一起的自包HTML項目時,特別有用。

在此範例中,假設項目目錄包含具有以下結構的ZIP文件:

//:path=/static-assets/ironpdf-nodejs/content-code-examples/tutorials/html-to-pdf/zip-structure.txt
html-zip.zip
├─ index.html
├─ style.css
├─ logo.png

index.html文件中包含:

//:path=/static-assets/ironpdf-nodejs/content-code-examples/tutorials/html-to-pdf/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="適用於 Node.js 的 IronPDF">
    </a>
  </body>
</html>
//:path=/static-assets/ironpdf-nodejs/content-code-examples/tutorials/html-to-pdf/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="適用於 Node.js 的 IronPDF">
    </a>
  </body>
</html>
HTML

style.css聲明頁面布局和字體規則:

//:path=/static-assets/ironpdf-nodejs/content-code-examples/tutorials/html-to-pdf/style.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;
}

在假設的HTML ZIP文件中包含的範例logo.png圖片 假設的HTML ZIP文件內的樣本圖片。

調用fromZip時,指定ZIP文件的路徑作為第一個參數,並指定配置物件作為第二個。 設置mainHtmlFile屬性為存檔內需要轉換的HTML文件名稱:

:path=/static-assets/ironpdf-nodejs/content-code-examples/tutorials/html-to-pdf/zip-to-pdf.js
import { PdfDocument } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// Convert an HTML file from a ZIP archive to PDF
PdfDocument.fromZip("./html-zip.zip", {
  mainHtmlFile: "index.html"
}).then(async (pdf) => {
  return await pdf.saveAs("html-zip-to-pdf.pdf");
});
JAVASCRIPT

從HTML ZIP歸檔生成的PDF,顯示IronPDF logo和黑色背景上的樣式標題 使用PdfDocument.fromZip進行PDF建立。 該函式成功渲染了ZIP文件中的HTML程式碼以及其捆綁的資產。

Icon Quote related to 如何從Zip存檔建立PDF?

我最喜歡的程式庫是IronPDF。它允許快速高效地操作PDF文件。它還有許多有價值的功能,例如導出到PDF/A格式和數位簽署PDF文件。

Milan Jovanovic related to 如何從Zip存檔建立PDF?

Milan Jovanovic

Microsoft MVP

查看案例研究
Icon Quote related to 如何從Zip存檔建立PDF?

IronOCR意味著我們每年可以從手動處理中節省$40,000,同時提高生產力,釋放資源以進行高影響的任務。我會強烈推薦它。

Brent Matzelle related to 如何從Zip存檔建立PDF?

Brent Matzelle

首席技術官,OPYN

查看案例研究
Icon Quote related to 如何從Zip存檔建立PDF?

IronSuite在我們的運營中扮演著至關重要的角色。這些工具增加了包括建立平面圖和改善庫存管理在內的業務效率。

David Jones related to 如何從Zip存檔建立PDF?

David Jones

首席軟體工程師,Agorus Build

查看案例研究

IronPDF支持哪些高級渲染選項?

ChromePdfRenderOptions接口提供了對PDF渲染行為的細膩自定義屬性。 這些設置在PDF生成之前應用,涵蓋佈局、視覺外觀和動態內容的邊界情況。

IronPDF對每次轉換應用預設渲染設置。 使用defaultChromePdfRenderOptions函式檢索這些預設值:

:path=/static-assets/ironpdf-nodejs/content-code-examples/tutorials/html-to-pdf/default-options.js
import { defaultChromePdfRenderOptions } from "@ironsoftware/ironpdf";

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

根據需要修改返回物件的屬性,並將其傳遞給任何轉換方法的renderOptions參數。

如何新增標頭和頁腳?

textFooter屬性將自定義基於文字的內容附加到每個新渲染的PDF頁面。 以下範例使用不同的字體從Google搜索主頁建立帶有自定義標頭和頁腳的PDF:

:path=/static-assets/ironpdf-nodejs/content-code-examples/tutorials/html-to-pdf/custom-headers-footers.js
import { PdfDocument, defaultChromePdfRenderOptions, AffixFonts } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// Start from default render options
var options = defaultChromePdfRenderOptions();

// Configure a text-based header
options.textHeader = {
  centerText: "https://www.adobe.com",
  dividerLine: true,
  font: AffixFonts.CourierNew,
  fontSize: 12,
  leftText: "URL to PDF"
};

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

從Google主頁建立的PDF,新增了自定義文字標頭和頁腳 使用textFooter從Google主頁生成帶有自定義文字標頭和頁腳的PDF。

對於更豐富的標頭和頁腳佈局,請改用htmlFooter屬性。 這些屬性接受原始HTML片段,提供對排版、圖片和對齊的完整控制。 下面的範例在標頭中以粗體居中頁面URL,並在頁腳嵌入一個logo圖片:

:path=/static-assets/ironpdf-nodejs/content-code-examples/tutorials/html-to-pdf/html-headers-footers.js
import { PdfDocument, defaultChromePdfRenderOptions } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// Start from default render options
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 with a logo
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
};

// Apply custom HTML headers and footers during rendering
await PdfDocument.fromUrl("https://www.google.com/", { renderOptions: options }).then(async (pdf) => {
  return await pdf.saveAs("add-html-headers-footers.pdf");
});
JAVASCRIPT

用HTML為基礎的標頭生成的PDF,顯示頁面URL以粗體和用HTML為基礎的頁腳顯示IronPDF logo IronPDF支持基於HTML的標頭和頁腳,提供對每個頁面上品牌和佈局的完整控制。

如何控制頁面大小、方向和邊距?

ChromePdfRenderOptions中控制每個渲染頁面的物理佈局。 以下範例將Google主頁轉換為帶有自定義邊距、A5橫向和灰階輸出的頁面:

:path=/static-assets/ironpdf-nodejs/content-code-examples/tutorials/html-to-pdf/page-size-orientation.js
import { PdfDocument, defaultChromePdfRenderOptions, PaperSize, FitToPaperModes, PdfPaperOrientation } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// Start from default render options
var options = defaultChromePdfRenderOptions();

// Set page margins in millimeters
options.margin = {
  top: 50,
  bottom: 50,
  left: 60,
  right: 60
};

// Configure paper size, fit mode, orientation, and color mode
options.paperSize = PaperSize.A5;
options.fitToPaperMode = FitToPaperModes.FitToPage;
options.paperOrientation = PdfPaperOrientation.Landscape;
options.grayScale = true;

// Render with the customized layout settings
PdfDocument.fromUrl("https://www.google.com/", { renderOptions: options }).then(async (pdf) => {
  return await pdf.saveAs("set-margins-and-page-size.pdf");
});
JAVASCRIPT

LegalLandscape。 這些設置提供了對印刷就緒文件輸出尺寸的精確控制。

提示在為印刷工作流生成PDF時,始終需要顯式指定邊距。 預設邊距可能不符合目標列印機或紙張格式的要求。

如何處理動態網頁?

通過JavaScript定時器、延遲載入或API調用異步載入內容的頁面可能在IronPDF引擎捕獲它們時未完全渲染。 ChromePdfRenderOptions上配置,指導Chrome渲染引擎在達到指定條件後再捕獲頁面。

以下程式碼塊設置IronPDF以在捕獲頁面內容前等待20秒:

:path=/static-assets/ironpdf-nodejs/content-code-examples/tutorials/html-to-pdf/waitfor-delay.js
import { PdfDocument, defaultChromePdfRenderOptions, WaitForType } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// Configure the renderer to wait 20 seconds before capturing
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等待特定的DOM元素出現後再渲染。 這在內容在JavaScript框架完成組合後注入的頁面中特別有用:

:path=/static-assets/ironpdf-nodejs/content-code-examples/tutorials/html-to-pdf/waitfor-element.js
import { PdfDocument, defaultChromePdfRenderOptions, WaitForType } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

// Configure the renderer to wait for a specific DOM element (up to 20 seconds)
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

WaitForType.HtmlElement策略使用標準CSS查詢選擇器。 渲染引擎輪詢元素的存在,直到maxWaitTime毫秒過去或找到元素——以先發生者為准。

警告設置過長的等待時間可能顯著增加高吞吐量應用中的PDF生成時間。 使用能可靠捕獲您的使用案例要求的內容的最小延遲。

如何從HTML模板生成PDF?

一個常見的現實世界自動化模式是從共享的HTML模板生成一批PDF,將資料庫、API或電子表格中的佔位符值替換為實際資料。 IronPDF的PdfDocument上直接處理此問題。

以下的樣本發票模板(改編自公開獲得的CodePen發票模板)使用了如{INVOICE-NUMBER}的大括號佔位符作為替換內容:

帶有用於動態資料替換的佔位符標籤的發票HTML樣本模板 帶有佔位符標籤的樣本發票模板。 JavaScript程式碼將在文件保存為PDF之前將每個標籤替換為實際資料。

以下程式碼載入模板,將每個佔位符替換為測試資料,並將結果保存為PDF:

//:path=/static-assets/ironpdf-nodejs/content-code-examples/tutorials/html-to-pdf/html-template-to-pdf.js
import { PdfDocument } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

/**
 * Loads an HTML template from the file system as a PdfDocument.
 */
async function getTemplateHtml(fileLocation) {
  return PdfDocument.fromHtml(fileLocation);
}

/**
 * Saves a PdfDocument to the specified file path.
 */
async function generatePdf(pdf, location) {
  return pdf.saveAs(location);
}

/**
 * Replaces a named placeholder in the PdfDocument with a data value.
 */
async function addTemplateData(pdf, key, value) {
  return pdf.replaceText(key, value);
}

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

// Load the template, fill in all placeholder values, then save the PDF
getTemplateHtml(template).then(async (doc) => {
    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"));
//:path=/static-assets/ironpdf-nodejs/content-code-examples/tutorials/html-to-pdf/html-template-to-pdf.js
import { PdfDocument } from "@ironsoftware/ironpdf";
import './config.js'; // Import the configuration script

/**
 * Loads an HTML template from the file system as a PdfDocument.
 */
async function getTemplateHtml(fileLocation) {
  return PdfDocument.fromHtml(fileLocation);
}

/**
 * Saves a PdfDocument to the specified file path.
 */
async function generatePdf(pdf, location) {
  return pdf.saveAs(location);
}

/**
 * Replaces a named placeholder in the PdfDocument with a data value.
 */
async function addTemplateData(pdf, key, value) {
  return pdf.replaceText(key, value);
}

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

// Load the template, fill in all placeholder values, then save the PDF
getTemplateHtml(template).then(async (doc) => {
    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

上面的程式碼定義了三個異步幫助函式:

  • PdfDocument物件中。
  • PdfDocument.replaceText替換佔位符鍵為其實際資料值。
  • PdfDocument寫入目標文件路徑。

每個replaceText調用直接在記憶體中的PDF表示上操作,因此可以在不從磁盤重新載入文件的情況下連結多個替換。 生成的PDF保留了原始模板中的所有CSS樣式、字體和佈局。

在所有佔位符替換為真實資料後從發票模板生成的PDF文件 將佔位符值替換為真實資料的完成PDF發票。 原始模板的CSS樣式和佈局被精確保留。

這種方法在批量文件生成中具有良好的擴展性。 為每個輸出文件調用generatePdf

接下來的步驟是什麼?

本教程涵蓋了Node.js中IronPDF的核心HTML至PDF轉換方法和最常用的渲染選項。 以下主題擴展了您在這裡學到的知識,進入更專門的領域。

常見問題

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

使用IronPDF程式庫。通過npm install @ironsoftware/ironpdf安裝它,然後調用PdfDocument.fromHtml並附上HTML字串或文件路徑,或使用PdfDocument.fromUrl並附上網頁地址。使用PdfDocument.saveAs保存結果。

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

用HTML字串作為參數調用PdfDocument.fromHtml。該方法返回一個Promise,解析為PdfDocument實例。在結果上連結saveAs以將PDF寫入磁碟。

如何在Node.js中將本地HTML文件轉換為PDF?

將有效的文件系統路徑傳遞給PdfDocument.fromHtml而不是HTML字串。IronPDF會像瀏覽器載入文件一樣解析相對CSS、圖像和脚本路徑。

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

使用目標URL調用PdfDocument.fromUrl。IronPDF使用其Chrome渲染引擎獲取頁面,並生成像素完美的PDF。目標URL必須可以從執行IronPDF的主機存取。

如何在Node.js中為PDF新增頁眉和頁腳?

對於簡單的文字頁眉和頁腳,在ChromePdfRenderOptions物件上設置textHeadertextFooter屬性。對於更豐富的佈局,使用帶有原始HTML的htmlHeaderhtmlFooter。將選項物件傳遞給任意轉換方法的renderOptions參數。

如何在Node.js中更改IronPDF的頁面大小和方向?

options.paperSize設置為PaperSize枚舉中的值(如PaperSize.A4PaperSize.Letter),並將options.paperOrientation設置為PdfPaperOrientation.PortraitPdfPaperOrientation.Landscape。將配置好的選項傳遞給轉換方法。

轉換為PDF時,如何處理動態JavaScript內容?

使用ChromePdfRenderOptions上的waitFor屬性。將type設置為WaitForType.RenderDelay並提供以毫秒為單位的延遲,或將type設置為WaitForType.HtmlElement並提供CSS查詢選擇器。IronPDF將暫停渲染直到滿足條件。

如何將ZIP檔案中的HTML文件轉換為PDF?

調用PdfDocument.fromZip,第一個參數是ZIP文件的路徑,第二個參數是一個選項物件。將mainHtmlFile屬性設置為應轉換的存檔內HTML文件的名稱。

如何從生成的PDF中移除IronPDF水印?

在調用任何轉換方法之前,將有效的授權金鑰應用於全域配置。使用IronPdfGlobalConfig.getConfig()檢索配置物件,然後將config.licenseKey設置為您的金鑰。在ironpdf.com上可以獲取免費試用授權。

如何在Node.js中從HTML模版生成PDF?

使用PdfDocument.fromHtml載入模板,然後針對模板中的每個佔位符調用PdfDocument.replaceText,傳入佔位符字串及其替代值。在所有替換完成後,調用saveAs將最終的PDF寫入。

Darrius Serrant
全端軟體工程師(WebOps)

Darrius Serrant擁有邁阿密大學的電腦科學學士學位,並在Iron Software擔任全端WebOps行銷工程師。從小就對程式設計有興趣,他認為計算既神秘又易於理解,成為創意和問題解決的完美媒介。

在Iron Software,Darrius喜歡創造新事物並簡化複雜的概念,使其更易於理解。作為我們的常駐開發人員之一,他還志願教學,將他的專業知識傳授給下一代。

對Darrius來說,他的工作是有意義的,因為它有價值且對社會有真正的影響。

準備好開始了嗎?
版本: 2026.6 剛剛發布
Still Scrolling Icon

還在滾動嗎?

想要快速的證據嗎?
運行範例觀看您的HTML變為PDF。