如何使用 IText7 和 C# 修改现有 PDF 中的外部 link,使其指向文档中的内部页面?

How do I modify external link in an existing PDF such that it points to an internal page within document using IText7 and C#?

我有一个现有的 PDF 文件,其中包含指向外部 PDF 文件的链接。我想编辑这些链接,使它们指向同一个 PDF 文档中的页面。此功能以前适用于 iTextsharp,现在我正在迁移到 iText7,但无法使用它。

下面是我试过的示例代码,感觉非常接近解决方案,但缺少一些东西。这段代码基本上加载了一个 2 页的 PDF。第一页有大约 15 个链接都指向一个外部文件。我正在尝试编辑链接,以便它们将用户带到同一文档的第 2 页。我能够加载所有链接并查询它们的值,但不会发生更改。

    private bool MakeLinksInternal(string inputFile)
    {
      if (Path.GetExtension(inputFile).ToLower() != ".pdf")
        return false;

      using (PdfDocument pdfDocument = new PdfDocument(new PdfReader(inputFile)))
      {
        //get the index page
        PdfPage pdfPage = pdfDocument.GetPage(1);
        //get all of the link annotations for the current page
        var annots = pdfPage.GetAnnotations().Where(a => a.GetSubtype().Equals(PdfName.Link));

        //Make sure we have something
        if ((annots == null) || (annots.Count() == 0))
          return true;

        foreach (PdfLinkAnnotation linkAnnotation in annots)
        {
          //get action associated to the annotation
          var action = linkAnnotation.GetAction();
          if (action == null)
            continue;

          // Test if it is a URI action 
          if (action.Get(PdfName.S).Equals(PdfName.URI)
            || action.Get(PdfName.S).Equals(PdfName.GoToR))
          {
            action.Remove(PdfName.S);

            action.Put(PdfName.S, PdfName.GoTo);

            var newLocalDestination = new PdfArray();
            newLocalDestination.Add(pdfDocument.GetPage(2).GetPdfObject());
            newLocalDestination.Add(PdfName.Fit);

            action.Put(PdfName.D, newLocalDestination);
          }

        }
        pdfDocument.Close();
      }

      return true;
    }

这是我在 Whosebug 中的第一个问题,如果我在创建此问题时犯了任何错误,请多多包涵 post。

你这样创建PdfDocument

using (PdfDocument pdfDocument = new PdfDocument(new PdfReader(inputFile)))

这将创建一个 PdfDocument 只读。如果你还想写你应用的更改,你必须使用

using (PdfDocument pdfDocument = new PdfDocument(new PdfReader(inputFile), new PdfWriter(outputFile)))

您应该为 inputFileoutputFile 使用不同的名称。