多頁單個pdf文件有效拆分成多個pdf

分兩步

1。//前提是需要加itext.jar

maven配置

    <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
        </dependency>

2。//說明 data單個需要拆分的文件流

//from 從第幾頁 end第幾頁爲一個文件

//savepath 拆分後保存的文件

 public static String splitFile(String savepath,byte[] data, Integer from,Integer end){
             
            Document document = null;
            PdfCopy copy = null;
            try {
                PdfReader reader = new PdfReader(data);
                int n = reader.getNumberOfPages();
                if(end==0){
                    end = n;
                }
                List<String> savepaths = new ArrayList<String>();
               // int a = pdfFile.lastIndexOf(".pdf");
                //String staticpath = pdfFile.substring(0, a);
               // String savepath = staticpath+ "_from_"+from+"_to_"+end+"_.pdf";
                savepaths.add(savepath);
                document = new Document(reader.getPageSize(1));
                copy = new PdfCopy(document, new FileOutputStream(savepaths.get(0)));
                document.open();
                for(int j=from; j<=end; j++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);
                    copy.addPage(page);
                }
                document.close();
                return savepath;
            } catch (IOException e) {
              //  logger.error("split pdf file error:{}",e.getMessage(),e);
                return null;
            } catch(DocumentException e) {
             //   logger.error("split pdf file error:{}",e.getMessage(),e);
                return null;
            }
        }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章