java使用itext按頁碼拆分pdf文件
java使用itext按頁碼拆分pdf文件,代碼實現如下:
/**
- @author viralpatel.net
- @param inputStream Input PDF file
- @param outputStream Output PDF file
- @param fromPage start page from input PDF file
@param toPage end page from input PDF file */ public static void splitPDF(InputStream inputStream,
OutputStream outputStream, int fromPage, int toPage) {
Document document = new Document(); try {
PdfReader inputPDF = new PdfReader(inputStream); int totalPages = inputPDF.getNumberOfPages(); //make fromPage equals to toPage if it is greater if(fromPage > toPage ) { fromPage = toPage; } if(toPage > totalPages) { toPage = totalPages; } // Create a writer for the outputstream PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); PdfContentByte cb = writer.getDirectContent(); // Holds the PDF data PdfImportedPage page; while(fromPage <= toPage) { document.newPage(); page = writer.getImportedPage(inputPDF, fromPage); cb.addTemplate(page, 0, 0); fromPage++; } outputStream.flush(); document.close(); outputStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (document.isOpen()) document.close(); try { if (outputStream != null) outputStream.close(); } catch (IOException ioe) { ioe.printStackTrace(); }
} }</pre>
使用示例如下,將一個20頁的pdf文件拆分成1-12和13-20頁兩個pdf文件:
public static void main(String[] args) { try {
MergePDF.splitPDF(new FileInputStream("C:\\input.pdf"), new FileOutputStream("C:\\output1.pdf"), 1, 12); MergePDF.splitPDF(new FileInputStream("C:\\input.pdf"), new FileOutputStream("C:\\output2.pdf"), 13, 20);
} catch (Exception e) {
e.printStackTrace();
} }</pre>
本文由用戶 c6g3 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!