【发布时间】:2018-11-24 14:18:45
【问题描述】:
我有一个带有目录的 PDF:
使用 iTextSharp.dll 我试图获取注释然后对这些注释执行操作。然后我想操纵/更改链接以指向另一个页面。例如,如果目录中的 第 1 章 指向第 5 页,我希望在单击链接时它指向第 2 页。由于某种原因,注释上的操作为空,因此我无法操作此数据。下面的代码有效,但始终提供空 action。我不明白为什么会这样。 重现有问题的pdf
- 创建一个 3 页的 word 文档
- 第 1 页为目录,第 2 页为第 1 章,第 3 页为第 2 章
- 导出为 PDF
- 拥有 PDF 后,目录应该是“可点击的”。
然后我希望能够操纵它点击的位置。谢谢。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using System.Collections;
namespace PDFLinks
{
class Program
{
//Folder that we are working in
//private static readonly string WorkingFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Hyperlinked PDFs");
//Sample PDF
private static readonly string BaseFile = Path.Combine("C:\\Temp", "TableOfContentsTest.pdf");
//Final file
private static readonly string OutputFile = Path.Combine("C:\\Temp", "NewFile.pdf");
static void Main(string[] args)
{
//Setup some variables to be used later
PdfReader R = default(PdfReader);
int PageCount = 0;
//Open our reader
R = new PdfReader(BaseFile);
//Get the page cont
PageCount = R.NumberOfPages;
Console.WriteLine("Page Count= " + PageCount);
//Loop through each page
//for (int i = 1; i <= PageCount; i++)
//{
//Get the current page
PdfDictionary PageDictionary = R.GetPageN(1);
//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))
{
Console.WriteLine("nothing");
}
//Loop through each annotation
if (Annots != null)
{
Console.WriteLine("ANNOTS Not Null" + Annots[0]);
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;
if (AnnotationDictionary.Get(PdfName.A) != null)
{
Console.WriteLine("ACTION Not Null");
}
//Get the ACTION for the current annotation
PdfDictionary AnnotationAction = AnnotationDictionary.GetAsDict(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);
string url1 = Destination.ToString();
}
}
}
//}
}
}
}
【问题讨论】:
-
与列出没有格式的步骤相比,提供一个可以立即重现问题的文件的链接会增加您的机会
-
这发生在任何文件上。使用 TOC 创建一个单词并将其转换为 PDF。
-
链接可以有 Destinatoons 而不是操作...
-
@mkl 请详细说明,能否提供到达目的地的路径?
-
@AlfonsoCaruana 由于很难在评论中详细说明,我在回答中这样做了,见下文。
标签: c# pdf itext tableofcontents