Search code examples
javahyperlinkitextpdf-generationbounding-box

Itext PDF Shrink issue with hyperlink bounding box is not getting Shrinked


I am working with PDF shrinking and then watermarking it and for the same I am using itextpdf-5.5.1.jar. Here is the code which I use to shrink PDF. In code xPercentage and xPercentage value is 0.9f. When I shrink PDF having content table , content on the page is shrinking properly. When I go to table of content the bounding box of hyperlink is getting misplaced. I noticed that size of bounding box is same for Original and shrink output document. How do I shrink bounding box of hyperlink with respect to content?

public  void shrinkPDF(String strFilePath , String strFileName) throws Exception{
PdfReader reader = new PdfReader(strFilePath+"//"+strFileName);
PdfStamper stamper = new PdfStamper(reader, new 
FileOutputStream(strFilePath+"//Shrink_"+strFileName));
int n = reader.getNumberOfPages();
Map mpPDFLayer = stamper.getPdfLayers();
    for (int p = 1; p <= n; p++) {
        float offsetX = (reader.getPageSize(p).getWidth() * (1 - xPercentage)) / 2;
        float offsetY = (reader.getPageSize(p).getHeight() * (1 - yPercentage)) / 2;
        stamper.getUnderContent(p).setLiteral(
                    String.format("\nq %s 0 0 %s %s %s cm\nq\n",
                    xPercentage, yPercentage, offsetX, offsetY));

        stamper.getOverContent(p).setLiteral("\nQ\nQ\n");
    }   
stamper.close();
reader.close();
}

Solution

  • Your code shrinks only the content but it does not accordingly move and shrink annotations. So what you have to do additionally is to iterate over the annotations of each page and shrink them.

    This in particular means that you have to shrink and move the Rect annotation rectangle. Depending on the nature of the respective annotation, though, there also are other coordinate values in them, e.g. the QuadPoints in case of a link or the L endpoint coordinates of a line.


    BTW, your content shrinking code makes assumptions on the origin of the user space coordinate system; it appears to assume that the origin is in the lower left of the crop box and that the crop box and the media box coincide.