iTextPDF-5.5.1缩小PDF后超链接bounding box未同步缩小问题
解决iText 5中PDF缩小后超链接Bounding Box错位的问题
我完全懂你碰到的这个坑——你通过修改页面内容流的变换矩阵缩小了页面内容,但PDF里的超链接属于注释(Annotation),它们并不在页面的内容流里,所以你的缩放操作根本没影响到它们,这就导致链接的点击区域还停留在原来的位置和大小,和缩小后的内容错位了。
要解决这个问题,你需要在遍历页面的时候,额外处理每个页面上的链接注释,手动把它们的Bounding Box也按照相同的缩放比例和偏移量调整。
修改后的完整代码
public void shrinkPDF(String strFilePath, String strFileName) throws Exception { float xPercentage = 0.9f; float yPercentage = 0.9f; 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 pageWidth = reader.getPageSize(p).getWidth(); float pageHeight = reader.getPageSize(p).getHeight(); float offsetX = (pageWidth * (1 - xPercentage)) / 2; float offsetY = (pageHeight * (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"); // 处理页面上的链接注释,调整它们的Bounding Box PdfAnnotation[] annotations = reader.getPageAnnotations(p); if (annotations != null) { for (PdfAnnotation annotation : annotations) { // 只处理链接类型的注释 if (annotation.getSubtype().equals(PdfAnnotation.LINK)) { Rectangle originalRect = annotation.getRectangle(); // 计算缩放并偏移后的新坐标:PDF坐标原点在左下角,所以每个坐标都要缩放+偏移 float newLeft = originalRect.getLeft() * xPercentage + offsetX; float newBottom = originalRect.getBottom() * yPercentage + offsetY; float newRight = originalRect.getRight() * xPercentage + offsetX; float newTop = originalRect.getTop() * yPercentage + offsetY; // 更新注释的Bounding Box annotation.setRectangle(new Rectangle(newLeft, newBottom, newRight, newTop)); // 把修改后的注释写回 stamper stamper.addAnnotation(annotation, p); } } } } stamper.close(); reader.close(); }
关键说明
- 注释的独立性:PDF的注释是和页面内容流分离的对象,内容流的变换矩阵不会自动应用到注释上,必须手动处理。
- 坐标计算:PDF的坐标系统以页面左下角为原点,所以我们需要对注释矩形的四个坐标分别进行缩放,再加上偏移量,确保链接区域和缩小后的内容精准对齐。
- 类型判断:这里只处理
LINK类型的注释,如果你还有其他需要同步调整的注释类型(比如表单域),可以扩展判断逻辑。
这样修改后,目录里的超链接Bounding Box就会和页面内容一起同步缩小,点击区域就不会错位了。
内容的提问来源于stack exchange,提问作者Chetan_C
相关产品推荐
相关产品推荐

