234234234

nodejs 多张图片按顺序合成pdf

import { PDFDocument, rgb } from "pdf-lib";
import fs from 'fs';
import path from 'path';


async function imagesToPdf(inputPaths, outputPath, options = {}) {
    // 默认配置:A4宽度595.28pt,边距0
    const { pageWidth = 595.28, margin = 0 } = options;

    const pdfDoc = await PDFDocument.create();

    for (const imgPath of inputPaths) {
        const imageBytes = fs.readFileSync(imgPath);
        const ext = path.extname(imgPath).toLowerCase();

        // 根据扩展名选择嵌入方式
        let image;
        if (ext === '.png') {
            image = await pdfDoc.embedPng(imageBytes);
        } else if (ext === '.jpg' || ext === '.jpeg') {
            image = await pdfDoc.embedJpg(imageBytes);
        } else {
            throw new Error(`Unsupported image format: ${ext}`);
        }

        // 计算缩放比例和实际绘制区域
        const contentWidth = pageWidth - margin * 2;
        const scale = contentWidth / image.width;
        const scaledHeight = image.height * scale;

        // 创建与内容匹配的页面
        const page = pdfDoc.addPage([pageWidth, scaledHeight + margin * 2]);

        // 绘制图片(自动适应宽度)
        page.drawImage(image, {
            x: margin,
            y: margin,
            width: contentWidth,
            height: scaledHeight,
        });
    }

    // 保存PDF文件
    const pdfBytes = await pdfDoc.save();
    fs.writeFileSync(outputPath, pdfBytes);
}

// 使用示例
const imagePaths = new Array(19).fill(0).map((_, i) => `C:\\Users\\Win10\\Desktop\\tttt/${i+1}.png`);
// 使用示例
imagesToPdf(
    imagePaths,
    'output.pdf',
    { pageWidth: 595.28, margin: 20 } // 可选参数
);

  

posted @ 2025-05-17 10:42  ukeepgoing  阅读(55)  评论(0)    收藏  举报
23423423423