IRONSOFTWAREHOME
圖片轉 PDF
import {PdfGenerator} from "@ironsoftware/ironpdf";
import fs from 'fs';

(async () => {
    // Specify the directory path
    const directoryPath = './images';

    // Read the contents of the directory
    fs.readdir(directoryPath, (err, files) => {
    if (err) {
        console.error('Error reading directory:', err);
        return;
    }

    // Filter file names to include only .jpg and .jpeg extensions
    const jpegFiles = files.filter((file) =>
        file.toLowerCase().endsWith('.jpg') || file.toLowerCase().endsWith('.jpeg')
    );

    // Construct full file paths for the filtered files
    const filePaths = jpegFiles.map((file) => `${directoryPath}/${file}`);

    // Converts the images to a PDF and save it.
    const pdf = PdfGenerator.imageToPdf(filePaths).then(
        (returnedPdf)=> {
            returnedPdf.saveAs("composite.pdf");
        });
    
    // Also see PdfDocument.rasterizeToImageFiles() method to flatten a PDF to images or thumbnails
    });
})();
npm i @ironsoftware/ironpdf
圖片轉 PDF

圖片轉 PDF

要將單一圖片轉換成PDF文件,只需輸入檔案路徑到PdfGenerator.imageToPdf方法並匯出生成的PDF文件。

將多個圖片轉換成PDF涉及使用檔案路徑的陣列。 下面是帶有正確格式化程式碼片段的完整指南。

程式碼說明

  1. 導入所需模組

    • fs:一個與檔案系統互動的核心Node.js模組。
    • path:一個處理和轉換檔案路徑的核心模組。
    • PdfGenerator:IronPDF程式庫中用於生成PDF的模組。
  2. 讀取目錄

    • imageDirectoryPath指定的目錄。
    • 過濾並返回具有.jpeg擴展名的檔案。
  3. 建立完整檔案路徑

    • 使用path.join來構建篩選後圖片檔案的完整路徑。
  4. 圖片轉換成PDF

    • PdfGenerator.imageToPdf方法接收圖片路徑的陣列並將其轉換成單一PDF。
  5. 保存PDF

    • composite.pdf

有關使用IronPDF將圖片轉換成PDF的更多詳細資訊,請造訪IronPDF產品頁面

探索Python PDF到圖像轉換指南
在 GitHub 上查看

準備好開始了嗎?

版本:2026.6剛剛發布

Key in blue circle

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

Your trial license will be sent to your email address

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

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

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

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