You can try this method using PdfCopy
, intermittently manipulating the PdfReader
copied from:
void splitIntoHalfPages(InputStream source, File target) throws IOException, DocumentException
{
final PdfReader reader = new PdfReader(source);
try ( OutputStream targetStream = new FileOutputStream(target) )
{
Document document = new Document();
PdfCopy copy = new PdfCopy(document, targetStream);
document.open();
for (int page = 1; page <= reader.getNumberOfPages(); page++)
{
PdfDictionary pageN = reader.getPageN(page);
Rectangle cropBox = reader.getCropBox(page);
PdfArray leftBox = new PdfArray(new float[]{cropBox.getLeft(), cropBox.getBottom(), (cropBox.getLeft() + cropBox.getRight()) / 2.0f, cropBox.getTop()});
PdfArray rightBox = new PdfArray(new float[]{(cropBox.getLeft() + cropBox.getRight()) / 2.0f, cropBox.getBottom(), cropBox.getRight(), cropBox.getTop()});
PdfImportedPage importedPage = copy.getImportedPage(reader, page);
pageN.put(PdfName.CROPBOX, leftBox);
copy.addPage(importedPage);
pageN.put(PdfName.CROPBOX, rightBox);
copy.addPage(importedPage);
}
document.close();
}
finally
{
reader.close();
}
}
(SplitIntoHalfPages.java)
This methods creates a copy of the source document containing each page twice, once with the CropBox limited to the left half page, once to the right one.
Beware: This method only splits the page content. If your source PDFs have annotations, you might want to also process them.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…