linux环境 itext 合并pdf

pom依赖
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13</version>
</dependency>

mergePdfUtil.java

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.framework.config.RuoYiConfig;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

/**
 * @author hzj
 * @date 2020/10/8 15:02
 */
public class MergePdfUtil {
    /**
     *
     * @param pdfFilesName 文件路径集合
     * @param newUrl 用于存放合并后的pdf
     * @param httpUrl 服务器路径
     */
    public static void MergePdf(List<String> pdfFilesName, String newUrl, String httpUrl) {
        PdfReader reader = null;
        Document document = null;
        try {
            //创建文件夹
            File file = new File(newUrl);
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            String docUrl = serviceUrl(pdfFilesName.get(0), httpUrl);
            document = new Document(new PdfReader(docUrl).getPageSize(1));
            PdfCopy pdfCopy = new PdfCopy(document, new FileOutputStream(newUrl));
            int pageCount = 0;
            document.open();
            for (int i = 0; i < pdfFilesName.size(); ++i) {
            System.out.println(pdfFilesName.get(i));
            String serviceUrl = serviceUrl(pdfFilesName.get(i),httpUrl);
            System.out.println(serviceUrl);
            File file1 = new File(serviceUrl);
                if(file1.exists()){
                    reader = new PdfReader(serviceUrl);
                    pageCount = reader.getNumberOfPages();
                    for (int j = 1; j <= pageCount; ++j) {
                        pdfCopy.addPage(pdfCopy.getImportedPage(reader, j));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            document.close();
        }
    }
    //替换后缀,拼出文件在服务器的路径
    private static String serviceUrl(String url,String httpUrl){
        String httpUrls = httpUrl + Constants.RESOURCE_PREFIX;
        String[] split = url.split(httpUrls);
        int i = split[1].lastIndexOf(".");
        String substring = split[1].substring(0, i)+".pdf";
        String replace = RuoYiConfig.getProfile()+ substring;
        return replace;
    }
}

遇到  PDF header signature not found,先排除文件损坏的原因,在仔细检查文件路径是否正确


版权声明:本文为qq_34279442原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
THE END
< <上一篇
下一篇>>