美文网首页
图片转pdf

图片转pdf

作者: 姜治宇 | 来源:发表于2024-07-23 15:50 被阅读0次

把图片转为pdf格式可以用pdfkit插件,主要是图片需要自适应pdf的大小,如果生成了pdf有多余的白页,可以用pdf-lib插件进行二次编辑。

const PDFKit = require('pdfkit');
const path = require('path');
const fs = require('fs');
const { PDFDocument } = require('pdf-lib');
handlePdf();
setTimeout(() => {
    removeEmptyPage();
}, 2000);

function handlePdf() {
    const directoryPath = './source';
    const images = fs.readdirSync(directoryPath);
    const outputPath = path.join(__dirname, 'output.pdf');


    const doc = new PDFKit({
        size: 'A4', // 可以是 'A4', 'Letter' 等标准尺寸,或者自定义尺寸如 '210mm'
        layout: 'portrait'
    });

    doc.pipe(fs.createWriteStream(outputPath));

    images.forEach((value) => {
        const imagePath = path.join(directoryPath, value);
        doc.addPage();
        const width = doc.page.width;
        const height = doc.page.height;
        doc.image(imagePath, 0, 0, {
            width: width,
            height: height,
            fit: [width, height]
        });
    });

    doc.end();
}
async function removeEmptyPage() {
    const pdfPath = path.join(__dirname, 'output.pdf');
    const updatedPdfPath = path.join(__dirname, 'output2.pdf');
    try {
        // 加载 PDF 文件
        const pdf = await PDFDocument.load(fs.readFileSync(pdfPath));

        // 删除第一页(如果存在)
        if (pdf.getPageCount() > 1) {
            pdf.removePage(0);
        }

        // 保存修改后的 PDF
        const data = await pdf.save();
        fs.writeFileSync(updatedPdfPath, data);

        console.log('PDF updated without the first page.');
    } catch (err) {
        console.error('Error updating PDF:', err);
    }


}

相关文章

网友评论

      本文标题:图片转pdf

      本文链接:https://www.haomeiwen.com/subject/bcxuhjtx.html