spring boot pdf 拆分

原创
2022/05/06 10:43
阅读数 213

spring boot pdf 拆分

1.其它文件请参照前面水印

2.请求参数

public class PdfSplitRequest {
    private String pdfBase64;//要拆分pdf base64
    private Integer cutePage;//每个文件的页数
}
{
  "cutePage": 1,
  "pdfBase64": ""
}  

3.具体的拆分方法

 public PdfSplitResponse splitPdf(PdfSplitRequest re) {
        Random random = new Random();
        Properties properties = System.getProperties();
        String baseUrl = properties.getProperty("user.dir")+"\\src\\main\\resources\\pdf\\";
        File dir = new File(baseUrl);
        if(!dir.exists()){
            dir.mkdirs();
        }
        String orgPdfPath = baseUrl + UUID.randomUUID().toString() + ".pdf";
        GLFile.decryptByBase64(re.getPdfBase64(),orgPdfPath);
        PdfDocument pdfDoc = null;
        try {
            pdfDoc = new PdfDocument(new PdfReader(orgPdfPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        ArrayList<Map<String,Integer>> pdfArrays = new ArrayList<>();
        Integer pages = pdfDoc.getNumberOfPages();
        for(int p = 1;p<= pages;){
            Map<String,Integer> mPage = new HashMap<>();
            mPage.put("fromPage",p);
            mPage.put("toPage",p+re.getCutePage()-1);
            pdfArrays.add(mPage);
            p = p + re.getCutePage();
        }
        ArrayList<String> pdfBase64s = new ArrayList<>();
        for(Map<String,Integer> mPage : pdfArrays){
            String newPdfPath = baseUrl + UUID.randomUUID().toString() + ".pdf";
            PdfDocument pdfDocument = null;
            try {
                pdfDocument = new PdfDocument(new PdfWriter(newPdfPath));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            pdfDoc.copyPagesTo(mPage.get("fromPage"),mPage.get("toPage"),pdfDocument);
            pdfDocument.close();
            String pdfStr = GLFile.encryptToBase64(newPdfPath);
            pdfBase64s.add(pdfStr);
            File newFile = new File(newPdfPath);
            newFile.delete();
        }
        pdfDoc.close();
        File orgFile = new File(orgPdfPath);
        orgFile.delete();
        PdfSplitResponse pdfSplitResponse = new PdfSplitResponse();
        pdfSplitResponse.setCode(1);
        pdfSplitResponse.setPdfs(pdfBase64s);
        return pdfSplitResponse;
    }

4.返回结果

{
  "code": 1,
  "apiCode": null,
  "message": null,
  "requestId": null,
  "requestTime": null,
  "pdfs": [
  {"base64"},{"base64"}
  ]
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
返回顶部
顶部