1. 程式人生 > >[Java程式碼] java使用itext按頁碼拆分pdf檔案

[Java程式碼] java使用itext按頁碼拆分pdf檔案

  1. /**
  2. * @author viralpatel.net
  3. *http://www.kmnk01.com/hxpfk/2015/bdf_1219/312.html
  4. * @param inputStream Input PDF file
  5. * @param outputStream Output PDF file
  6. * @param fromPage start page from input PDF file
  7. * @param toPage end page from input PDF file
  8. */http://www.kmnk01.com/hxpfk/2015/xmz_1219/320.html
  9. public static void splitPDF(InputStream inputStream,
  10. OutputStream outputStream, int fromPage, int toPage) {
  11. Document document = new Document();
  12. try {
  13. PdfReader inputPDF = new PdfReader(inputStream);
  14. http://www.kmnk01.com/hxpfk/2015/gm_1219/314.html
  15. int totalPages = inputPDF.getNumberOfPages();
  16. //make fromPage equals to toPage if it is greater
  17. if(fromPage > toPage ) {
  18. fromPage = toPage;
  19. http://www.kmnk01.com/hxpfk/2015/mny_1219/315.html
  20. if(toPage > totalPages) {
  21. toPage = totalPages;
  22. }
  23. // Create a writer for the outputstream
  24. PdfWriter writer = PdfWriter.getInstance(document, outputStream);
  25. http://www.kmnk01.com/hxpfk/2015/qcd_1219/318.html
  26. document.open();
  27. PdfContentByte cb = writer.getDirectContent(); // Holds the PDF data
  28. PdfImportedPage page;
  29. http://www.kmnk01.com/hxpfk/2015/py_1219/321.html
  30. while(fromPage <= toPage) {
  31. document.newPage();
  32. page = writer.getImportedPage(inputPDF, fromPage);
  33. cb.addTemplate(page, 0, 0);
  34. fromPage++;
  35. http://www.kmnk01.com/hxpfk/2015/sz_1219/313.html
  36. outputStream.flush();
  37. document.close();
  38. outputStream.close();
  39. } catch (Exception e) {
  40. e.printStackTrace();
  41. } finally {
  42. if (document.isOpen())
  43. document.close();
  44. try {http://www.kmnk01.com/hxpfk/2015/py_1219/316.html
  45. if (outputStream != null)
  46. outputStream.close();
  47. } catch (IOException ioe) {
  48. ioe.printStackTrace();
  49. }
  50. }
  51. }