前端将多个PDF链接的内容拼接成一个后返回出一个链接进行打开

发布于:2025-06-14 ⋅ 阅读:(43) ⋅ 点赞:(0)

1、引用了 “pdf-lib”库,它提供了一组丰富的功能,可以在客户端和服务器端中对PDF文件进行各种操作。

要对应 node 版本进行下载对应 “pdf-lib”库的依赖(直接问下AI);

node:v18.20.4

pdf-lib:"^1.17.1"

这是我这边的版本,如果一样的话可以直接下载依赖

安装命令:

yarn add pdf-lib
//指定版本
yarn add pdf-lib@1.17.1

2、安装完在需要的页面进行引用

import { PDFDocument } from 'pdf-lib';

3、思路:

  • 创建一个空白的PDF文档
  • 遍历即将合并的PDF文档,获取二进制数据
  • 依次将数据写入到空白文档中(如果单个PDF中有多页,需要一次一页往新建空白PDF中添加)
  • 将合并后的PDF文档保存为Blob对象
  • 创建URL并返回

4、具体代码实现:

const pdfLinkPrint = async (links: string[]) => {
    async function mergePDFs(links: string[]) {
        try {
            // 创建一个新的空白PDF文档
            const mergedPdfDoc = await PDFDocument.create();

            for (const pdfUrl of links) {
                // 获取PDF文件的二进制数据
                const pdfBytes = await fetch(pdfUrl).then(response => response.arrayBuffer());
        
                // 将获取到的PDF文件添加到新的文档中
                const pdfDoc = await PDFDocument.load(pdfBytes);
                // 如果单个PDF为多页,则要一页一页往新建的PDF中添加
                const copiedPages = await mergedPdfDoc.copyPages(pdfDoc, pdfDoc.getPageIndices());
                copiedPages.forEach((page: any) => mergedPdfDoc.addPage(page));
            }
        
            // 将合并后的PDF保存为Blob对象
            const mergedPdfBytes = await mergedPdfDoc.save();
            const mergedPdfBlob = new Blob([mergedPdfBytes], { type: 'application/pdf' });
            return URL.createObjectURL(mergedPdfBlob);
        } catch {}
    };
    if (!links.length) return;
    const url = links.length === 1 ? links[0] : await mergePDFs(links);
    const newWindow = window.open(url);

    if (newWindow) {
        newWindow.onload = () => {
            setTimeout(() => {
                URL.revokeObjectURL(url); // 释放 Blob URL
            }, 1000);
        };
    }
};

 5、最终的实现效果:


网站公告

今日签到

点亮在社区的每一天
去签到