I have requirement where I have to split a PDF page right at center vertically. I searched through various posts and could not identify the right way to do it
I want to use iText Library using Java.
I used the SplitPDFFile.java from
iText: split a PDF into several PDF (1 per page)
and modified it like below, but page not getting split but it copies entire page.
import java.io.FileOutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
public class SplitPDFFile {
/**
* @param args
*/
public static void main(String[] args) {
try {
String inFile = "C:/input.pdf";
System.out.println ("Reading " + inFile);
PdfReader reader = new PdfReader(inFile);
Rectangle cropBox = reader.getCropBox(1);
Rectangle psize = reader.getPageSize(1);
cropBox.setRight(psize.getWidth()/2);
System.out.println(psize.getWidth());
System.out.println(psize.getHeight());
int n = reader.getNumberOfPages();
System.out.println ("Number of pages : " + n);
int i = 0;
while ( i < n ) {
String outFile = inFile.substring(0, inFile.indexOf(".pdf"))
+ "-" + String.format("%03d", i + 1) + ".pdf";
System.out.println ("Writing " + outFile);
Document document = new Document(cropBox);
PdfCopy writer = new PdfCopy(document, new FileOutputStream(outFile));
writer.setCropBoxSize(cropBox);
document.open();
PdfImportedPage page = writer.getImportedPage(reader, ++i);
writer.addPage(page);
document.close();
writer.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}