如何使用 Node.js 列印 PDF 檔案
要在 Node.js 中列印 PDF 檔案,必須將文件傳送至作業系統的列印佇列。 pdf-to-printer npm 套件將該系統呼叫封裝為基於 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. 成功狀況請使用 `.then()`,錯誤狀況請使用 `.catch()` 5. 將 `printer選項s` 物件作為第二個參數傳入,以指定特定印表機或設定複印份數在 Node.js 中列印 PDF 的先決條件有哪些?
using pdf-to-printer 之前,必須安裝 Node.js 14.x 或更新版本以及 npm。 此套件仰賴作業系統原生PRINT指令,而非內建的列印引擎,因此目標機器上必須已設定好印表機驅動程式。
在 Windows 系統上,此套件會透過 PowerShell 呼叫 SumatraPDF。 請確保您的系統政策不會阻擋 PowerShell 腳本的執行。 在 macOS 和 Linux 系統上,此套件會委派給 lp 指令,該指令是 CUPS 列印系統的一部分。 請確認已安裝 CUPS,且至少有一台印表機已註冊 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()。 此方法會將文件排入系統預設印表機的佇列,並在列印工作被列印排程器接受時解決 Promise —— 而非在實際列印完成時。
//: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.co/de === '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.co/de === '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 回應進行彙整。 請參閱 HTML 轉 PDF 教學指南,以了解 IronPDF 渲染選項的完整操作流程,包括 CSS 支援以及頁首/頁尾插入功能。
如何指定自訂印表機選項?
將 printer選項s 物件作為第二個參數傳遞給 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 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.co/pies} 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.co/pies} copies to "${options.printer}"`);
}
printWith選項s('./pdfs/shipping-label.pdf').catch(console.error);在 print() 之前呼叫 getPrinters() 有兩個目的:一是確認印表機已連線且可存取,二是取得作業系統用於路由列印工作所使用的權威名稱字串。 印表機名稱通常包含版本號或網路後綴,這些與系統設定中顯示的名稱可能有所不同。
getPrinters() 會從登錄檔中擷取印表機清單。 在 macOS/Linux 系統上,它會查詢 CUPS。 isDefault 標記用於識別在未指定印表機名稱時接收列印工作的印表機。可以設定哪些印表機選項?
printer選項s 物件支援以下欄位:
| 選項 | 類型 | 描述 | 範例值 |
|---|---|---|---|
印表機 | string | 與 getPrinters() | 'HP LaserJet Pro' |
副本 | number | 需列印的份數 | 2 |
頁面 | string | 頁碼範圍字串 | '1-3,5' |
scale | string | 頁面縮放模式 | 'fit', 'noscale', 'shrink' |
方向 | string | 頁面方向覆寫 | 'portrait', 'landscape' |
若文件需要在生成 PDF 時(而非列印時)套用自訂紙張尺寸或特定頁面方向,請在儲存檔案前,於 IronPDF 的渲染步驟中設定這些選項。
如何在 Node.js 中實作批次列印?
透過遍歷陣列並針對每個檔案呼叫 printer.print(),來處理一整夾層的 PDF 檔案或動態生成的清單。將 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() 處理過程中,若檔案不存在則會跳過,以避免單一檔案缺失導致整個批次處理中止。 printAll() 方法會記錄每份檔案的錯誤,並返回一份摘要,該摘要可記錄於日誌或轉發至監控服務。
針對動態生成的報告,可將此模式與 IronPDF 的 HTML 字串轉 PDF 功能結合,以單一流程完成生成與列印。在處理大量列印批次前,建議套用 PDF 壓縮範例,以減少網路印表機的排程傳輸時間。
await 延遲 -- 部分較舊的網路印表機會拒絕快速連續的提交請求。 通常暫停 200 至 500 毫秒即可。針對 Node.js PDF 列印,有哪些平台特定的考量因素?
pdf-to-printer 套件在各作業系統上會使用不同的系統指令。 理解底層運作機制有助於診斷特定平台的故障。
Windows 上的 PDF 列印功能如何運作?
在 Windows 系統上,pdf-to-printer 會透過 PowerShell 指令呼叫 SumatraPDF。 SumatraPDF 已內建於套件中,無需另行安裝。 在當前的執行政策下,必須允許執行 PowerShell 腳本。 請在 PowerShell 中執行 Get-ExecutionPolicy 進行驗證; 若結果為 Restricted,請將其設定為 RemoteSigned 或 Bypass 以供本次會話使用。
Windows 系統中的印表機名稱區分大小寫,且必須與"設定 > 藍牙與裝置 > 印表機與掃描器"中顯示的值完全一致,包括任何括號內的網路後綴。
PDF 列印在 macOS 和 Linux 上是如何運作的?
在 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.com/pletedAt = 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.com/pletedAt = 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,且透過 lpstat -p 指令至少已註冊一台印表機。
如何在 Node.js 中將文件印至特定印表機?
請將 printerOptions 物件作為第二個參數傳遞給 printer.print()。請將 printer 欄位設定為 printer.getPrinters() 所返回的精確印表機名稱。印表機名稱區分大小寫,且必須與作業系統登錄檔中的條目完全一致。
我可以在同一個 Node.js 腳本中生成 PDF 並直接列印嗎?
是的。請先使用 IronPDF for Node.js 生成檔案:呼叫 PdfDocument.fromHtml(html) 來渲染 HTML 內容,透過 pdf.saveAs(path) 儲存檔案,然後將該路徑傳遞給 printer.print(path)。請使用 npm install @ironsoftware/ironpdf 安裝 IronPDF。
pdf-to-printer 是否支援 macOS 和 Linux 系統?
是的。在 macOS 和 Linux 系統上,此套件會透過 CUPS 調用 lp 指令。請使用 lpstat -p 確認 CUPS 是否正在執行。請注意,縮放比例與方向選項可能無法在所有 CUPS 印表機驅動程式上生效。
如何在 Node.js 中為 PRINT 工作新增稽核日誌?
將 printer.print() 封裝於一個類別中,該類別會使用 crypto.randomBytes(8).toString('hex') 指派一個唯一的作業 ID,並記錄檔案路徑、使用者 ID 以及時間戳記。將日誌陣列儲存至資料庫,或儲存至應用程式可寫入目錄外的只讀檔案中。





