Node.jsを使用してPDFファイルを印刷する方法
Node.jsでPDFファイルを印刷するには、文書をオペレーティングシステムの印刷スプーラーに送信する必要があります。 pdf-to-printer npm パッケージは、そのシステムコールを Windows、macOS、および Linux で動作する Promise ベースの API に抽象化し、単一のメソッド呼び出しで印刷ジョブをキューに入れることを可能にします。 印刷前に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. 成功時は `.then()`、エラー時は `.catch()` を使用して処理してください 5. 特定のプリンターを指定したり、コピー枚数を設定したりするには、`printerオプションs` オブジェクトを 2 番目の引数として渡しますNode.jsでPDFを印刷するための前提条件は何ですか?
pdf-to-printerを使用するには、Node.js 14.x以降およびnpmが必要です。 このパッケージは、バンドルされた印刷エンジンではなくネイティブ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インストール後、印刷ロジック用の index.js ファイルと、印刷したいドキュメントを格納する 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() を呼び出す前にファイルの存在を確認することで、パスが間違っていたりファイルが移動されていたりする場合の、気づかれない失敗を防ぐことができます。 fs.access() 呼び出しは、パスが解決されない場合、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への変換チュートリアルを参照してください。
カスタムプリンターオプションを指定するにはどうすればよいですか?
printerオプションs オブジェクトを printer.print() の 2 番目の引数として渡すことで、特定のプリンターを指定したり、コピー枚数を設定したり、ページ範囲を選択したり、ページの拡大縮小を制御したりできます。 プリンター名は、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 printWithオプションs(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}"`);
}
printWithオプションs('./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 printWithオプションs(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}"`);
}
printWithオプションs('./pdfs/shipping-label.pdf').catch(console.error);getPrinters() を print() の前に呼び出すことには、2つの目的があります。1つはプリンターがオンラインで接続可能であることを確認すること、もう1つはOSが印刷ジョブをルーティングするために使用する正式な名前文字列を取得することです。 プリンター名には、システム設定に表示される表示名とは異なるバージョン番号やネットワーク接尾辞が含まれていることがよくあります。
getPrinters() はレジストリからプリンター一覧を返します。 macOS/Linuxでは、CUPSにクエリを発行します。 isDefault フラグは、プリンター名が指定されていない場合にジョブを受け取るプリンターを識別します。}}]どのようなプリンターオプションを設定できますか?
printerオプションs オブジェクトは、以下のフィールドをサポートしています:
| オプション | タイプ | 翻訳内容 | 例の値 |
|---|---|---|---|
printer | 文字列 | getPrinters()によって返される正確なプリンター名 | 'HP LaserJet Pro' |
コピー | 数値 | 印刷するコピーの数 | 2 |
ページ | 文字列 | ページ範囲文字列 | '1-3,5' |
scale | 文字列 | ページスケーリングモード | 'fit', 'noscale', 'shrink' |
方向性 | 文字列 | ページの向きのオーバーライド | 'portrait', 'landscape' |
PDFの生成時に、印刷時間ではなくカスタム用紙サイズや特定のページの向きを適用する必要がある文書の場合、ファイルを保存する前にIronPDFレンダリングステップでそれらのオプションを設定します。
Node.jsでバッチ印刷を実装するにはどうすればよいですか?
PDF ファイルが格納されたフォルダ、または動的に生成されたリストを処理するには、配列を反復処理し、各ファイルに対して printer.print() を呼び出します。for...of を await と併用することで、ジョブを順次実行でき、同時リクエストによってプリントスプーラーが過負荷になるのを防ぐことができます。
//: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 printオプションs = {
...options,
...(this.printerName && { printer: this.printerName }),
};
await printer.print(filePath, printオプションs);
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 printオプションs = {
...options,
...(this.printerName && { printer: this.printerName }),
};
await printer.print(filePath, printオプションs);
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() 処理中、存在しないファイルはスキップされるため、1つのファイルが欠落しているだけでバッチ全体が中止されることはありません。 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を実行して確認してください; 結果が Restricted の場合、そのセッションでは RemoteSigned または Bypass に設定してください。
Windows上のプリンター名は大文字小文字を区別し、設定 > Bluetooth & デバイス > プリンター & スキャナーに表示される値と正確に一致する必要があります。括弧内のネットワーク接尾辞を含みます。
macOSおよびLinuxでのPDF印刷はどのように機能しますか?
macOSおよびLinuxでは、このパッケージは lp(CUPSの一部)を呼び出します。 lpstat -p を使用して、CUPSが実行されていることを確認してください。これにより、登録されているすべてのプリンターとその現在のステータスが一覧表示されます。 プリンターが表示されない場合、CUPSサービスが開始されていない可能性があります; Linux では sudo systemctl start cups を使用するか、macOS では"システム環境設定">"プリンタ"から有効にしてください。
lp コマンドは、Windows の SumatraPDF パスと同じオプションをすべてサポートしているわけではありません。 scale および orientation オプションは、プリンタドライバによっては、CUPS ベースの印刷には効果がない場合があります。 配備前にターゲットハードウェアでテストします。
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 クラスは、すべての PRINT リクエストに一意のジョブ 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、タイムスタンプを記録します。ログ配列をデータベースまたはアプリケーションの書き込み可能ディレクトリ外の追記専用ファイルに永続化してください。





