我需要替换多个PDF页面中的特定超链接,这些超链接包含图像,链接,段落文本等。我可以更改注释但不能更改相应的链接文本。这是迄今为止的代码
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
PdfArray array = reader.getPageN(i).getAsArray(PdfName.ANNOTS);
if (array == null) continue;
for (int j = 0; j < array.size(); j++) {
PdfDictionary annot = array.getAsDict(j);
PdfDictionary link = (PdfDictionary)reader.getPdfObjectRelease(annot);
if(i==1 && j==0 || i==2 && j==0 || i==3 && j==0 || i==4 && j==0 || i==4 && j==1){
link.put(PdfName.A, new PdfAction(newurl));
}
}
}
我尝试使用以下代码替换链接文本,但它似乎不存在于流字节中。
PdfObject object = dict.getDirectObject(PdfName.CONTENTS);
if (object instanceof PRStream) {
PRStream stream = (PRStream)object;
byte[] data = PdfReader.getStreamBytes(stream);
stream.setData(new String(data).replace(oldstring, newstring).getBytes());
}
此外,必须保留链接文字下划线
答案 0 :(得分:1)
下面的代码对我有用,我必须更改出现在多个页面中相同位置的超链接
Chunk url = new Chunk(new_url_text);
url.setUnderline(0.1f, -2f);
BaseColor bcolor = new BaseColor(0xFF, 0xFF, 0xFF);
Font ffont = new Font();
ffont.setColor(0, 114, 53);
ffont.setSize(12);
Phrase p = new Phrase("",ffont); // Text that appears before the link can be added here (optional)
p.add(url);
int pages = reader.getNumberOfPages();
for (int j = 1; j <= reader.getNumberOfPages(); j++) {
PdfContentByte canvas = stamper.getOverContent(j);
canvas.setColorFill(bcolor);
canvas.rectangle(270, 135, 500, 40);
canvas.fill();
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, p, 340, 160, 0);
}