Reputation: 11
I need to replace a particular hyperlink in multiple PDF pages which has images, links, paragraph texts, etc. I am able to change the annotations but not the corresponding link text. Here's the code so far
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));
}
}
}
I have tried replacing the link text using the below code but it doesn't seem to be present in the stream bytes.
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());
}
Also, the link text underline has to be retained
Upvotes: 0
Views: 1346
Reputation: 11
Below code worked for me where I had to change hyperlinks appearing at the same location in multiple pages
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);
}
Upvotes: 1