You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PDFBox添加PDAnnotationLink后,如何让黑色矩形透明?

解决PDFBox添加链接注释出现黑色矩形的问题

你的问题出在默认注释边框配置和链接区域位置不匹配上,按以下步骤修改代码即可解决:

1. 隐藏默认矩形边框,仅保留下划线

默认情况下PDAnnotationLink会显示矩形边框,即便你设置了下划线样式。需要先将默认边框宽度设为0,再单独配置下划线样式:

final PDAnnotationLink txtLink = new PDAnnotationLink();

// 隐藏默认矩形边框
txtLink.setBorder(new float[]{0, 0, 0});

// 配置下划线样式
final PDBorderStyleDictionary linkBorder = new PDBorderStyleDictionary();
linkBorder.setStyle(PDBorderStyleDictionary.STYLE_UNDERLINE);
linkBorder.setWidth(1); // 下划线宽度建议设为1-2,过大会影响视觉
txtLink.setBorderStyle(linkBorder);

2. 让链接区域与文本位置完全匹配

你当前的链接矩形位置(200,302,100,11)和文本起始位置(102,302)不重合,会导致下划线或黑色矩形出现在错误区域。需要先计算文本实际宽度,再调整链接矩形坐标:

// 计算文本实际宽度(字体大小10,需转换单位)
String linkText = "This is linked to the outside world";
float textWidth = PDType1Font.COURIER_BOLD.getStringWidth(linkText) * 10 / 1000;

// 设置链接矩形:x与文本起始位置一致,y略低于文本(适配下划线位置),宽度等于文本宽度
final PDRectangle position = new PDRectangle(102, 300, textWidth, 2);
txtLink.setRectangle(position);

3. 可选:设置下划线颜色(更贴近常规链接视觉)

如果想让下划线显示为蓝色,可添加颜色配置:

// 设置下划线为蓝色(RGBA格式,最后一位1为完全不透明)
txtLink.setColor(new PDColor(new float[]{0, 0, 1, 1}, PDDeviceRGB.INSTANCE));

修改后的完整代码片段

PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);

final PDAnnotationLink txtLink = new PDAnnotationLink();

// 隐藏默认矩形边框
txtLink.setBorder(new float[]{0, 0, 0});

// 配置下划线样式
final PDBorderStyleDictionary linkBorder = new PDBorderStyleDictionary();
linkBorder.setStyle(PDBorderStyleDictionary.STYLE_UNDERLINE);
linkBorder.setWidth(1);
txtLink.setBorderStyle(linkBorder);

// 设置下划线颜色为蓝色
txtLink.setColor(new PDColor(new float[]{0, 0, 1, 1}, PDDeviceRGB.INSTANCE));

// 配置跳转动作
final PDActionURI action = new PDActionURI();
action.setURI("https://www.test.com");
txtLink.setAction(action);

// 计算文本宽度并设置链接位置
String linkText = "This is linked to the outside world";
float textWidth = PDType1Font.COURIER_BOLD.getStringWidth(linkText) * 10 / 1000;
final PDRectangle position = new PDRectangle(102, 300, textWidth, 2);
txtLink.setRectangle(position);
page.getAnnotations().add(txtLink);

// 绘制文本
contentStream.beginText();
contentStream.newLineAtOffset(102, 302);
contentStream.setFont(PDType1Font.COURIER_BOLD, 10);
contentStream.showText(linkText);
contentStream.endText();
contentStream.close();

修改后黑色矩形会消失,仅显示文本下方的蓝色下划线,点击文本即可正常跳转。

内容的提问来源于stack exchange,提问作者Mario Rovelli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 18:43:14