itext Split PDF Vertically

前端 未结 1 892
执念已碎
执念已碎 2020-12-20 07:01

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

相关标签:
1条回答
  • 2020-12-20 07:39

    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.

    0 讨论(0)
提交回复
热议问题