HTML 轉 PDF NodeJS
IronPDF 最強大、最受歡迎的功能是能夠從原始 HTML、CSS 和 JavaScript 建立高保真 PDF。 本教學課程是一份全面的入門指南,旨在幫助Node開發人員利用IronPDF將HTML轉PDF產生功能整合到自己的專案中。
IronPDF 是一個進階 API 庫,可協助開發人員快速輕鬆地將強大且穩健的 PDF 處理功能整合到軟體應用程式中。 IronPDF支援多種程式語言。 有關如何在.NET 、 Java和Python中建立 PDF 的詳細介紹,請參閱官方文件頁面。 本教學將介紹它在 Node.js 專案中的用法。
如何在Node.js中將HTML轉換為PDF
- Install the HTML to PDF Node library via NPM:
npm install @ironsoftware/ironpdf. - 從
@ironsoftware/ironpdf套件中匯入PdfDocument類別。 - 從HTML字符串、文件或網頁URL進行轉換。
- (可選)新增頁首和頁腳,變更頁面大小、方向和顏色。
- 呼叫
PdfDocument.saveAs儲存產生的 PDF 文件
開始
!{--01001100010010010100001001010010010000010101001001011001010111110101001101010100010001010101010 10100010111110101010001010010010010010100000101001100010111110100001001001100010011111010000100100110001001111010101
安裝適用於 Node.js 的 IronPDF 庫
在您選擇的 Node 專案中執行以下 NPM 指令,安裝 IronPDF Node.js 套件:
npm install @ironsoftware/ironpdfnpm install @ironsoftware/ironpdf您也可以手動下載並安裝 IronPDF 軟體包。
手動安裝 IronPDF 引擎(選購)
目前,Node.js 版 IronPDF 需要IronPDF Engine 二進位才能正常運作。
透過安裝適合您作業系統的軟體包來安裝 IronPDF Engine 二進位檔案:
安裝 IronPDF 引擎是可選的,因為@ironpdf會在首次運行時自動從 NPM 下載並安裝適用於您的瀏覽器和作業系統的正確二進位。 然而,在網路存取受限、減少或不希望存取網路的情況下,明確安裝此二進位檔案至關重要。
應用許可證密鑰(可選)
預設情況下,IronPDF 會為其產生或修改的所有文件新增帶有標題的背景浮水印。
請造訪 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}";您可以從我們的授權頁面購買許可證金鑰,或聯絡我們以取得免費試用許可證金鑰。
{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
// ...將 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");如上所示,我們呼叫PdfDocument.fromHtml方法,傳入一個包含一級標題元素標記代碼的文字字串。
PdfDocument.fromHtml傳回一個 Promise,該 Promise 解析為PdfDocument類別的一個實例。 PdfDocument表示庫根據某些來源內容產生的 PDF 檔案。 這個類別構成了 IronPDF 大多數核心功能的基礎,推動了重要的 PDF 建立和編輯用例。
最後,我們使用PdfDocument的saveAs方法將檔案儲存到磁碟。 儲存的PDF文件如下所示。
The PDF generated from the HTML string "<h1>Hello from IronPDF!</h1>". PdfDocument.fromHtml產生的 PDF 檔案與網頁內容的顯示效果完全相同。
從 HTML 文件建立 PDF 文件
PdfDocument.fromHtml不僅適用於 HTML 字串。 該方法也接受本機 HTML 文件的路徑。
在下一個範例中,我們將使用這個範例網頁。
以下是我們在Google瀏覽器中顯示的範例HTML頁面。 從文件範例網站下載此頁面及類似頁面: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");我們已將產生的 PDF 文件內容列在下方。 請注意,IronPDF 不僅保留了原始 HTML 文件的外觀,還保留了連結、表單和其他常用互動元素的功能。
此PDF文件由之前的程式碼範例產生。 將它的外觀與上一張圖片進行比較,你會發現它們驚人地相似!
如果您查看過範例頁面的原始程式碼,您會發現它更加複雜。 它使用了更多類型的 HTML 元素(段落、無序列表、換行符、水平線、超連結、圖像等),並且還包含一些腳本(用於設定 cookie)。
IronPDF能夠渲染比我們目前使用的要複雜得多的網頁內容。 為了說明這一點,讓我們來看看下面這一頁:
一篇有關 Puppeteer 的文章,Puppeteer 是一個 Node 函式庫,因其能使用無頭瀏覽器實體以程式化方式控制 Chrome 而廣受歡迎。
上圖所示頁面是一篇關於 Puppeteer 節點庫的文章。 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");
});下圖顯示了上述程式碼片段的運行結果。
如果在Google瀏覽器中顯示效果好,那麼轉換成 PDF 格式後效果也會很好。 這包括大量使用 CSS 和 JavaScript 的頁面設計。
從 URL 建立 PDF 文件
IronPDF 可以轉換任何大小和複雜度的 HTML 字串和 HTML 檔案。 但是,您並不局限於使用字串和文件中的原始標記。 IronPDF也可以從URL請求HTML。
請參閱位於https://en.wikipedia.org/wiki/PDF 的維基百科文章。
維基百科上關於 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");上面,我們使用PdfDocument.fromUrl將網頁轉換為 PDF,只需幾行程式碼即可完成。 IronPDF 會自動抓取網址的 HTML 程式碼並無縫渲染。 無需HTML檔案或文字字串!
 透過對維基百科文章呼叫PdfDocument.fromUrl產生的 PDF 檔案。 請注意它與原始網頁的相似之處。
從 ZIP 壓縮包建立 PDF 文件
使用PdfDocument.fromZip將位於壓縮 (zip) 檔案中的特定 HTML 檔案轉換為 PDF。
例如,假設我們在專案目錄中有一個 Zip 文件,其內部結構如下:
html-zip.zip
├─ index.html
├─ style.css
├─ logo.pngindex.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>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 展示的是我們的產品標誌:
假設的 HTML zip 檔案中的範例圖像。
當呼叫fromZip方法時,在第一個參數中指定 zip 檔案的有效路徑,以及一個 JSON 對象,該對象將mainHtmlFile屬性設定為我們要轉換的 zip 檔案中的 HTML 檔案的名稱。
我們以同樣的方式轉換壓縮資料夾內的 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");
}); 使用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();本節將簡要介紹需要使用ChromePdfRenderOptions介面的最受歡迎的 HTML 到 PDF 渲染用例。
每個小節都將從預設值開始,並根據需要進行修改以達到目標結果。
自訂 PDF 生成輸出
新增自訂頁首和頁尾
透過textHeader和textFooter屬性,您可以將自訂頁首和/或頁尾內容附加到新渲染的 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");
});原始碼產生以下PDF文件:
 建立了一個 PDF 格式的新頁面,該頁面由 Google 首頁產生。 請注意添加了額外的頁首和頁尾。
為了更好地控制頁首和頁尾的佈局、位置和內容,您還可以使用原始 HTML 而不是文字來定義它們。
在接下來的程式碼區塊中,我們使用 HTML 在頁首和頁尾中加入更豐富的內容。 在頁眉中,我們將頁面網址加粗並居中對齊; 在頁腳中,我們嵌入並居中放置一個徽標。
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");
});下圖顯示了這些變更的結果。
 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");
});在上面的程式碼區塊中,我們配置 IronPDF 以產生我們的 Google 主頁 PDF,採用橫向灰階顯示,並至少留出 50 毫米的邊距空間。 我們還將其設定為適合 A5 紙張尺寸的內容。
從動態網頁產生 PDF 文件
對於包含無法在頁面載入時立即呈現的內容的網頁,可能需要暫停呈現該頁面的內容,直到滿足某些條件。
例如,開發人員可能希望產生一個 PDF 文件,其中包含的內容僅在頁面載入 15 秒後顯示。 在另一種情況下,相同的內容可能只會在執行一些複雜的客戶端程式碼後才會出現。
為了處理這兩種極端情況(以及更多其他情況),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");
});下一個程式碼區塊配置 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");
});從 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"));上述程式碼定義了三個非同步輔助函數:
getTemplateHtml:使用PdfDocument.fromHtml方法將 HTML 範本載入到新的PdfDocument物件中。addTemplateData:使用PdfDocument.replaceText方法將提供的佔位符(稱為鍵)替換為其替換資料值。generatePdf:將PdfDocument儲存到指定的檔案位置。
此外,我們聲明了一個const template變數來保存 HTML 模板檔案的位置。下面顯示了根據上述原始程式碼產生的 PDF 檔案。
 透過將 HTML 範本中定義的佔位符替換為真實數據,建立了新的 PDF 文件。 本文檔保留如無此類替換時我們所期望的 CSS 樣式和佈局。
延伸閱讀
本教學僅觸及了 IronPDF 進階 API 函數功能的冰山一角。 為了增進您的知識和理解,建議您學習以下相關主題。
1.PdfGenerator 類:這是一個專用的實用類,用來從 HTML、URL、Zip 檔案和其他來源媒體建立 PdfDocument 物件。 此類別提供了一個可行的替代方案,可以替代使用PdfDocument類別中定義的 PDF 渲染函數。
2.HttpLoginCredentials:如果您需要從需要特定 cookies 或有密碼保護的網頁產生 PDF,那麼這份參考資料將證明非常有用。
常見問題解答
如何在Node.js中將HTML轉換為PDF而不丟失格式?
在Node.js中,可以使用IronPDF將HTML轉換為PDF而不丟失格式,通過使用PdfDocument.fromHtml等方法,支持精確渲染HTML字符串和文件為PDF格式。
在Node.js中安裝IronPDF需要哪些步驟?
要在Node.js項目中安裝IronPDF,運行命令npm install @Iron Software/ironpdf。這將把IronPDF包添加到項目的依賴項中,使您能夠使用其PDF處理功能。
如何在Node.js中從網頁URL生成PDF?
您可以使用IronPDF中的PdfDocument.fromUrl方法,通過提供網頁的URL將網頁直接轉換為PDF。此方法獲取內容並將其渲染成PDF格式。
自定義IronPDF的PDF輸出有哪些選項?
IronPDF提供了ChromePdfRenderOptions接口,允許自定義PDF輸出。您可以通過此接口調整設置,如頁面大小、方向、邊距,並包含動態內容。
如何使用IronPDF為PDF文檔添加頁眉和頁腳?
要為IronPDF中的PDF添加頁眉和頁腳,使用ChromePdfRenderOptions中的textHeader和textFooter屬性。這允許在每頁的頂部和底部插入自定義文本。
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,包括 RenderHtmlAsPdf, RenderHtmlFileAsPdf, 和 RenderUrlAsPdf 方法,並支援 CSS3, JavaScript, 圖片和外部資產。這一點在 IronPDF 有關 .NET PDF Library 功能的文件中得到了明確的確認。





