IRONSOFTWAREHOME

如何使用 Node.js 列印 PDF 檔案

Curtis Chau
Curtis Chau
Updated: 2026年6月29日

要在 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));
JavaScript

在 Node.js 中列印 PDF 的先決條件有哪些?

using pdf-to-printer 之前,必須安裝 Node.js 14.x 或更新版本以及 npm。 此套件仰賴作業系統原生PRINT指令,而非內建的列印引擎,因此目標機器上必須已設定好印表機驅動程式。

在 Windows 系統上,此套件會透過 PowerShell 呼叫 SumatraPDF。 請確保您的系統政策不會阻擋 PowerShell 腳本的執行。 在 macOS 和 Linux 系統上,此套件會委派給 lp 指令,該指令是 CUPS 列印系統的一部分。 請確認已安裝 CUPS,且至少有一台印表機已註冊 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
SHELL

安裝完成後,請建立一個名為 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);
  }
});
JavaScript

在呼叫 printer.print() 之前檢查檔案是否存在,可避免因路徑錯誤或檔案已被移動而導致的隱性失敗。 若路徑無法解析,fs.access() 呼叫會拋出 ENOENT 錯誤,提供具描述性的錯誤訊息,而非一般的列印排程器拒絕訊息。 常見的錯誤原因包括相對路徑錯誤、缺少印表機驅動程式,以及印表機處於離線狀態。

重要: 該 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');
JavaScript

此模式常見於報表工作流程中,其中 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);
JavaScript

在 print() 之前呼叫 getPrinters() 有兩個目的:一是確認印表機已連線且可存取,二是取得作業系統用於路由列印工作所使用的權威名稱字串。 印表機名稱通常包含版本號或網路後綴,這些與系統設定中顯示的名稱可能有所不同。

提示: 在 Windows 系統上,getPrinters() 會從登錄檔中擷取印表機清單。 在 macOS/Linux 系統上,它會查詢 CUPS。 isDefault 標記用於識別在未指定印表機名稱時接收列印工作的印表機。

可以設定哪些印表機選項?

printer選項s 物件支援以下欄位:

pdf-to-printer option properties
選項型別描述範例值
印表機string與 getPrinters()'HP LaserJet Pro'
副本number需列印的份數2
頁面string頁碼範圍字串'1-3,5'
scalestring頁面縮放模式'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 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 壓縮範例,以減少網路印表機的排程傳輸時間。

提示: 若印表機支援PRINT佇列功能,請在每次列印任務之間加入短暫的 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.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 類別會為每個 PRINT 請求指派一個唯一的作業 ID,並記錄使用者身分、檔案路徑及時間戳記。 將 this.log 儲存至資料庫或僅追加的日誌檔案中,即可將其轉化為持久的稽核紀錄。 對於包含個人識別資訊的文件,建議使用 IronPDF 的 PDF 加密功能,在檔案進入列印佇列前對靜態檔案進行保護。

對於透過 HTTP 接收列印請求的伺服器應用程式,請在列印前驗證檔案型別與大小——若上傳檔案非有效的 PDF 二進位檔,請予以拒絕。 切勿在未進行安全處理的情況下,將使用者提供的檔案路徑直接傳遞給 printer.print()。

重要: 將稽核日誌儲存於應用程式可寫入目錄之外。 (具備檔案系統寫入權限的攻擊者不應能篡改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命令。確認CUPS正在運行,使用lpstat -p。注意scale和orientation選項可能不會在所有CUPS列印驅動上生效。

如何在Node.js中為列印工作新增審計記錄?

將printer.print()包裝在一個類中,通過crypto.randomBytes(8).toString('hex')分配唯一工作ID,並記錄文件路徑、使用者ID和時間戳。將日誌陣列持久化到資料庫或應用程式的可寫目錄外的追加文件中。

How can I handle security and permissions when printing sensitive PDFs?

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.

How does IronPDF support multi-platform PDF generation?

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
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

...
閱讀更多

準備好開始了嗎?

版本:2026.6剛剛發布

立即獲取您的免費30天試用金鑰。
無需信用卡或帳戶建立
Node.js模組下載PDF
使用npm安裝

版本: 2026.6

  1. 下載並安裝Node.js 12+。
  2. 在終端機中執行上述命令。

授權從$999起

Key in blue circle

立即免費取得 30 天試用金鑰。

Your trial license will be sent to your email address

無任何限制。100% 解鎖。無需信用卡。

OR
bullet_checked無需信用卡或建立帳號無任何限制。100% 解鎖。無需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried Iron Suite
預訂您的免費線上演示
Booking Badge

獲得來自全球數百萬工程師的信賴

Iron Software的客戶徽標
獲取您的無義務諮詢
填寫以下表格或發送電子郵件至sales@ironsoftware.com
您的資料將始終保密。
獲得來自全球數百萬工程師的信賴
Iron Software的客戶徽標
立即獲取您的30天試用金鑰。
無需信用卡或帳戶建立
Node.js模組下載PDF
使用npm安裝

版本: 2026.6

  1. 下載並安裝Node.js 12+。
  2. 在終端機中執行上述命令。

授權從$999起