如何使用 itext 替换 PDF 中的超链接文本

How to replace hyperlink text in PDF using itext

我需要在多个包含图像、links、段落文本等的 PDF 页面中替换特定的 hyperlink。我可以更改注释但不能更改相应的 link 文本。这是到目前为止的代码

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));
    }
}
}

我尝试使用以下代码替换 link 文本,但它似乎不存在于流字节中。

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());
}

此外,link文本下划线必须保留

下面的代码对我有用,我不得不更改出现在多个页面中相同位置的超链接

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);
}