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. 读取目录:

    • fs.readdir: 读取由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% 解锁。无需信用卡。

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
using npm 安装

版本: 2026.6

  1. 下载并安装 Node.js 12+。
  2. 在终端中执行上述命令。

$999 起