Node.jsを使用してPDFファイルを印刷する方法 Copy for LLMsCopy for LLMs Copy page as Markdown for LLMs
# Node.jsを使用してPDFファイルを印刷する方法
Node.jsでPDFファイルを印刷するには、文書をオペレーティングシステムの印刷スプーラーに送信する必要があります。 [`pdf-to-printer`](https://www.npmjs.com/package/pdf-to-printer)npmパッケージはそのシステムコールをPromiseベースのAPIに抽象化し、Windows、macOS、Linuxで機能します。これにより、単一のメソッドコールで印刷ジョブをキューに追加できます。 印刷前にPDFを生成する -- HTML、URL、またはテンプレートを印刷可能な文書に変換する -- のには、[IronPDF for Node.js](https://ironpdf.com/nodejs/)との組み合わせが自然です。
*as-heading:2(クイックスタート:Node.jsでPDFファイルを印刷する)*
```javascript
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-print-pdf/quickstart.js
// 1. Install: npm install pdf-to-printer
const printer = require('pdf-to-printer');
// 2. Print the PDF file (returns a Promise)
printer
.print('./invoice.pdf')
.then(() => console.log('Print job queued successfully.'))
.catch((err) => console.error('Print failed:', err));
```
<div class="hsg-featured-snippet">
<h3>最小限のワークフロー(5ステップ)</h3>
1. パッケージのインストール:`npm install pdf-to-printer`
2. モジュールのインポート:`const printer = require('pdf-to-printer');`
3. `printer.print('./path/to/file.pdf')`を呼び出します - Promiseを返します
4. `.catch()`でエラーを処理します
5. `printerオプションs`オブジェクトを第2引数として渡し、特定のプリンターやコピー数を設定します
</div>
## Node.jsでPDFを印刷するための前提条件は何ですか?
Node.js 14.x以降およびnpmが`pdf-to-printer`を使用する前に必要です。 このパッケージは、バンドルされた印刷エンジンではなくネイティブOS印刷コマンドに依存しているため、ターゲットマシン上でプリンタードライバーがすでに設定されている必要があります。
**Windows**では、パッケージが[SumatraPDF](https://www.sumatrapdfreader.org/free-pdf-reader)をPowerShell経由で呼び出します。 システムポリシーによってPowerShellスクリプトの実行がブロックされていないことを確認してください。 **macOSとLinux**では、パッケージは[CUPS印刷システム](https://www.cups.org/)の一部である`lp`コマンドに委譲します。 CUPSがインストールされており、少なくとも1台のプリンターが`lpstat -p`で登録されていることを確認してください。
[[i:(Node.js 18.x LTSは、プロダクションワークロードに推奨されます。 `pdf-to-printer`パッケージはすべてのアクティブなNode.js LTSバージョンをサポートしています。)]]
## Node.jsプロジェクトをPDF印刷のためにセットアップする方法は?
新しいプロジェクトを初期化し、パッケージをインストールし、印刷ロジックを書く前に最小限のディレクトリ構造を作成します。
```shell
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-print-pdf/setup.sh
mkdir pdf-printer
cd pdf-printer
npm init -y
npm install pdf-to-printer
```
インストール後、印刷ロジックのための`pdfs/`フォルダーを作成します。 プリンター設定のための独立した`config.js`により、プリンター名がコアロジックに含まれないようにします。これは、開発と本番でターゲットプリンターが異なるマルチ環境デプロイメントにおいて便利なパターンです。
モジュールはランタイムで解決されるネイティブバインディングを使用しているため、コンパイルステップは必要ありません。 `node_modules/pdf-to-printer/dist/`ディレクトリには、検出されたプラットフォームのための事前構築バイナリが含まれます。
## PDFファイルを基本使用で印刷する方法は?
`printer.print()`に絶対または相対ファイルパスを渡します。 このメソッドは、システムのデフォルトプリンターで文書をキューに登録し、ジョブがスプーラーに受け入れられた時点でプロミスを解決します - 物理的な印刷が完了した時ではありません。
```javascript
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-print-pdf/basic-print.js
const fs = require('fs').promises;
const printer = require('pdf-to-printer');
async function printPDF(filePath) {
// Verify the file exists before sending to printer
await fs.access(filePath);
const stats = await fs.stat(filePath);
if (stats.size === 0) {
throw new Error('PDF file is empty');
}
await printer.print(filePath);
console.log(`Print job queued: ${filePath}`);
}
printPDF('./pdfs/invoice.pdf').catch((err) => {
if (err.code === 'ENOENT') {
console.error('File not found:', err.path);
} else {
console.error('Print error:', err.message);
}
});
```
`printer.print()`を呼び出す前にファイルの存在を確認することで、パスが間違っているか、ファイルが移動されている場合の無言の失敗を防ぎます。 `ENOENT`をスローし、一般的なスポーラー拒否ではなく詳細なエラーを提供します。 一般的なエラーの原因には、不正な相対パス、不足しているプリンタードライバー、プリンターのオフラインステータスが含まれます。
[[n:(プロミスは印刷ジョブがOSスプーラーに受け入れられた時点で解決しますが、文書が印刷された時点ではありません。 監査目的のため、文書がプリンターを離れたと仮定するのではなく、解決時にタイムスタンプを記録します。)]]
### 印刷する前にPDFを生成するにはどうすればよいですか?
ドキュメントがすでにファイルとして存在しない場合、`printer.print()`を呼び出す前に[IronPDF for Node.js](https://ironpdf.com/nodejs/docs/)で生成してください。 IronPDFは、HTML、URL、およびテンプレート文字列を、別のブラウザーインスタンスを必要とせずに、印刷可能なPDFファイルにレンダリングします。
```javascript
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-print-pdf/generate-and-print.js
const { PdfDocument } = require('@ironsoftware/ironpdf');
const printer = require('pdf-to-printer');
async function generateAndPrint(htmlContent, outputPath) {
// Render HTML to a PDF file using IronPDF
const pdf = await PdfDocument.fromHtml(htmlContent);
await pdf.saveAs(outputPath);
// Send the generated file to the default printer
await printer.print(outputPath);
console.log(`Generated and printed: ${outputPath}`);
}
generateAndPrint('<h1>Monthly Report</h1><p>Sales data for May 2026.</p>', './pdfs/report.pdf');
```
このパターンは、PDFコンテンツがデータベースレコードやAPIレスポンスからランタイムで組み立てられる報告ワークフローで一般的です。 IronPDFのレンダリングオプション、CSSサポート、ヘッダー/フッターの挿入を含む完全なウォークスルーについては、[HTMLからPDFへの変換チュートリアル](https://ironpdf.com/nodejs/tutorials/html-to-pdf/)を参照してください。
## カスタムプリンターオプションを指定するにはどうすればよいですか?
特定のプリンターをターゲットにし、コピー数を設定し、ページ範囲を選択し、ページスケーリングを制御するために、第2引数として`printer.print()`に渡します。 プリンター名は`printer.getPrinters()`によって返された正確な値と一致しなければなりません。
```javascript
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-print-pdf/custom-options.js
const printer = require('pdf-to-printer');
async function printWithOptions(filePath) {
// List available printers to find the correct name
const printers = await printer.getPrinters();
printers.forEach((p) => {
console.log(`${p.name} -- default: ${p.isDefault}`);
});
const options = {
printer: 'HP LaserJet Pro', // Exact name from getPrinters()
copies: 2, // Number of copies
pages: '1-3,5', // Pages to print (optional)
scale: 'fit', // 'fit' | 'noscale' | 'shrink'
orientation: 'portrait', // 'portrait' | 'landscape'
};
await printer.print(filePath, options);
console.log(`Printed ${options.copies} copies to "${options.printer}"`);
}
printWithOptions('./pdfs/shipping-label.pdf').catch(console.error);
```
`print()`より先に呼び出すことは2つの目的があります:プリンターがオンラインで到達可能であることを確認し、OSが印刷ジョブをルートするために使用する権威ある名称文字列を提供します。 プリンター名には、システム設定に表示される表示名とは異なるバージョン番号やネットワーク接尾辞が含まれていることがよくあります。
[[t:(Windowsでは、`getPrinters()`がレジストリからプリンターリストを返します。 macOS/Linuxでは、CUPSにクエリを発行します。 `isDefault`フラグはプリンター名が指定されていない場合にジョブを受け取るプリンターを識別します。)]]
### どのようなプリンターオプションを設定できますか?
`printerオプションs`オブジェクトは以下のフィールドをサポートします:
<table class="content__data-table" data-content-table>
<caption>pdf-to-printer option properties</caption>
<thead>
<tr>
<th>オプション</th>
<th>タイプ</th>
<th>翻訳内容</th>
<th>例の値</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>プリンタ</code></td>
<td>string</td>
<td><code>getPrinters()</code>によって返される正確なプリンター名</td>
<td><code>'HP LaserJet Pro'</code></td>
</tr>
<tr>
<td><code>コピー</code></td>
<td>number</td>
<td>印刷するコピーの数</td>
<td><code>2</code></td>
</tr>
<tr>
<td><code>ページ</code></td>
<td>string</td>
<td>ページ範囲文字列</td>
<td><code>'1-3,5'</code></td>
</tr>
<tr>
<td><code>規模</code></td>
<td>string</td>
<td>ページスケーリングモード</td>
<td><code>'fit'</code>, <code>'noscale'</code>, <code>'shrink'</code></td>
</tr>
<tr>
<td><code>方向性</code></td>
<td>string</td>
<td>ページの向きのオーバーライド</td>
<td><code>'portrait'</code>, <code>'landscape'</code></td>
</tr>
</tbody>
</table>
PDFの生成時に、印刷時間ではなく[カスタム用紙サイズ](https://ironpdf.com/nodejs/examples/custom-pdf-paper-size/)や特定の[ページの向き](https://ironpdf.com/nodejs/examples/pdf-page-orientation/)を適用する必要がある文書の場合、ファイルを保存する前にIronPDFレンダリングステップでそれらのオプションを設定します。
## Node.jsでバッチ印刷を実装するにはどうすればよいですか?
PDFファイルのフォルダまたは動的に生成されたリストを処理するには、配列を反復して各ファイルに対して`printer.print()`を呼び出します。 `for...of`を使用すると、ジョブが順番に保持され、印刷スポーラーが同時要求で圧倒されるのを防ぎます。
```javascript
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-print-pdf/batch-print.js
const printer = require('pdf-to-printer');
const fs = require('fs').promises;
const path = require('path');
class BatchPrinter {
constructor(printerName = null) {
this.printerName = printerName;
this.queue = [];
}
async addFiles(filePaths) {
for (const filePath of filePaths) {
try {
await fs.access(filePath);
this.queue.push(filePath);
} catch {
console.warn(`Skipped (not found): ${filePath}`);
}
}
}
async printAll(options = {}) {
const results = { successful: 0, failed: 0, errors: [] };
for (const filePath of this.queue) {
try {
const printOptions = {
...options,
...(this.printerName && { printer: this.printerName }),
};
await printer.print(filePath, printOptions);
results.successful++;
console.log(`Printed: ${path.basename(filePath)}`);
} catch (err) {
results.failed++;
results.errors.push({ file: filePath, error: err.message });
}
}
this.queue = [];
return results;
}
}
// Usage: print monthly reports to a specific printer
(async () => {
const batch = new BatchPrinter('Office Printer A3');
await batch.addFiles([
'./reports/january.pdf',
'./reports/february.pdf',
'./reports/march.pdf',
]);
const results = await batch.printAll({ copies: 1 });
console.log(`Done -- ${results.successful} printed, ${results.failed} failed.`);
})();
```
`BatchPrinter`クラスはバリデーションと実行を分離します。 `addFiles()`中に存在しないファイルはスキップされ、単一の欠落ファイルがバッチ全体を中断させることはありません。 `printAll()`メソッドはファイルごとのエラーを記録し、ロギングや監視サービスに転送できる要約を返します。
動的に生成されたレポートのためには、IronPDFの[HTML文字列からPDFへの変換](https://ironpdf.com/nodejs/examples/using-html-to-create-a-pdf/)とこのパターンを組み合わせて、単一のパイプラインで生成および印刷を行います。[PDF圧縮の例](https://ironpdf.com/nodejs/examples/pdf-compression/)は、大きな印刷バッチを行う前に適用する価値があります。これにより、ネットワークプリンタでのスプーラー転送時間を短縮できます。
[[t:(古いネットワークプリンターが迅速な連続提出を拒否するため、`await`でジョブ間に短い遅延を追加します。 通常、200-500ミリ秒の停止で十分です。)]]
## Node.js PDF印刷のためのプラットフォーム固有の考慮事項は何ですか?
`pdf-to-printer`パッケージは各OSで異なるシステムコマンドを使用します。 基礎となるメカニズムを理解することは、プラットフォーム固有の障害を診断するのに役立ちます。
### WindowsでのPDF印刷はどのように機能しますか?
Windowsでは、`pdf-to-printer`がPowerShellコマンドを通じてSumatraPDFに依存しています。 SumatraPDFはこのパッケージにバンドルされており、別途インストールする必要はありません。 現在の実行ポリシーの下でPowerShellスクリプト実行が許可されている必要があります。 確認するためにPowerShellで`Get-ExecutionPolicy`を実行します; 結果が`Bypass`に設定します。
Windows上のプリンター名は大文字小文字を区別し、**設定 > Bluetooth & デバイス > プリンター & スキャナー**に表示される値と正確に一致する必要があります。括弧内のネットワーク接尾辞を含みます。
### macOSおよびLinuxでのPDF印刷はどのように機能しますか?
macOSとLinuxでは、パッケージが`lp`を呼び出します(CUPSの一部)。 `lpstat -p`でCUPSが実行中であることを確認します。これはすべての登録済みプリンタとその現在のステータスを一覧表示します。 プリンターが表示されない場合、CUPSサービスが開始されていない可能性があります; Linuxで`sudo systemctl start cups`を、macOSでは**システム設定 > プリンター**で有効にします。
`lp`コマンドは、WindowsのSumatraPDFパスと同じオプションのすべてをサポートしているわけではありません。 `orientation`オプションは、プリンタードライバーによってはCUPSベースの印刷で効果がない場合があります。 配備前にターゲットハードウェアでテストします。
[[w: (`pdf-to-printer`パッケージは現在、ローカルおよびネットワークプリンターにのみ印刷します。 Microsoft Universal Printなどのクラウド印刷サービスは、このパッケージではサポートされていません。)]]
## PDF印刷時のセキュリティと権限をどのように処理しますか?
契約書、財務記録、医療フォームなどの機密文書を処理するプロダクション印刷システムは、アクセス制御と監査トレイルが必要です。 何を印刷したか、いつ印刷したかを追跡することは、多くの規制されている業界でのコンプライアンス要件です。
```javascript
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-print-pdf/secure-print.js
const printer = require('pdf-to-printer');
const crypto = require('crypto');
class AuditedPrinter {
constructor() {
this.log = [];
}
async print(filePath, userId, options = {}) {
const jobId = crypto.randomBytes(8).toString('hex');
const entry = { jobId, userId, filePath, options, status: 'pending', startedAt: new Date().toISOString() };
this.log.push(entry);
try {
await printer.print(filePath, options);
entry.status = 'completed';
entry.completedAt = new Date().toISOString();
return { success: true, jobId };
} catch (err) {
entry.status = 'failed';
entry.error = err.message;
throw err;
}
}
getLog(userId = null) {
return userId ? this.log.filter((e) => e.userId === userId) : this.log;
}
}
// Usage
const auditedPrinter = new AuditedPrinter();
(async () => {
await auditedPrinter.print('./contracts/nda-2026.pdf', 'user-42', { copies: 1 });
console.log('Audit log:', auditedPrinter.getLog('user-42'));
})();
```
`AuditedPrinter`クラスはすべての印刷要求にユニークなジョブIDを割り当て、ユーザー識別、ファイルパス、タイムスタンプを記録します。 `this.log`をデータベースまたは追加専用ログファイルに永続させることで、永続的な監査記録に変わります。 個人識別情報を含む文書の場合、[IronPDFのPDF暗号化機能](https://ironpdf.com/nodejs/examples/encryption-and-decryption/)を使用して、プリンターキューに到達する前にファイルを保護することを検討してください。
HTTP経由で印刷要求を受け入れるサーバーアプリケーションの場合、印刷前にファイルの種類とサイズを確認し、正しいPDFバイナリでないものをアップロードします。 ユーザー提供のファイルパスをサニタイズせずに`printer.print()`に直接渡さないでください。
[[n:(監査ログをアプリケーションの書き込み可能ディレクトリの外側に保存します。 ファイルシステムへの書き込みアクセスを持つ攻撃者が、印刷記録を改ざんできてはいけません。)]]
## Node.js PDF印刷の次のステップは何ですか?
このガイドは、基本的な単一ファイル印刷からバッチキュー、カスタムプリンターオプション、プラットフォームの考慮、規制環境のための監査ログまで、`pdf-to-printer`を使用してローカルおよびネットワークプリンターに既存のPDFファイルを印刷することをカバーしました。
このワークフローをPDF生成で拡張するには、[IronPDF for Node.jsの無料トライアルを開始](#trial-license)し、エンドツーエンドのドキュメントパイプラインを構築するためにHTMLからPDFへのチュートリアルに従ってください。ライセンスオプションとボリューム価格については、[IronPDFライセンスページ](#licensing)をご覧ください。
さらに進む準備はできましたか? IronPDF for Node.jsの完全なハウツーコレクションを探索し、[PDFファイルをマージ](https://ironpdf.com/nodejs/how-to/nodejs-merge-pdf/)し、[PDFファイルを圧縮](https://ironpdf.com/nodejs/how-to/nodejs-compress-pdf/)し、[PDFを画像に変換](https://ironpdf.com/nodejs/how-to/nodejs-pdf-to-image/)する方法を学びましょう。
Ask ChatGPT about this page
Ask Gemini about this page
Ask Perplexity about this page
Node.jsでPDFファイルを印刷するには、文書をオペレーティングシステムの印刷スプーラーに送信する必要があります。 pdf-to-printer npmパッケージはそのシステムコールをPromiseベースのAPIに抽象化し、Windows、macOS、Linuxで機能します。これにより、単一のメソッドコールで印刷ジョブをキューに追加できます。 印刷前にPDFを生成する -- HTML、URL、またはテンプレートを印刷可能な文書に変換する -- のには、IronPDF for Node.js との組み合わせが自然です。
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-print-pdf/quickstart.js
// 1. Install: npm install pdf-to-printer
const printer = require( 'pdf-to-printer' );
// 2. Print the PDF file (returns a Promise)
printer
.print( './invoice.pdf' )
.then(() => console.log( 'Print job queued successfully.' ))
.catch((err) => console.error( 'Print failed:' , err));
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-print-pdf/quickstart.js
// 1. Install: npm install pdf-to-printer
const printer = require('pdf-to-printer');
// 2. Print the PDF file (returns a Promise)
printer
.print('./invoice.pdf')
.then(() => console.log('Print job queued successfully.'))
.catch((err) => console.error('Print failed:', err));
JavaScript
最小限のワークフロー(5ステップ)
パッケージのインストール:npm install pdf-to-printer
モジュールのインポート:const printer = require('pdf-to-printer');
printer.print('./path/to/file.pdf')を呼び出します - Promiseを返します
.catch()でエラーを処理します
printerオプションsオブジェクトを第2引数として渡し、特定のプリンターやコピー数を設定します
Node.jsでPDFを印刷するための前提条件は何ですか?
Node.js 14.x以降およびnpmがpdf-to-printerを使用する前に必要です。 このパッケージは、バンドルされた印刷エンジンではなくネイティブOS印刷コマンドに依存しているため、ターゲットマシン上でプリンタードライバーがすでに設定されている必要があります。
Windows では、パッケージがSumatraPDF をPowerShell経由で呼び出します。 システムポリシーによってPowerShellスクリプトの実行がブロックされていないことを確認してください。 macOSとLinux では、パッケージはCUPS印刷システム の一部であるlpコマンドに委譲します。 CUPSがインストールされており、少なくとも1台のプリンターがlpstat -pで登録されていることを確認してください。
Node.js 18.x LTSは、プロダクションワークロードに推奨されます。 pdf-to-printerパッケージはすべてのアクティブなNode.js LTSバージョンをサポートしています。
Node.jsプロジェクトをPDF印刷のためにセットアップする方法は?
新しいプロジェクトを初期化し、パッケージをインストールし、印刷ロジックを書く前に最小限のディレクトリ構造を作成します。
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-print-pdf/setup.sh
mkdir pdf-printer
cd pdf-printer
npm init -y
npm install pdf-to-printer
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-print-pdf/setup.sh
mkdir pdf-printer
cd pdf-printer
npm init -y
npm install pdf-to-printer
SHELL
インストール後、印刷ロジックのためのpdfs/フォルダーを作成します。 プリンター設定のための独立したconfig.jsにより、プリンター名がコアロジックに含まれないようにします。これは、開発と本番でターゲットプリンターが異なるマルチ環境デプロイメントにおいて便利なパターンです。
モジュールはランタイムで解決されるネイティブバインディングを使用しているため、コンパイルステップは必要ありません。 node_modules/pdf-to-printer/dist/ディレクトリには、検出されたプラットフォームのための事前構築バイナリが含まれます。
PDFファイルを基本使用で印刷する方法は?
printer.print()に絶対または相対ファイルパスを渡します。 このメソッドは、システムのデフォルトプリンターで文書をキューに登録し、ジョブがスプーラーに受け入れられた時点でプロミスを解決します - 物理的な印刷が完了した時ではありません。
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-print-pdf/basic-print.js
const fs = require( 'fs' ).promises;
const printer = require( 'pdf-to-printer' );
async function printPDF(filePath) {
// Verify the file exists before sending to printer
await fs.access(filePath);
const stats = await fs.stat(filePath);
if (stats.size === 0 ) {
throw new Error ( 'PDF file is empty' );
}
await printer.print(filePath);
console.log( `Print job queued: ${ filePath } ` );
}
printPDF( './pdfs/invoice.pdf' ).catch((err) => {
if (err.code === 'ENOENT' ) {
console.error( 'File not found:' , err.path);
} else {
console.error( 'Print error:' , err.message);
}
});
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-print-pdf/basic-print.js
const fs = require('fs').promises;
const printer = require('pdf-to-printer');
async function printPDF(filePath) {
// Verify the file exists before sending to printer
await fs.access(filePath);
const stats = await fs.stat(filePath);
if (stats.size === 0) {
throw new Error('PDF file is empty');
}
await printer.print(filePath);
console.log(`Print job queued: ${filePath}`);
}
printPDF('./pdfs/invoice.pdf').catch((err) => {
if (err.code === 'ENOENT') {
console.error('File not found:', err.path);
} else {
console.error('Print error:', err.message);
}
});
JavaScript
printer.print()を呼び出す前にファイルの存在を確認することで、パスが間違っているか、ファイルが移動されている場合の無言の失敗を防ぎます。 ENOENTをスローし、一般的なスポーラー拒否ではなく詳細なエラーを提供します。 一般的なエラーの原因には、不正な相対パス、不足しているプリンタードライバー、プリンターのオフラインステータスが含まれます。
プロミスは印刷ジョブがOSスプーラーに受け入れられた時点で解決しますが、文書が印刷された時点ではありません。 監査目的のため、文書がプリンターを離れたと仮定するのではなく、解決時にタイムスタンプを記録します。
印刷する前にPDFを生成するにはどうすればよいですか?
ドキュメントがすでにファイルとして存在しない場合、printer.print()を呼び出す前にIronPDF for Node.js で生成してください。 IronPDFは、HTML、URL、およびテンプレート文字列を、別のブラウザーインスタンスを必要とせずに、印刷可能なPDFファイルにレンダリングします。
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-print-pdf/generate-and-print.js
const { PdfDocument } = require( '@ironsoftware/ironpdf' );
const printer = require( 'pdf-to-printer' );
async function generateAndPrint(htmlContent, outputPath) {
// Render HTML to a PDF file using IronPDF
const pdf = await PdfDocument .fromHtml(htmlContent);
await pdf.saveAs(outputPath);
// Send the generated file to the default printer
await printer.print(outputPath);
console.log( `Generated and printed: ${ outputPath } ` );
}
generateAndPrint( '<h1>Monthly Report</h1><p>Sales data for May 2026.</p>' , './pdfs/report.pdf' );
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-print-pdf/generate-and-print.js
const { PdfDocument } = require('@ironsoftware/ironpdf');
const printer = require('pdf-to-printer');
async function generateAndPrint(htmlContent, outputPath) {
// Render HTML to a PDF file using IronPDF
const pdf = await PdfDocument.fromHtml(htmlContent);
await pdf.saveAs(outputPath);
// Send the generated file to the default printer
await printer.print(outputPath);
console.log(`Generated and printed: ${outputPath}`);
}
generateAndPrint('<h1>Monthly Report</h1><p>Sales data for May 2026.</p>', './pdfs/report.pdf');
JavaScript
このパターンは、PDFコンテンツがデータベースレコードやAPIレスポンスからランタイムで組み立てられる報告ワークフローで一般的です。 IronPDFのレンダリングオプション、CSSサポート、ヘッダー/フッターの挿入を含む完全なウォークスルーについては、HTMLからPDFへの変換チュートリアル を参照してください。
カスタムプリンターオプションを指定するにはどうすればよいですか?
特定のプリンターをターゲットにし、コピー数を設定し、ページ範囲を選択し、ページスケーリングを制御するために、第2引数としてprinter.print()に渡します。 プリンター名はprinter.getPrinters()によって返された正確な値と一致しなければなりません。
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-print-pdf/custom-options.js
const printer = require( 'pdf-to-printer' );
async function printWithOptions(filePath) {
// List available printers to find the correct name
const printers = await printer.getPrinters();
printers.forEach((p) => {
console.log( ` ${ p . name } -- default: ${ p . isDefault } ` );
});
const options = {
printer: 'HP LaserJet Pro' , // Exact name from getPrinters()
copies: 2 , // Number of copies
pages: '1-3,5' , // Pages to print (optional)
scale: 'fit' , // 'fit' | 'noscale' | 'shrink'
orientation: 'portrait' , // 'portrait' | 'landscape'
};
await printer.print(filePath, options);
console.log( `Printed ${ options . copies } copies to " ${ options . printer } "` );
}
printWithOptions( './pdfs/shipping-label.pdf' ).catch(console.error);
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-print-pdf/custom-options.js
const printer = require('pdf-to-printer');
async function printWithOptions(filePath) {
// List available printers to find the correct name
const printers = await printer.getPrinters();
printers.forEach((p) => {
console.log(`${p.name} -- default: ${p.isDefault}`);
});
const options = {
printer: 'HP LaserJet Pro', // Exact name from getPrinters()
copies: 2, // Number of copies
pages: '1-3,5', // Pages to print (optional)
scale: 'fit', // 'fit' | 'noscale' | 'shrink'
orientation: 'portrait', // 'portrait' | 'landscape'
};
await printer.print(filePath, options);
console.log(`Printed ${options.copies} copies to "${options.printer}"`);
}
printWithOptions('./pdfs/shipping-label.pdf').catch(console.error);
JavaScript
print()より先に呼び出すことは2つの目的があります:プリンターがオンラインで到達可能であることを確認し、OSが印刷ジョブをルートするために使用する権威ある名称文字列を提供します。 プリンター名には、システム設定に表示される表示名とは異なるバージョン番号やネットワーク接尾辞が含まれていることがよくあります。
Windowsでは、getPrinters()がレジストリからプリンターリストを返します。 macOS/Linuxでは、CUPSにクエリを発行します。 isDefaultフラグはプリンター名が指定されていない場合にジョブを受け取るプリンターを識別します。
どのようなプリンターオプションを設定できますか?
printerオプションsオブジェクトは以下のフィールドをサポートします:
PDFの生成時に、印刷時間ではなくカスタム用紙サイズ や特定のページの向き を適用する必要がある文書の場合、ファイルを保存する前にIronPDFレンダリングステップでそれらのオプションを設定します。
Node.jsでバッチ印刷を実装するにはどうすればよいですか?
PDFファイルのフォルダまたは動的に生成されたリストを処理するには、配列を反復して各ファイルに対してprinter.print()を呼び出します。 for...ofを使用すると、ジョブが順番に保持され、印刷スポーラーが同時要求で圧倒されるのを防ぎます。
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-print-pdf/batch-print.js
const printer = require( 'pdf-to-printer' );
const fs = require( 'fs' ).promises;
const path = require( 'path' );
class BatchPrinter {
constructor (printerName = null ) {
this.printerName = printerName;
this.queue = [];
}
async addFiles(filePaths) {
for ( const filePath of filePaths) {
try {
await fs.access(filePath);
this.queue.push(filePath);
} catch {
console.warn( `Skipped (not found): ${ filePath } ` );
}
}
}
async printAll(options = {}) {
const results = { successful: 0 , failed: 0 , errors: [] };
for ( const filePath of this.queue) {
try {
const printOptions = {
...options,
...(this.printerName && { printer: this.printerName }),
};
await printer.print(filePath, printOptions);
results.successful++;
console.log( `Printed: ${ path . basename(filePath) } ` );
} catch (err) {
results.failed++;
results.errors.push({ file: filePath, error: err.message });
}
}
this.queue = [];
return results;
}
}
// Usage: print monthly reports to a specific printer
( async () => {
const batch = new BatchPrinter ( 'Office Printer A3' );
await batch.addFiles([
'./reports/january.pdf' ,
'./reports/february.pdf' ,
'./reports/march.pdf' ,
]);
const results = await batch.printAll({ copies: 1 });
console.log( `Done -- ${ results . successful } printed, ${ results . failed } failed.` );
})();
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-print-pdf/batch-print.js
const printer = require('pdf-to-printer');
const fs = require('fs').promises;
const path = require('path');
class BatchPrinter {
constructor(printerName = null) {
this.printerName = printerName;
this.queue = [];
}
async addFiles(filePaths) {
for (const filePath of filePaths) {
try {
await fs.access(filePath);
this.queue.push(filePath);
} catch {
console.warn(`Skipped (not found): ${filePath}`);
}
}
}
async printAll(options = {}) {
const results = { successful: 0, failed: 0, errors: [] };
for (const filePath of this.queue) {
try {
const printOptions = {
...options,
...(this.printerName && { printer: this.printerName }),
};
await printer.print(filePath, printOptions);
results.successful++;
console.log(`Printed: ${path.basename(filePath)}`);
} catch (err) {
results.failed++;
results.errors.push({ file: filePath, error: err.message });
}
}
this.queue = [];
return results;
}
}
// Usage: print monthly reports to a specific printer
(async () => {
const batch = new BatchPrinter('Office Printer A3');
await batch.addFiles([
'./reports/january.pdf',
'./reports/february.pdf',
'./reports/march.pdf',
]);
const results = await batch.printAll({ copies: 1 });
console.log(`Done -- ${results.successful} printed, ${results.failed} failed.`);
})();
JavaScript
BatchPrinterクラスはバリデーションと実行を分離します。 addFiles()中に存在しないファイルはスキップされ、単一の欠落ファイルがバッチ全体を中断させることはありません。 printAll()メソッドはファイルごとのエラーを記録し、ロギングや監視サービスに転送できる要約を返します。
動的に生成されたレポートのためには、IronPDFのHTML文字列からPDFへの変換 とこのパターンを組み合わせて、単一のパイプラインで生成および印刷を行います。PDF圧縮の例 は、大きな印刷バッチを行う前に適用する価値があります。これにより、ネットワークプリンタでのスプーラー転送時間を短縮できます。
古いネットワークプリンターが迅速な連続提出を拒否するため、awaitでジョブ間に短い遅延を追加します。 通常、200-500ミリ秒の停止で十分です。
Node.js PDF印刷のためのプラットフォーム固有の考慮事項は何ですか?
pdf-to-printerパッケージは各OSで異なるシステムコマンドを使用します。 基礎となるメカニズムを理解することは、プラットフォーム固有の障害を診断するのに役立ちます。
WindowsでのPDF印刷はどのように機能しますか?
Windowsでは、pdf-to-printerがPowerShellコマンドを通じてSumatraPDFに依存しています。 SumatraPDFはこのパッケージにバンドルされており、別途インストールする必要はありません。 現在の実行ポリシーの下でPowerShellスクリプト実行が許可されている必要があります。 確認するためにPowerShellでGet-ExecutionPolicyを実行します; 結果がBypassに設定します。
Windows上のプリンター名は大文字小文字を区別し、設定 > Bluetooth & デバイス > プリンター & スキャナー に表示される値と正確に一致する必要があります。括弧内のネットワーク接尾辞を含みます。
macOSおよびLinuxでのPDF印刷はどのように機能しますか?
macOSとLinuxでは、パッケージがlpを呼び出します(CUPSの一部)。 lpstat -pでCUPSが実行中であることを確認します。これはすべての登録済みプリンタとその現在のステータスを一覧表示します。 プリンターが表示されない場合、CUPSサービスが開始されていない可能性があります; Linuxでsudo systemctl start cupsを、macOSではシステム設定 > プリンター で有効にします。
lpコマンドは、WindowsのSumatraPDFパスと同じオプションのすべてをサポートしているわけではありません。 orientationオプションは、プリンタードライバーによってはCUPSベースの印刷で効果がない場合があります。 配備前にターゲットハードウェアでテストします。
[[w: (pdf-to-printerパッケージは現在、ローカルおよびネットワークプリンターにのみ印刷します。 Microsoft Universal Printなどのクラウド印刷サービスは、このパッケージではサポートされていません。)]]
PDF印刷時のセキュリティと権限をどのように処理しますか?
契約書、財務記録、医療フォームなどの機密文書を処理するプロダクション印刷システムは、アクセス制御と監査トレイルが必要です。 何を印刷したか、いつ印刷したかを追跡することは、多くの規制されている業界でのコンプライアンス要件です。
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-print-pdf/secure-print.js
const printer = require( 'pdf-to-printer' );
const crypto = require( 'crypto' );
class AuditedPrinter {
constructor () {
this.log = [];
}
async print(filePath, userId, options = {}) {
const jobId = crypto.randomBytes( 8 ).toString( 'hex' );
const entry = { jobId, userId, filePath, options, status: 'pending' , startedAt: new Date ().toISOString() };
this.log.push(entry);
try {
await printer.print(filePath, options);
entry.status = 'completed' ;
entry.completedAt = new Date ().toISOString();
return { success: true , jobId };
} catch (err) {
entry.status = 'failed' ;
entry.error = err.message;
throw err;
}
}
getLog(userId = null ) {
return userId ? this.log.filter((e) => e.userId === userId) : this.log;
}
}
// Usage
const auditedPrinter = new AuditedPrinter ();
( async () => {
await auditedPrinter.print( './contracts/nda-2026.pdf' , 'user-42' , { copies: 1 });
console.log( 'Audit log:' , auditedPrinter.getLog( 'user-42' ));
})();
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-print-pdf/secure-print.js
const printer = require('pdf-to-printer');
const crypto = require('crypto');
class AuditedPrinter {
constructor() {
this.log = [];
}
async print(filePath, userId, options = {}) {
const jobId = crypto.randomBytes(8).toString('hex');
const entry = { jobId, userId, filePath, options, status: 'pending', startedAt: new Date().toISOString() };
this.log.push(entry);
try {
await printer.print(filePath, options);
entry.status = 'completed';
entry.completedAt = new Date().toISOString();
return { success: true, jobId };
} catch (err) {
entry.status = 'failed';
entry.error = err.message;
throw err;
}
}
getLog(userId = null) {
return userId ? this.log.filter((e) => e.userId === userId) : this.log;
}
}
// Usage
const auditedPrinter = new AuditedPrinter();
(async () => {
await auditedPrinter.print('./contracts/nda-2026.pdf', 'user-42', { copies: 1 });
console.log('Audit log:', auditedPrinter.getLog('user-42'));
})();
JavaScript
AuditedPrinterクラスはすべての印刷要求にユニークなジョブIDを割り当て、ユーザー識別、ファイルパス、タイムスタンプを記録します。 this.logをデータベースまたは追加専用ログファイルに永続させることで、永続的な監査記録に変わります。 個人識別情報を含む文書の場合、IronPDFのPDF暗号化機能 を使用して、プリンターキューに到達する前にファイルを保護することを検討してください。
HTTP経由で印刷要求を受け入れるサーバーアプリケーションの場合、印刷前にファイルの種類とサイズを確認し、正しいPDFバイナリでないものをアップロードします。 ユーザー提供のファイルパスをサニタイズせずにprinter.print()に直接渡さないでください。
監査ログをアプリケーションの書き込み可能ディレクトリの外側に保存します。 ファイルシステムへの書き込みアクセスを持つ攻撃者が、印刷記録を改ざんできてはいけません。
Node.js PDF印刷の次のステップは何ですか?
このガイドは、基本的な単一ファイル印刷からバッチキュー、カスタムプリンターオプション、プラットフォームの考慮、規制環境のための監査ログまで、pdf-to-printerを使用してローカルおよびネットワークプリンターに既存のPDFファイルを印刷することをカバーしました。
このワークフローをPDF生成で拡張するには、IronPDF for Node.jsの無料トライアルを開始 し、エンドツーエンドのドキュメントパイプラインを構築するためにHTMLからPDFへのチュートリアルに従ってください。ライセンスオプションとボリューム価格については、IronPDFライセンスページ をご覧ください。
さらに進む準備はできましたか? IronPDF for Node.jsの完全なハウツーコレクションを探索し、PDFファイルをマージ し、PDFファイルを圧縮 し、PDFを画像に変換 する方法を学びましょう。
よくある質問 pdf-to-printer npm パッケージを使用します。これをインストールするには、npm install pdf-to-printer を実行し、その後 printer.print('./file.pdf') を呼び出します。これにより、Promise が返され、システムのデフォルトプリンターでジョブが単一の呼び出しでキューに設定されます。
Node.js 14.x以降、npm、およびホストマシンに設定されたプリンタードライバーが必要です。Windowsでは、PowerShellの実行ポリシーがスクリプトの実行を許可する必要があります。macOSおよびLinuxでは、CUPSがインストールされて実行中であり、少なくとも1つのプリンターがlpstat -p経由で登録されている必要があります。
printer.print()にprinterOptionsオブジェクトを第二引数として渡します。printerフィールドをprinter.getPrinters()で返された正確なプリンター名に設定します。プリンター名は大文字と小文字を区別し、OSのレジストリエントリと正確に一致している必要があります。
はい。最初に IronPDF for Node.js を使用してファイルを生成します。PdfDocument.fromHtml(html) を呼び出してHTMLコンテンツをレンダリングし、pdf.saveAs(path) で保存した後、そのパスを printer.print(path) に渡します。IronPDFは npm install @ironsoftware/ironpdf でインストールします。
はい。macOSとLinuxでは、パッケージはCUPSのlpコマンドに委譲します。lpstat -pでCUPSが実行中であることを確認してください。scaleおよびorientationオプションは、すべてのCUPSプリンタードライバーで有効になるわけではないことに注意してください。
printer.print() をクラスでラップし、crypto.randomBytes(8).toString('hex') を使用して一意のジョブIDを割り当てます。そして、ファイルパス、ユーザーID、タイムスタンプを記録します。ログ配列をデータベースまたはアプリケーションの書き込み可能ディレクトリ外の追記専用ファイルに永続化してください。
For secure printing, use an audit log to track print job details, such as user identity and timestamps. Consider integrating IronPDF's PDF encryption features to protect files before they're sent to the printer.
IronPDF supports PDF generation across Windows, macOS, and Linux platforms, providing functionality such as HTML rendering and template processing to create consistently formatted PDFs that can subsequently be printed using `pdf-to-printer`.
テクニカルライター
Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。
...
詳しく読む