[Java程式碼] java使用itext按頁碼拆分pdf檔案
阿新 • • 發佈:2019-01-25
- /**
- * @author viralpatel.net
- *http://www.kmnk01.com/hxpfk/2015/bdf_1219/312.html
- * @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
- */http://www.kmnk01.com/hxpfk/2015/xmz_1219/320.html
- public static void splitPDF(InputStream inputStream,
- OutputStream outputStream, int fromPage, int toPage) {
- Document document = new Document();
- try {
- PdfReader inputPDF = new PdfReader(inputStream);
- http://www.kmnk01.com/hxpfk/2015/gm_1219/314.html
- int totalPages = inputPDF.getNumberOfPages();
- //make fromPage equals to toPage if it is greater
- if(fromPage > toPage ) {
- fromPage = toPage;
- http://www.kmnk01.com/hxpfk/2015/mny_1219/315.html
- if(toPage > totalPages) {
- toPage = totalPages;
- }
- // Create a writer for the outputstream
- PdfWriter writer = PdfWriter.getInstance(document, outputStream);
- http://www.kmnk01.com/hxpfk/2015/qcd_1219/318.html
- document.open();
- PdfContentByte cb = writer.getDirectContent(); // Holds the PDF data
- PdfImportedPage page;
- http://www.kmnk01.com/hxpfk/2015/py_1219/321.html
- while(fromPage <= toPage) {
- document.newPage();
- page = writer.getImportedPage(inputPDF, fromPage);
- cb.addTemplate(page, 0, 0);
- fromPage++;
- http://www.kmnk01.com/hxpfk/2015/sz_1219/313.html
- outputStream.flush();
- document.close();
- outputStream.close();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (document.isOpen())
- document.close();
- try {http://www.kmnk01.com/hxpfk/2015/py_1219/316.html
- if (outputStream != null)
- outputStream.close();
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- }
- }