1 50 51 package com.lowagie.tools; 52 53 import java.io.FileOutputStream ; 54 55 import com.lowagie.text.Document; 56 import com.lowagie.text.DocumentException; 57 import com.lowagie.text.pdf.PdfContentByte; 58 import com.lowagie.text.pdf.PdfImportedPage; 59 import com.lowagie.text.pdf.PdfReader; 60 import com.lowagie.text.pdf.PdfWriter; 61 62 66 public class split_pdf extends java.lang.Object { 67 68 72 public static void main(String args[]) { 73 if (args.length != 4) { 74 System.err.println("arguments: srcfile destfile1 destfile2 pagenumber"); 75 } 76 else { 77 try { 78 int pagenumber = Integer.parseInt(args[3]); 79 80 PdfReader reader = new PdfReader(args[0]); 82 int n = reader.getNumberOfPages(); 84 System.out.println("There are " + n + " pages in the original file."); 85 86 if (pagenumber < 2 || pagenumber > n) { 87 throw new DocumentException("You can't split this document at page " + pagenumber + "; there is no such page."); 88 } 89 90 Document document1 = new Document(reader.getPageSizeWithRotation(1)); 92 Document document2 = new Document(reader.getPageSizeWithRotation(pagenumber)); 93 PdfWriter writer1 = PdfWriter.getInstance(document1, new FileOutputStream (args[1])); 95 PdfWriter writer2 = PdfWriter.getInstance(document2, new FileOutputStream (args[2])); 96 document1.open(); 98 PdfContentByte cb1 = writer1.getDirectContent(); 99 document2.open(); 100 PdfContentByte cb2 = writer2.getDirectContent(); 101 PdfImportedPage page; 102 int rotation; 103 int i = 0; 104 while (i < pagenumber - 1) { 106 i++; 107 document1.setPageSize(reader.getPageSizeWithRotation(i)); 108 document1.newPage(); 109 page = writer1.getImportedPage(reader, i); 110 rotation = reader.getPageRotation(i); 111 if (rotation == 90 || rotation == 270) { 112 cb1.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight()); 113 } 114 else { 115 cb1.addTemplate(page, 1f, 0, 0, 1f, 0, 0); 116 } 117 } 118 while (i < n) { 119 i++; 120 document2.setPageSize(reader.getPageSizeWithRotation(i)); 121 document2.newPage(); 122 page = writer2.getImportedPage(reader, i); 123 rotation = reader.getPageRotation(i); 124 if (rotation == 90 || rotation == 270) { 125 cb2.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight()); 126 } 127 else { 128 cb2.addTemplate(page, 1f, 0, 0, 1f, 0, 0); 129 } 130 System.out.println("Processed page " + i); 131 } 132 document1.close(); 134 document2.close(); 135 } 136 catch(Exception e) { 137 e.printStackTrace(); 138 } 139 } 140 } 141 } 142 143 | Popular Tags |