我正在尝试读取 pdf 文件并从该文件获取所有超链接。 我正在为 C# .net 使用 iTextSharp。
PdfReader reader = new PdfReader("test.pdf");
List<PdfAnnotation.PdfImportedLink> list = reader.GetLinks(36);
“GetLinks”这个方法返回一个列表,里面有很多关于链接的信息,但是这个方法没有返回我想要的值,超链接字符串,我完全知道第 36 页有超链接
最佳答案
PdfReader.GetLinks()
仅适用于文档内部链接,不适用于外部超链接。为什么?我不知道。
以下代码基于 code I wrote earlier但我将其限制为以 PdfName.URI
形式存储在 PDF 中的链接。可以将链接存储为最终执行相同操作的 Javascript,并且可能还有其他类型,但您需要对此进行检测。我不相信规范中有任何内容说链接实际上需要是 URI,这只是隐含的,所以下面的代码返回一个字符串,您可以(可能)自己将其转换为 URI。
private static List<string> GetPdfLinks(string file, int page)
{
//Open our reader
PdfReader R = new PdfReader(file);
//Get the current page
PdfDictionary PageDictionary = R.GetPageN(page);
//Get all of the annotations for the current page
PdfArray Annots = PageDictionary.GetAsArray(PdfName.ANNOTS);
//Make sure we have something
if ((Annots == null) || (Annots.Length == 0))
return null;
List<string> Ret = new List<string>();
//Loop through each annotation
foreach (PdfObject A in Annots.ArrayList)
{
//Convert the itext-specific object as a generic PDF object
PdfDictionary AnnotationDictionary = (PdfDictionary)PdfReader.GetPdfObject(A);
//Make sure this annotation has a link
if (!AnnotationDictionary.Get(PdfName.SUBTYPE).Equals(PdfName.LINK))
continue;
//Make sure this annotation has an ACTION
if (AnnotationDictionary.Get(PdfName.A) == null)
continue;
//Get the ACTION for the current annotation
PdfDictionary AnnotationAction = (PdfDictionary)AnnotationDictionary.Get(PdfName.A);
//Test if it is a URI action (There are tons of other types of actions, some of which might mimic URI, such as JavaScript, but those need to be handled seperately)
if (AnnotationAction.Get(PdfName.S).Equals(PdfName.URI))
{
PdfString Destination = AnnotationAction.GetAsString(PdfName.URI);
if (Destination != null)
Ret.Add(Destination.ToString());
}
}
return Ret;
}
并称它为:
string myfile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Output.pdf");
List<string> Links = GetPdfLinks(myfile, 1);
关于c# - 从pdf文件中读取超链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6959076/