如何修改现有PDF中的外部链接,使其指向文档内使用IText7和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;
}

这是我在stackoverflow的第一个问题,所以如果我在创建这个帖子时犯了任何错误,请原谅。

您可以像这样创建PdfDocument

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

创建一个只读的PdfDocument。如果您还想写入所应用的更改,则必须使用

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

inputFileoutputFile应该使用不同的名称。

最新更新