如何使用 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.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 錯誤,提供具描述性的錯誤訊息,而非一般的列印排程器拒絕訊息。 常見的錯誤原因包括相對路徑錯誤、缺少印表機驅動程式,以及印表機處於離線狀態。
[[n:(該 Promise 會在印表工作被作業系統排程器接受時解決,而非文件完成列印時。 (為審計目的,請記錄解析時點的時間戳記,而非假設文件已離開印表機。)]])}]
如何在列印前產生 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 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() 之前呼叫 getPrinters() 有兩個目的:一是確認印表機已連線且可存取,二是取得作業系統用於路由列印工作所使用的權威名稱字串。 印表機名稱通常包含版本號或網路後綴,這些與系統設定中顯示的名稱可能有所不同。
[[t:(在 Windows 系統上,getPrinters() 會從登錄檔中擷取印表機清單。 在 macOS/Linux 系統上,它會查詢 CUPS。 isDefault 標記用於識別在未指定印表機名稱時接收列印工作的印表機。





