如何解决如何使用 IText7 和 C# 修改现有 PDF 中的外部链接,使其指向文档中的内部页面?
我有一个现有的 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;
}
这是我在 stackoverflow 中的第一个问题,所以如果我在创建这篇文章时犯了任何错误,请多多包涵。
解决方法
您像这样创建 PdfDocument
using (PdfDocument pdfDocument = new PdfDocument(new PdfReader(inputFile)))
这会创建一个只读的 PdfDocument
。如果您还想编写您应用的更改,则必须使用
using (PdfDocument pdfDocument = new PdfDocument(new PdfReader(inputFile),new PdfWriter(outputFile)))
您应该为 inputFile
和 outputFile
使用不同的名称。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。