IronPDFの最も強力で最も人気のある機能は、生のHTML、CSS、JavaScriptから高忠実度のPDFを作成できることです。 このチュートリアルでは、Node.js開発者にHTMLコンテンツをPDFに変換するための実践的な方法をすべて案内します。— 1行の文字列変換から動的テンプレート駆動のドキュメント生成まで。
IronPDFは、高レベルのAPIライブラリであり、開発者が強力なPDF処理機能をソフトウェアアプリケーションに迅速に実装するのを支援します。 IronPDFは複数のプログラミング言語で利用可能です。 詳細なカバレッジについては、.NET、Java、PythonでPDFを作成する公式ドキュメンテーションページをご覧ください。 このチュートリアルでは、その使用方法をNode.jsプロジェクトに適用する方法を説明しています。
クイックスタート: Node.jsでHTMLをPDFに変換
Node.jsでHTMLをPDFに変換する方法
- NPMを介してIronPDF Node.jsライブラリをインストールします:
npm install @ironsoftware/ironpdf @ironsoftware/ironpdfパッケージからPdfDocumentクラスをインポートしてください。PdfDocument.fromHtml、PdfDocument.fromUrl、またはPdfDocument.fromZipをHTMLソースに応じて呼び出します。- オプションでレンダリングオプションを設定します: ヘッダー、フッター、ページサイズ、向き、余白。
- 生成されたPDFをディスクに保存するために
PdfDocument.saveAsを呼び出します。
目次
- IronPDF for Node.jsの始め方は?
- Node.jsでHTMLをPDFに変換するには?
- IronPDFがサポートする高級レンダリングオプションは?
- HTMLテンプレートからPDFを生成するには?
- 次のステップは何ですか?
IronPDF for Node.js を使い始めるにはどうすればよいですか? {#getting-started}
今日あなたのプロジェクトでIronPDFを無料トライアルで使用開始。
IronPDFライブラリをインストールする
以下のNPMコマンドを選択したNode.jsプロジェクトで実行して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/ironpdfIronPDF エンジンをインストールするにはどうすればよいですか?
IronPDF for Node.jsは機能するためにIronPDFエンジンのバイナリを必要とします。
@ironsoftware/ironpdf パッケージは、初回実行時に、お使いのオペレーティングシステムに適したバイナリを自動的にダウンロードしてインストールします。 インターネットアクセスが制限されている環境や利用できない環境では、明示的なインストールが推奨されます。)}]適切なオペレーティングシステム用パッケージをインストールしてIronPDFエンジンのバイナリをインストールします。
ライセンスキーの適用方法を教えてください
デフォルトでは、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}";無料トライアルライセンスキーを取得するかライセンスキーを購入してライセンスページから入手してください。
このチュートリアルの残りのコード例では、ライセンスキーが別の 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
// ...
ironPdf.com/nodejs/licensing/でライセンスキーを取得し、透かしなしのPDFドキュメントを生成してください。
Node.jsでHTMLをPDFに変換するにはどうすればよいですか? {#convert-html-to-pdf}
IronPDF Node.jsライブラリは、HTMLコンテンツからPDFファイルを作成するための4つのアプローチを提供します。
1.HTMLコードの文字列から 2.ローカルのHTMLファイルから
- オンラインURLから
- 圧縮されたZIPアーカイブから
各アプローチは、PdfDocument クラスを基盤としています。 PdfDocument は、何らかのソースコンテンツから生成された PDF ファイルを表し、IronPDF のコアとなる作成および編集機能の大部分を支えています。
HTML文字列からPDFを作成するには? {#create-pdf-from-html-string}
PdfDocument.fromHtml は、生の HTML マークアップ文字列から PDF を生成します。このアプローチは、テキストファイル、データストリーム、HTML テンプレートエンジン、あるいは動的に構築されたマークアップなど、事実上あらゆる場所から HTML 文字列を取得できるため、4つの方法の中で最も柔軟性が高いと言えます。
//: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");PdfDocument.fromHtml は、PdfDocument クラスのインスタンスに解決される Promise を返します。 インスタンスを取得した後、PDFをディスクに書き込むために、ターゲットファイルのパスを指定して saveAs を呼び出します。 保存されたPDFファイルは、標準に準拠したブラウザが表示するのと正確に同じようにHTMLをレンダリングします。
The PDF generated from the HTML string <h1>Hello from IronPDF!</h1>. PdfDocument.fromHtmlが生成するPDFファイルは、Webページのコンテンツがそのまま表示されるような形式で表示されます。
HTMLファイルからPDFを作成するには? {#create-pdf-from-html-file}
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");//: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");
Google Chromeに表示されたサンプルHTMLページ。 このページおよび類似のページをファイルサンプルズウェブサイトからダウンロードしてください: https://filesamples.com/samples/code/html/sample2.html
IronPDFは元のHTMLドキュメントの外観を保持し、リンク、フォーム、その他のインタラクティブな要素の機能を維持します。 この忠実度は、段落、リスト、画像、ハイパーリンク、およびクライアント側スクリプトを含む複雑なページにまで及びます。
上記のHTMLファイル例から生成されたこのPDF。 前の画像とその外観を比較してください—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");
});//: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");
});
Google Chromeで見た目が良ければ、PDFに変換したときも見た目が良くなります。 これには、CSSが多用され、JavaScriptでレンダリングされたページデザインが含まれています。
URLからPDFを作成するには? {#create-pdf-from-url}
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");//: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");
標準に準拠したウェブブラウザで表示されるPDFフォーマットに関するウィキペディアの記事。
ウィキペディアの記事で PdfDocument.fromUrl を呼び出した際に生成された PDF。 元のウェブページによく似ていることに注意してください。
ChromePdfRenderOptions による追加の設定が必要になる場合があります。)}]ZipアーカイブからPDFを作成するには? {#create-pdf-from-zip}
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.pngindex.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>また、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ファイル内のサンプル画像。
fromZip を呼び出す際は、最初の引数として ZIP ファイルへのパスを、2 番目の引数として構成オブジェクトを指定してください。 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");
});
PdfDocument.fromZip を使用した PDF/A 作成。 この関数は、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();必要に応じて返されたオブジェクトのプロパティを変更し、任意の変換メソッドの renderOptions パラメータに渡してください。
ヘッダーとフッターを追加するにはどうすればよいですか? {#add-headers-footers}
textHeader および 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");
});//: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");
});
Googleのホームページから生成されたPDFで、textFooterを使用してカスタムテキストのヘッダーとフッターが適用されています。
より複雑なヘッダーおよびフッターのレイアウトを作成する場合は、代わりに htmlHeader および htmlFooter プロパティを使用してください。 これらは生のHTMLフラグメントを受け取り、タイポグラフィ、画像、配置に完全な制御を与えます。 以下の例では、ヘッダーにページURLを太字で中央に、フッターにロゴ画像を埋め込みます。
//: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");
});
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");
});PaperSize 列挙型には、Letter、および Legal などの標準的な用紙サイズが含まれます。 Landscapeをサポートしています。 これらの設定は、印刷対応ドキュメントの出力寸法を正確に制御することができます。
動的なウェブページをどのように処理しますか? {#dynamic-web-pages}
JavaScriptのタイマー、遅延読み込み、API呼び出しを介して非同期でコンテンツをロードするページは、IronPDFのエンジンがそれらをキャプチャする頃には完全にレンダリングされていない可能性があります。 WaitFor プロパティを介して waitFor に設定される 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");
});//: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");
});または、特定のDOM要素が表示されるまで待機するようにIronPDFを構成してください。 これは、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");
});WaitForType.HtmlElement 戦略では、標準的な CSS クエリセレクタを使用します。 レンダラーは、maxWaitTime ミリ秒が経過するか、要素が見つかるかのいずれか早い方まで、要素の存在を確認し続けます。
HTMLテンプレートからPDFを生成する方法は? {#html-template-to-PDF}
一般的な現実世界の自動化パターンは、データベース、API、またはスプレッドシートからのデータでプレースホルダー値を置換して、共有HTMLテンプレートからバッチのPDFを生成することです。 IronPDFのPdfDocument上でこれを直接処理します。
以下の請求書テンプレート例(一般公開されている CodePen の請求書テンプレートを改変したもの)では、置換可能なコンテンツに対して {INVOICE-NUMBER} といった中括弧のプレースホルダーが使用されています:
プレースホルダータグを含むサンプル請求書テンプレート。 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"));上記のコードは、3つの非同期ヘルパー関数を定義しています:
getTemplateHtml:PdfDocumentを使用して、HTML ファイルをPdfDocument.fromHtmlオブジェクトに読み込みます。addTemplateData:PdfDocument.replaceTextを呼び出し、プレースホルダーキーを実際のデータ値に置換します。generatePdf: 完成したPdfDocumentを指定されたファイルパスに書き込みます。
各 replaceText 呼び出しは、メモリ内の PDF 表現に対して直接操作を行うため、ディスクからドキュメントを再読み込みすることなく、複数の置換を連鎖させることができます。 生成されたPDFは、元のテンプレートのCSSスタイル、フォント、およびレイアウトをすべて保持します。
実データでプレースホルダーの値が置換された完成PDF請求書。 元のテンプレートのCSSスタイルとレイアウトが正確に保持されています。
このアプローチはバッチドキュメント生成に適しています。 レコードごとに getTemplateHtml を 1 回呼び出して、出力ファイルごとに新しい PdfDocument を作成し、そのレコードのデータに対して addTemplateData の呼び出しを連鎖させた後、generatePdf を呼び出してください。
次のステップは何ですか? {#next-steps}
このチュートリアルでは、IronPDF for Node.jsで使用頻度の高いレンダリングオプションとHTMLからPDFへの変換の主要な方法について説明します。 以下のトピックは、ここで学んだことをより専門的な領域に拡張します。
- Node.jsでのPDF編集とスタンピング — 既存のPDFドキュメントにプログラムによってスタンプ、注釈、テキスト編集を適用します。
- Node.jsでのPDFのマージと分割 — 複数のPDFを1つのドキュメントに結合する、または1つのPDFを個別のページに分割する。
- Node.jsでのPDFへのウォーターマークの追加 — 各ページにテキストまたは画像のウォーターマークを正確な位置制御とともに追加します。
- IronPDF for Node.js API リファレンス —
AffixFonts、およびその他のすべてのエクスポートされたクラスとインターフェースの完全な API を参照してください。 - 無料トライアルライセンスキーを取得する —無料30日間のトライアルライセンスをアクティブにすると、ウォーターマークなしでプロダクション品質のPDFを生成できます。
よくある質問
Node.jsでHTMLをPDFに変換するには?
IronPDFライブラリを使用します。npm install @ironsoftware/ironpdfでインストールし、次にPdfDocument.fromHtmlをHTML文字列またはファイルパスで呼び出し、またはPdfDocument.fromUrlをWebアドレスで呼び出します。結果をPdfDocument.saveAsで保存します。
Node.jsでHTML文字列をPDFに変換するには?
HTML文字列を引数としてPdfDocument.fromHtmlを呼び出します。このメソッドはPdfDocumentインスタンスに解決されるPromiseを返します。PDFをディスクに書き込むためにsaveAsを結果にチェーンします。
Node.jsでローカルHTMLファイルをPDFに変換するには?
HTML文字列の代わりに有効なファイルシステムパスをPdfDocument.fromHtmlに渡します。IronPDFは、CSS、画像、スクリプトの相対パスをブラウザがファイルをロードする場合と同じ方法で解決します。
Node.jsでURLをPDFに変換するには?
ターゲットURLでPdfDocument.fromUrlを呼び出します。IronPDFは、Chromeレンダリングエンジンを使用してページを取得し、ピクセルパーフェクトなPDFを生成します。ターゲットURLはIronPDFを実行しているホストから公にアクセス可能でなければなりません。
Node.jsでPDFにヘッダーとフッターを追加するには?
シンプルなテキストヘッダーとフッターのためにChromePdfRenderOptionsオブジェクトのtextHeaderとtextFooterプロパティを設定します。リッチなレイアウトのためには、生のHTMLフラグメントを使用してhtmlHeaderおよびhtmlFooterを使用します。オプションオブジェクトをあらゆる変換メソッドのrenderOptionsパラメータに渡します。
IronPDF for Node.jsでページサイズと向きを変更するには?
options.paperSizeをPaperSize列挙型からの値(例:PaperSize.A4またはPaperSize.Letter)に設定し、options.paperOrientationをPdfPaperOrientation.PortraitまたはPdfPaperOrientation.Landscapeに設定します。設定済みのオプションを変換メソッドに渡します。
PDFに変換する際に動的なJavaScriptコンテンツを処理するには?
ChromePdfRenderOptionsのwaitForプロパティを使用します。typeをWaitForType.RenderDelayに設定し、ミリ秒単位の遅延を指定するか、typeをWaitForType.HtmlElementに設定し、CSSクエリセレクターを提供します。IronPDFは、条件が満たされるまでレンダリングを一時停止します。
ZIPアーカイブ内のHTMLファイルをPDFに変換するには?
PdfDocument.fromZipをZIPファイルへのパスを第1引数として呼び出し、オプションオブジェクトを第2引数とします。mainHtmlFileプロパティをアーカイブ内で変換すべきHTMLファイルの名前に設定します。
生成されたPDFからIronPDFの透かしを削除するには?
変換メソッドを呼び出す前に、グローバル設定に有効なライセンスキーを適用します。IronPdfGlobalConfig.getConfig()で設定オブジェクトを取得し、config.licenseKeyをキーに設定します。無料トライアルライセンスはironpdf.comで入手できます。
Node.jsでHTMLテンプレートからPDFを生成するには?
PdfDocument.fromHtmlでテンプレートをロードし、次にPdfDocument.replaceTextをテンプレート内の各プレースホルダーに対して呼び出し、プレースホルダー文字列とその置換値を渡します。すべての置換が完了したら、saveAsを呼び出して最終的なPDFを書き込みます。





