Node.jsを使用してPDFファイルを印刷する方法
Node.jsでPDFファイルを印刷するには、文書をオペレーティングシステムの印刷スプーラーに送信する必要があります。 pdf-to-printernpmパッケージはそのシステムコールをPromiseベースのAPIに抽象化し、Windows、macOS、Linuxで機能します。これにより、単一のメソッドコールで印刷ジョブをキューに追加できます。 印刷前にPDFを生成する -- HTML、URL、またはテンプレートを印刷可能な文書に変換する -- のには、IronPDF for Node.jsとの組み合わせが自然です。
クイックスタート:Node.jsでPDFファイルを印刷する
//: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));最小限のワークフロー(5ステップ)
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引数として渡し、特定のプリンターやコピー数を設定しますNode.jsでPDFを印刷するための前提条件は何ですか?
Node.js 14.x以降およびnpmがpdf-to-printerを使用する前に必要です。 このパッケージは、バンドルされた印刷エンジンではなくネイティブOS印刷コマンドに依存しているため、ターゲットマシン上でプリンタードライバーがすでに設定されている必要があります。
Windowsでは、パッケージがSumatraPDFをPowerShell経由で呼び出します。 システムポリシーによってPowerShellスクリプトの実行がブロックされていないことを確認してください。 macOSとLinuxでは、パッケージはCUPS印刷システムの一部であるlpコマンドに委譲します。 CUPSがインストールされており、少なくとも1台のプリンターがlpstat -pで登録されていることを確認してください。
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インストール後、印刷ロジックのための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);
}
});printer.print()を呼び出す前にファイルの存在を確認することで、パスが間違っているか、ファイルが移動されている場合の無言の失敗を防ぎます。 ENOENTをスローし、一般的なスポーラー拒否ではなく詳細なエラーを提供します。 一般的なエラーの原因には、不正な相対パス、不足しているプリンタードライバー、プリンターのオフラインステータスが含まれます。
印刷する前に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');このパターンは、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);print()より先に呼び出すことは2つの目的があります:プリンターがオンラインで到達可能であることを確認し、OSが印刷ジョブをルートするために使用する権威ある名称文字列を提供します。 プリンター名には、システム設定に表示される表示名とは異なるバージョン番号やネットワーク接尾辞が含まれていることがよくあります。
getPrinters()がレジストリからプリンターリストを返します。 macOS/Linuxでは、CUPSにクエリを発行します。 isDefaultフラグはプリンター名が指定されていない場合にジョブを受け取るプリンターを識別します。どのようなプリンターオプションを設定できますか?
printerオプションsオブジェクトは以下のフィールドをサポートします:
| オプション | タイプ | 翻訳内容 | 例の値 |
|---|---|---|---|
プリンタ | string | getPrinters()によって返される正確なプリンター名 | 'HP LaserJet Pro' |
コピー | number | 印刷するコピーの数 | 2 |
ページ | string | ページ範囲文字列 | '1-3,5' |
規模 | string | ページスケーリングモード | 'fit', 'noscale', 'shrink' |
方向性 | string | ページの向きのオーバーライド | 'portrait', 'landscape' |
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.`);
})();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'));
})();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を画像に変換する方法を学びましょう。
よくある質問
Node.jsでPDFファイルを印刷する最も簡単な方法は何ですか?
pdf-to-printer npm パッケージを使用します。これをインストールするには、npm install pdf-to-printer を実行し、その後 printer.print('./file.pdf') を呼び出します。これにより、Promise が返され、システムのデフォルトプリンターでジョブが単一の呼び出しでキューに設定されます。
Node.jsでPDFを印刷するための前提条件は何ですか?
Node.js 14.x以降、npm、およびホストマシンに設定されたプリンタードライバーが必要です。Windowsでは、PowerShellの実行ポリシーがスクリプトの実行を許可する必要があります。macOSおよびLinuxでは、CUPSがインストールされて実行中であり、少なくとも1つのプリンターがlpstat -p経由で登録されている必要があります。
Node.js で特定のプリンターに印刷するにはどうすればよいですか?
printer.print()にprinterOptionsオブジェクトを第二引数として渡します。printerフィールドをprinter.getPrinters()で返された正確なプリンター名に設定します。プリンター名は大文字と小文字を区別し、OSのレジストリエントリと正確に一致している必要があります。
同じNode.jsスクリプトでPDFを生成してから印刷することはできますか?
はい。最初に IronPDF for Node.js を使用してファイルを生成します。PdfDocument.fromHtml(html) を呼び出してHTMLコンテンツをレンダリングし、pdf.saveAs(path) で保存した後、そのパスを printer.print(path) に渡します。IronPDFは npm install @ironsoftware/ironpdf でインストールします。
pdf-to-printerはmacOSおよびLinuxで動作しますか?
はい。macOSとLinuxでは、パッケージはCUPSのlpコマンドに委譲します。lpstat -pでCUPSが実行中であることを確認してください。scaleおよびorientationオプションは、すべてのCUPSプリンタードライバーで有効になるわけではないことに注意してください。
Node.jsで印刷ジョブの監査ログを追加するにはどうすればよいですか?
printer.print() をクラスでラップし、crypto.randomBytes(8).toString('hex') を使用して一意のジョブIDを割り当てます。そして、ファイルパス、ユーザーID、タイムスタンプを記録します。ログ配列をデータベースまたはアプリケーションの書き込み可能ディレクトリ外の追記専用ファイルに永続化してください。





