使用PDFBox无法在现有PDF页面追加高亮、图片等内容求助
PDFBox在现有页面追加内容的问题解决
代码中的直接错误
你提供的代码存在变量名不一致的问题:加载文档用的是document,但保存和关闭时误用了document1,这会导致修改无法写入目标文件,甚至触发空指针异常——这是调用getPage(0)后内容不生效的核心原因之一。
修正后的图片追加代码
以下是修正变量问题、确保内容正确追加到现有页面的代码:
File file = new File("FinalPDF 1.pdf"); try (PDDocument document = PDDocument.load(file)) { PDPage page1 = document.getPage(0); // 以APPEND模式追加内容到页面现有流之后 try (PDPageContentStream stream1 = new PDPageContentStream(document, page1, PDPageContentStream.AppendMode.APPEND, true, true)) { PDImageXObject pdImage = PDImageXObject.createFromFile("download.jpg", document); // PDF坐标原点在页面左下角,需确认坐标处于可见区域内 stream1.drawImage(pdImage, 250, 200); } document.save(file); } catch (IOException e) { e.printStackTrace(); }
高亮文本的正确实现方式
使用PDAnnotationTextMarkup实现高亮时,需正确设置高亮区域坐标并将注解添加到页面注解列表,示例代码如下:
File file = new File("FinalPDF 1.pdf"); try (PDDocument document = PDDocument.load(file)) { PDPage page1 = document.getPage(0); // 创建高亮注解实例 PDAnnotationTextMarkup highlight = new PDAnnotationTextMarkup(PDAnnotationTextMarkup.SUB_TYPE_HIGHLIGHT); // 设置高亮区域矩形(参数为x1,y1,x2,y2,坐标基于PDF左下角) PDRectangle rect = new PDRectangle(100, 600, 200, 20); highlight.setRectangle(rect); // 设置半透明黄色高亮 highlight.setColor(new PDColor(new float[]{1, 1, 0}, PDDeviceRGB.INSTANCE)); // 定义高亮区域的四个顶点(顺序:左上、右上、右下、左下) float[] quadPoints = new float[]{ rect.getLowerLeftX(), rect.getUpperRightY(), rect.getUpperRightX(), rect.getUpperRightY(), rect.getLowerLeftX(), rect.getLowerLeftY(), rect.getUpperRightX(), rect.getLowerLeftY() }; highlight.setQuadPoints(quadPoints); // 将注解添加到页面 page1.getAnnotations().add(highlight); document.save(file); } catch (IOException e) { e.printStackTrace(); }
额外注意事项
- PDF坐标原点在页面左下角,设置位置时可通过
page1.getMediaBox()获取页面宽高,确保坐标处于可见范围内。 - 若APPEND模式下内容被原有内容覆盖,可尝试改为
PDPageContentStream.AppendMode.PREPEND,将内容绘制在原有内容之前。
内容的提问来源于stack exchange,提问作者Sunket Xoriant
相关产品推荐
相关产品推荐

