该代码需要添加itext.jar的依赖,建议直接去maven仓库下载。具体操作只需要设置待拆分文件的路径,以及拆分后文件的最大页数,实现自动拆分。
public class SplitFileTest {public static void main(String[] args) {splitExistFile();}public static void splitExistFile() {// 文档路径String path = "D:\\Personality\\pdf\\";// 待拆分文件名String pdfFileName = "test.pdf";// 每个文件最大页数int filePageSize = 2;// 待拆分文件的总页数int totalPage;// 拆分后的文件数量int splitFileNum;int pageIndex = 1;PdfReader reader = null;try {String orignName = pdfFileName.split("\\.")[0];reader = new PdfReader(path + pdfFileName);totalPage = reader.getNumberOfPages();splitFileNum = totalPage % filePageSize == 0 ? totalPage / filePageSize : totalPage / filePageSize + 1;for (int i = 0; i < splitFileNum; i++) {String newFileName = path + orignName + "_" + (i + 1) + ".pdf";// 新建一个PDF文件Document document = null;PdfWriter writer = null;try {document = new Document();writer = PdfWriter.getInstance(document, new FileOutputStream(newFileName));document.open();PdfContentByte pdfContentByte = writer.getDirectContent();for (int j = 0; j < filePageSize; j++) {document.newPage();pdfContentByte.addTemplate(writer.getImportedPage(reader, pageIndex), 0, 0);pageIndex ++;if (pageIndex > totalPage)break;}} catch (IOException e) {e.printStackTrace();} catch (DocumentException e) {e.printStackTrace();}catch (Exception e) {e.printStackTrace();}finally {//这个地方要特别注意资源关闭的顺序if (document != null)document.close();if (writer != null)writer.close();}}} catch (IOException e1) {e1.printStackTrace();} finally {if(reader!=null) reader.close();}}}
如果觉得《java使用itext开源包实现pdf文件拆分 可根据需要 设置拆分的页数 亲测可用》对你有帮助,请点赞、收藏,并留下你的观点哦!