在 Node.js 中将 HTML 转换为 PDF

[@64:(IronPDF的最强大和最受欢迎的功能是能够从原始HTML、CSS和JavaScript创建高保真PDF。)] [@65:(本教程引导Node.js开发者了解将HTML内容转化为PDF的每一种实用方法——从单行字符串转换直到动态模板驱动的文档生成。)]

[@66:(IronPDF是一个高级API库,能够帮助开发者快速将强大的PDF处理功能实现到软件应用程序中。)] IronPDF 提供 多种编程语言。 [@67:(有关在.NETJavaPython中创建PDF文档的详细介绍,请参阅官方文档页面。)] [@68:(本教程涵盖它在Node.js项目中的应用。)]

[@69:(快速入门:在Node.js中将HTML转换为PDF)]

目录

[@74:(- 如何开始使用IronPDF for Node.js?)] [@75:(- 如何在Node.js中将HTML转换为PDF?)] [@76:( - 如何从HTML字符串创建PDF?)] [@77:( - 如何从HTML文件创建PDF?)] [@78:( - 如何从URL创建PDF?)] [@79:( - 如何从Zip压缩包创建PDF?)] [@80:(- IronPDF支持哪些高级渲染选项?)] [@81:( - 如何添加标题和页脚?)] [@82:( - 如何控制页面大小、方向和边距?)] [@83:( - 如何处理动态网页?)] [@84:(- 如何从HTML模板生成PDF?)]

[@85:(## 如何开始使用IronPDF for Node.js?)] [@86:([#getting-started])]

今天在您的项目中使用 IronPDF,免费试用。

第一步:
green arrow pointer

安装IronPDF库

[@87:(在您选择的Node.js项目中运行以下NPM命令来安装IronPDF Node.js包:)]

//:path=/static-assets/ironpdf-nodejs/content-code-examples/tutorials/html-to-pdf/install.sh
npm install @ironsoftware/ironpdf
//:path=/static-assets/ironpdf-nodejs/content-code-examples/tutorials/html-to-pdf/install.sh
npm install @ironsoftware/ironpdf
SHELL

[@88:(您也可以手动下载并安装IronPDF包。)]

[@89:(### 如何安装IronPDF引擎?)]

[@90:(IronPDF for Node.js需要一个IronPDF引擎二进制文件来运行。)]

[@91:([@i:(安装IronPDF引擎是可选的。)] @ironsoftware/ironpdf 软件包在首次运行时会自动下载并安装适用于您操作系统的相应二进制文件。 [@93:(在网络访问受到限制或不可用的环境中,建议手动安装。)]]

[@94:(通过安装适合您操作系统的包来安装IronPDF引擎二进制文件。)]

如何应用许可证密钥?

[@95:(默认情况下,IronPDF会在它生成或修改的所有文档上添加水印。)] 要移除水印,请在全局 IronPdfGlobalConfig 对象上设置 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}";
//: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

[@97:(获取一个免费试用许可证密钥或从许可页面购买许可证密钥。)]

[@98:([@i:(设置许可证密钥和任何其他全球配置设置]在调用其他库函数之前。)] [@99:(这可以确保应用程序的最佳性能和正确行为。)]]

本教程中其余的代码示例假设已将许可证密钥应用在单独的 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
// ...
//: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

未使用许可证密钥生成的 PDF 文档上显示的 IronPDF 水印 在 ironpdf.com/nodejs/licensing/ 上获取许可证密钥以生成无水印的 PDF 文档。

[@102:(## 如何在Node.js中将HTML转换为PDF?)] [@103:([#convert-html-to-pdf])]

[@104:(IronPDF Node.js库提供了四种从HTML内容创建PDF文件的方法:)]

  1. 从 HTML 代码字符串中
  2. 从本地 HTML 文件中 [@105:(3. 从在线URL创建)] [@106:(4. 从压缩的ZIP档案创建)]

每种方法均以 PdfDocument 类为基础。 PdfDocument 代表由源内容生成的 PDF 文件,并驱动 IronPDF 大部分核心的创建和编辑功能。

[@109:(### 如何从HTML字符串创建PDF?)] [@110:([#create-pdf-from-html-string])]

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");
//: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.fromHtml 返回一个 Promise,该 Promise 解析为 PdfDocument 类的实例。 获取实例后,调用 saveAs 并传入目标文件路径,即可将 PDF 写入磁盘。 [@114:(保存的PDF文件会将HTML呈现为符合标准的浏览器显示的样子。)]

PDF document generated from the HTML string containing a level-one heading Hello from IronPDF! The PDF generated from the HTML string <h1>Hello from IronPDF!</h1>. 由 PdfDocument.fromHtml 生成的 PDF 文件显示效果与网页内容完全一致。

[@118:(### 如何从HTML文件创建PDF? {#create-pdf-from-html-file})]

PdfDocument.fromHtml 也支持传入本地 HTML 文档的路径。 [@120:(而不是一段标记字符串,将有效的文件路径作为第一个参数传递。)] [@121:(这是在处理引用本地CSS、JavaScript和图像资产的保存网页时的首选方法。)]

[@122:(以下示例将示例网页转换为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");
//: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 中显示的 HTML 页面示例(转换为 PDF 前) [@124:(示例HTML页面在Google Chrome中的显示。)] [@125:(从文件示例网站下载该页面及类似页面:https://filesamples.com/samples/code/html/sample2.html)]

[@126:(IronPDF会保持原始HTML文档的外观,并保留链接、表单和其他交互元素的功能。)] [@127:(这种保真度扩展至包含段落、列表、图像、超链接和客户端脚本的复杂页面。)]

由示例 HTML 文件生成的 PDF 文档,完整还原了原始页面布局 [@129:(此PDF是从上面的HTML文件示例生成的。)] [@130:(与之前的图像比较其外观——IronPDF保留了布局的高保真度。)]

[@131:(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");
});
//: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 文件 [@133:(如果在Google Chrome中看起来不错,转换为PDF时也会看起来不错。)] [@134:(这包括CSS重和JavaScript渲染的页面设计。)]

[@135:([@t:(如果页面的资源来自本地文件路径,请确保所有引用的CSS文件、图像和脚本相对于HTML文件的位置存在。)] [@136:(IronPDF的Chrome渲染引擎以与浏览器相同的方式解析这些路径。)]]

[@137:(### 如何从URL创建PDF?)] [@138:([#create-pdf-from-url])]

PdfDocument.fromUrl 用于抓取并渲染实时网页为 PDF 文件。 [@140:(将任何公开可访问的URL作为参数传递。)] [@141:(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");
//: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 格式的 Wikipedia 文章,其在符合标准的网络浏览器中的显示方式。

通过在维基百科PDF文章页面调用 PdfDocument.fromUrl 生成的PDF文档 通过在维基百科条目中调用 PdfDocument.fromUrl 生成的 PDF。 [@145:(请注意其与原始网页的高度相似性。)]

[@146:([@n:(基于URL的转换需要目标服务器对于运行IronPDF的机器是可访问的。)] 位于身份验证、VPN 或防火墙后方的页面可能需要通过 ChromePdfRenderOptions 进行额外配置。)}]

[@148:(### 如何从Zip压缩包创建PDF? {#create-pdf-from-zip})]

PdfDocument.fromZip 将 ZIP 压缩包中包含的特定 HTML 文件转换为 PDF。 [@150:(这在分发将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="IronPDF for Node.js">
    </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="IronPDF for Node.js">
    </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 文件中包含的 Sample 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");
});
//: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 徽标及黑色背景上的样式化标题 使用 PdfDocument.fromZip 创建 PDF。 该函数成功渲染了ZIP文件中的HTML代码以及其捆绑的资产。

IronPDF支持哪些高级渲染选项? {#advanced-rendering-options}

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();
//: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 参数。

如何添加页眉和页脚? {#add-headers-footers}

textHeadertextFooter 属性可在新渲染的 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");
});
//: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,添加了自定义的页眉和页脚 这是从 Google 首页生成的 PDF 文件,其中应用了使用 textHeadertextFooter 生成的自定义文本页眉和页脚。

若需更丰富的页眉和页脚布局,请改用 htmlHeaderhtmlFooter 属性。 这些接受原生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");
});
//: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 的页眉(以粗体显示页面 URL)和基于 HTML 的页脚(显示 IronPDF 徽标)生成的 PDF 文件 IronPDF支持基于HTML的页眉和页脚,能够在每一页上完全控制品牌和布局。

如何控制页面大小、方向和边距? {#page-size-orientation-margins}

paperOrientation 以及 grayScale 属性控制着每个渲染页面的物理布局。 以下示例将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");
});
//: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

PaperSize 枚举包含标准纸张尺寸,例如 LetterLegalPdfPaperOrientation 枚举支持 PortraitLandscape。 这些设置对打印就绪文档的输出尺寸提供了精确控制。

提示生成用于打印工作流程的PDF时,请始终明确指定边距。 默认边距可能不符合目标打印机或纸张格式的要求。

如何处理动态网页? {#dynamic-web-pages}

通过JavaScript计时器、懒加载或API调用异步加载内容的页面,可能在IronPDF的引擎捕获时尚未完全呈现。 通过 waitFor 上的 ChromePdfRenderOptions 属性配置的 WaitFor 机制,会指示 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");
});
//: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");
});
//: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-template-to-PDF}

一个常见的实际自动化模式是从共享HTML模板生成一批PDF,用数据库、API或电子表格中的数据替换占位符值。 IronPDF 的 replaceText 方法在 PdfDocument 上可直接处理此操作。

下面的发票模板示例(改编自一个公开的 CodePen 发票模板)使用了大括号占位符(如 {FULL-NAME}{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

上面的代码定义了三个异步辅助函数:

  • getTemplateHtml:使用 PdfDocument 将 HTML 文件加载到 PdfDocument.fromHtml 对象中。
  • addTemplateData:调用 PdfDocument.replaceText 将占位符键替换为实际数据值。
  • generatePdf:将生成的 PdfDocument 写入目标文件路径。

每个 replaceText 调用都直接作用于内存中的 PDF 表示形式,因此可以链式调用多个替换操作,而无需从磁盘重新加载文档。 生成的PDF保留了原始模板的所有CSS样式、字体和布局。

使用发票模板生成并替换所有占位符为实际数据后的 PDF 文档 已完成的PDF发票,占位符值已替换为真实数据。 原始模板的CSS样式和布局被精确保留。

这种方法在批量文档生成中表现良好。 每条记录调用一次 getTemplateHtml 以为每个输出文件创建一个新的 PdfDocument,然后在调用 generatePdf 之前,依次调用 addTemplateData 处理该记录的数据。

下一步是什么? {#next-steps}

本教程涵盖了核心HTML到PDF转换方法以及IronPDF for Node.js中最常用的渲染选项。 下面的主题将您在此处学习的内容扩展到更专业的领域。

常见问题解答

如何在Node.js中将HTML转换为PDF?

使用IronPDF库。通过npm install @ironsoftware/ironpdf安装,然后用HTML字符串或文件路径调用PdfDocument.fromHtml,或用网址调用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属性以进行简单文本页眉和页脚。对于更丰富的布局,使用htmlHeaderhtmlFooter结合原始HTML片段。将选项对象传给任何转换方法的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?

用ZIP文件路径作为第一个参数和选项对象为第二个参数调用PdfDocument.fromZip。将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.5 just released
Still Scrolling Icon

还在滚动吗?

想快速获得证据?
运行示例看着你的HTML代码变成PDF文件。