2

I am trying to use PDFBox to resize PDFs so that I can make some space for header and footer later. I am able to do it for most cases except when the page size is way much large.

Page Width & Height = 3168.0 :: 22023.0 (pts)

I am using the following code:

public static void main(String[] args) {
    // TODO Auto-generated method stub
    try {
    //String pdfFilename = "/MuhimbiPOC/Templates/Source_doc_withheaderfooter.pdf";
    //String pdfFilename = "/MuhimbiPOC/Templates/3.pdf";
    String pdfFilename = "/MuhimbiPOC/Templates/PDFsam_3.pdf";
    PDDocument document = PDDocument.load(new File(pdfFilename));
    PDDocument documentPDF = new PDDocument();
    PDFRenderer pdfRenderer = new PDFRenderer(document);
    PDPage pge = new PDPage();
    int pageCounter = 0;
    for (PDPage page : document.getPages())
    {

        final PDRectangle mediaBox = page.getMediaBox();
        mediaBox.setUpperRightX((float) (page.getMediaBox().getUpperRightX()));
        mediaBox.setUpperRightY(page.getMediaBox().getUpperRightY() + page.getMediaBox().getHeight() * 0.1f);
        mediaBox.setLowerLeftY(page.getMediaBox().getLowerLeftY() - page.getMediaBox().getHeight() * 0.1f); 
        System.out.println("====================================");
        System.out.println((float) (page.getMediaBox().getWidth()) + " :: " + page.getMediaBox().getHeight());
        System.out.println(mediaBox.getWidth() + " :: " + mediaBox.getHeight());
        System.out.println("====================================");
        // note that the page number parameter is zero based
        page.setMediaBox(mediaBox);
    }
    System.out.println("No. of Pages :: " + document.getNumberOfPages());
    document.save(pdfFilename + "_test.pdf");
    System.out.println("Task Completed ... @ " + new Date());
    document.close();


}
 catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
}

This works perfectly for every cases except with the one i mentioned.

Prashant Chaudhary
  • 95
  • 1
  • 1
  • 15

1 Answers1

1

The OP's code only reads and updates the MediaBox of the page. But the CropBox is more important for the visible size of a page. You can find an enumeration and description of the different boxes one can define on a page in this answer.

The reason why the code works most of the time in spite of this, is that the CropBox defaults to the MediaBox if it is not explicitly given.

Thus, the code should be updated to update both the MediaBox and the CropBox if the latter also is explicitly given for a page.

mkl
  • 90,588
  • 15
  • 125
  • 265