Remove hyperlinks from a PDF document (iTextSharp)

安稳与你 提交于 2019-12-01 10:54:05

问题


I'm trying to leverage iTextSharp (very new to the product) to remove hyperlinks from a PDF document. Does anyone know if this is possible? I've been digging through the API and haven't found an obvious way to do this.

My problem is that I'm doing maintenance on a system that has PDFs empbedded in an iframe and the links within the PDF are causing users to end up browsing the site within the iframe rather than in a new window or tab so I'm looking for a way to kill the links in the PDF at request time.

Thanks in advance, Scott


回答1:


The links people click on are annotations in a given page's /Annots array.

You have two options:

  1. Destroy the entire /Annots array
  2. Search through the /Annots array and remove all the link annotations

Simply blasting the annotation array is easy:

 PdfDictionary pageDict = reader.getPageN(1); // 1st page is 1
 pageDict.remove(PdfName.ANNOTS);

 stamper.close();

The problem is that you might be destroying annotations that you want to keep along with those you don't.

The solution is to search the annot array looking for links to URLs.

PdfDictionary pageDict = reader.getPageN(1);
PdfArray annots = pageDict.getAsArray(PdfName.ANNOTS);
PdfArray newAnnots = new PdfArray();
if (annots != null) {
  for (int i = 0; i < annots.size(); ++i) {
    PdfDictionary annotDict = annots.getAsDict(i);
    if (!PdfName.LINK.equals(annotDict.getAsName(PdfName.SUBTYPE))) {
      // annots are actually listed as PdfIndirectReference's.  
      // Adding the dict directly would be A Bad Thing.
      newAnnots.add(annots.get(i));// get the original reference, not the dict
    }
  }
  pageDict.put(PdfName.ANNOTS, newAnnots);
}

This will remove all link annotations, not just those that link to internal sites. If you need to dig deeper, you'll need to check out the PDF Spec, section 12.5.6.5 (link annotations) and section 12.6.4.7 (URI actions).



来源:https://stackoverflow.com/questions/5871906/remove-hyperlinks-from-a-pdf-document-itextsharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!