Node.jsでHTMLをPDFに変換する

IronPDFの最も強力で最も人気のある機能は、生のHTML、CSS、JavaScriptから高忠実度のPDFを作成できることです。 このチュートリアルでは、Node.js開発者にHTMLコンテンツをPDFに変換するための実践的な方法をすべて案内します。— 1行の文字列変換から動的テンプレート駆動のドキュメント生成まで。

IronPDFは、高レベルのAPIライブラリであり、開発者が強力なPDF処理機能をソフトウェアアプリケーションに迅速に実装するのを支援します。 IronPDFは複数のプログラミング言語で利用可能です。 詳細なカバレッジについては、.NETJavaPythonでPDFを作成する公式ドキュメンテーションページをご覧ください。 このチュートリアルでは、その使用方法をNode.jsプロジェクトに適用する方法を説明しています。

クイックスタート: Node.jsでHTMLをPDFに変換

目次

IronPDF for Node.js を使い始めるにはどうすればよいですか? {#getting-started}

今日あなたのプロジェクトでIronPDFを無料トライアルで使用開始。

最初のステップ:
green arrow pointer

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/ironpdf
SHELL

IronPDFパッケージの手動ダウンロードとインストールも可能です。

IronPDF エンジンをインストールするにはどうすればよいですか?

IronPDF for Node.jsは機能するためにIronPDFエンジンのバイナリを必要とします。

ご注意Install the IronPDF Engine is optional. @ironsoftware/ironpdf パッケージは、初回実行時に、お使いのオペレーティングシステムに適したバイナリを自動的にダウンロードしてインストールします。 インターネットアクセスが制限されている環境や利用できない環境では、明示的なインストールが推奨されます。)}]

適切なオペレーティングシステム用パッケージをインストールしてIronPDFエンジンのバイナリをインストールします。

ライセンスキーの適用方法を教えてください

デフォルトでは、IronPDFは生成または修正されたすべてのドキュメントにウォーターマークを表示します。 透かしを削除するには、グローバルオブジェクト IronPdfGlobalConfiglicenseKey プロパティに有効なライセンスキーを設定してください:

//: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

無料トライアルライセンスキーを取得するかライセンスキーを購入してライセンスページから入手してください。

ご注意ライセンスキーを設定し、他のglobal configuration settingsを他のライブラリ機能を呼び出す前に設定します。 これにより、アプリケーション全体で最適なパフォーマンスと正しい動作が保証されます。)}]

このチュートリアルの残りのコード例では、ライセンスキーが別の 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ドキュメントを生成してください。

Node.jsでHTMLをPDFに変換するにはどうすればよいですか? {#convert-html-to-pdf}

IronPDF Node.jsライブラリは、HTMLコンテンツからPDFファイルを作成するための4つのアプローチを提供します。

1.HTMLコードの文字列から 2.ローカルのHTMLファイルから

  1. オンラインURLから
  2. 圧縮された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");
JAVASCRIPT

PdfDocument.fromHtml は、PdfDocument クラスのインスタンスに解決される Promise を返します。 インスタンスを取得した後、PDFをディスクに書き込むために、ターゲットファイルのパスを指定して saveAs を呼び出します。 保存された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ファイルは、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");
JAVASCRIPT

PDF変換前のGoogle Chromeで表示されたHTMLページのサンプル Google Chromeに表示されたサンプルHTMLページ。 このページおよび類似のページをファイルサンプルズウェブサイトからダウンロードしてください: https://filesamples.com/samples/code/html/sample2.html

IronPDFは元のHTMLドキュメントの外観を保持し、リンク、フォーム、その他のインタラクティブな要素の機能を維持します。 この忠実度は、段落、リスト、画像、ハイパーリンク、およびクライアント側スクリプトを含む複雑なページにまで及びます。

サンプルHTMLファイルから生成されたPDFドキュメント。元のページレイアウトが忠実に再現されています 上記の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");
});
JAVASCRIPT

豊富なCSSスタイルやJavaScriptでレンダリングされたコンテンツを含む複雑なHTMLページから生成されたPDF Google Chromeで見た目が良ければ、PDFに変換したときも見た目が良くなります。 これには、CSSが多用され、JavaScriptでレンダリングされたページデザインが含まれています。

ヒントページがローカルファイルパスからアセットをソースとしている場合、HTMLファイルの場所に対してすべての参照されたCSSファイル、画像、およびスクリプトが存在することを確認してください。 IronPDFのChromeレンダリングエンジンはこれらのパスをブラウザがするのと同じように解決します。

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

標準準拠のブラウザで表示されるPDF形式に関するWikipediaの記事 標準に準拠したウェブブラウザで表示されるPDFフォーマットに関するウィキペディアの記事

WikipediaのPDF記事ページでPdfDocument.fromUrlを呼び出して生成されたPDFドキュメント ウィキペディアの記事で PdfDocument.fromUrl を呼び出した際に生成された PDF。 元のウェブページによく似ていることに注意してください。

重要URLベースの変換では、対象サーバーがIronPDFを実行しているマシンからアクセス可能である必要があります。 認証、VPN、またはファイアウォールで保護されたページには、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.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ファイル内に含まれる 仮想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");
});
JAVASCRIPT

HTML ZIPアーカイブから生成されたPDF。黒い背景にIronPDFのロゴとスタイルが適用された見出しが表示されています 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();
JAVASCRIPT

必要に応じて返されたオブジェクトのプロパティを変更し、任意の変換メソッドの 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");
});
JAVASCRIPT

Googleのホームページから生成された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");
});
JAVASCRIPT

ページURLを太字で表示するHTMLベースのヘッダーと、IronPDFのロゴを表示するHTMLベースのフッターを持つ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 列挙型には、Letter、および Legal などの標準的な用紙サイズが含まれます。 Landscapeをサポートしています。 これらの設定は、印刷対応ドキュメントの出力寸法を正確に制御することができます。

ヒント印刷ワークフロー用にPDFを生成する際は、必ずマージンを明示的に指定してください。 デフォルトのマージンは、ターゲットプリンターや紙の形式の要件に一致しない場合があります。

動的なウェブページをどのように処理しますか? {#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");
});
JAVASCRIPT

または、特定の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");
});
JAVASCRIPT

WaitForType.HtmlElement 戦略では、標準的な CSS クエリセレクタを使用します。 レンダラーは、maxWaitTime ミリ秒が経過するか、要素が見つかるかのいずれか早い方まで、要素の存在を確認し続けます。

警告過剰に長い待機時間を設定すると、高スループットアプリケーションでのPDF生成時間が大幅に増加する可能性があります。 あなたのユースケースが必要とするコンテンツを確実にキャプチャするために最小限の遅延を使用してください。)}]

HTMLテンプレートからPDFを生成する方法は? {#html-template-to-PDF}

一般的な現実世界の自動化パターンは、データベース、API、またはスプレッドシートからのデータでプレースホルダー値を置換して、共有HTMLテンプレートからバッチのPDFを生成することです。 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

上記のコードは、3つの非同期ヘルパー関数を定義しています:

  • getTemplateHtml: PdfDocument を使用して、HTML ファイルを PdfDocument.fromHtml オブジェクトに読み込みます。
  • addTemplateData: PdfDocument.replaceText を呼び出し、プレースホルダーキーを実際のデータ値に置換します。
  • generatePdf: 完成した PdfDocument を指定されたファイルパスに書き込みます。

replaceText 呼び出しは、メモリ内の PDF 表現に対して直接操作を行うため、ディスクからドキュメントを再読み込みすることなく、複数の置換を連鎖させることができます。 生成されたPDFは、元のテンプレートのCSSスタイル、フォント、およびレイアウトをすべて保持します。

すべてのプレースホルダーが実際のデータに置き換えられた後、請求書テンプレートから生成されたPDFドキュメント 実データでプレースホルダーの値が置換された完成PDF請求書。 元のテンプレートのCSSスタイルとレイアウトが正確に保持されています。

このアプローチはバッチドキュメント生成に適しています。 レコードごとに getTemplateHtml を 1 回呼び出して、出力ファイルごとに新しい PdfDocument を作成し、そのレコードのデータに対して addTemplateData の呼び出しを連鎖させた後、generatePdf を呼び出してください。

次のステップは何ですか? {#next-steps}

このチュートリアルでは、IronPDF for Node.jsで使用頻度の高いレンダリングオプションとHTMLから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オブジェクトのtextHeadertextFooterプロパティを設定します。リッチなレイアウトのためには、生のHTMLフラグメントを使用してhtmlHeaderおよびhtmlFooterを使用します。オプションオブジェクトをあらゆる変換メソッドのrenderOptionsパラメータに渡します。

IronPDF for Node.jsでページサイズと向きを変更するには?

options.paperSizePaperSize列挙型からの値(例:PaperSize.A4またはPaperSize.Letter)に設定し、options.paperOrientationPdfPaperOrientation.PortraitまたはPdfPaperOrientation.Landscapeに設定します。設定済みのオプションを変換メソッドに渡します。

PDFに変換する際に動的なJavaScriptコンテンツを処理するには?

ChromePdfRenderOptionswaitForプロパティを使用します。typeWaitForType.RenderDelayに設定し、ミリ秒単位の遅延を指定するか、typeWaitForType.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を書き込みます。

Darrius Serrant
フルスタックソフトウェアエンジニア(WebOps)

Darrius Serrantは、マイアミ大学でコンピュータサイエンスの学士号を取得し、Iron SoftwareでフルスタックWebOpsマーケティングエンジニアとして働いています。若い頃からコーディングに惹かれ、コンピューティングを神秘的かつアクセス可能なものとし、創造性と問題解決のための完璧な媒体と考えていました。

Iron Softwareでは、新しいものを創造することと、複雑なコンセプトをより理解しやすくすることを楽しんでいます。Resident Developerの一人として、次世代に専門知識を共有するために、学生を教えることにも志願しました。

Darriusにとって、その仕事は価値があり、実際の影響があるため、満足感があります。

準備はできましたか?
バージョン: 2026.5 just released
Still Scrolling Icon

まだスクロールしていますか?

すぐに証拠が欲しいですか?
サンプルを実行するHTML が PDF に変換されるのを確認します。