c# - 从pdf文件中读取超链接

标签 c# .net pdf itextsharp

我正在尝试读取 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/

相关文章:

c# - 如何使用基于 uaExpert 的客户端连接到需要基于 x509 证书的用户身份验证的 OPC-UA 服务器

c# - LINQ 导致我的混淆器崩溃

c# - 领域驱动设计、.NET 和 Entity Framework

c# - 线程时出现异常 - 线程之间的传播?

html - 从 CSS 和 HTML 生成 PDF,@page @top-center 和内容之间的距离更大

java - Apache poi 幻灯片到 pdf 转换

c# - DragDropEffects.Copy 和 DragDropEffects.Move 有什么区别?

.net - Visual Basic 如何读取 CSV 文件并在数据网格中显示值?

asp.net - 在 VB.Net 页面中使用 ASP.Net 导入指令的别名通用类型

pdf - 经典 ASP/asppdf 组件和页码