如何使用iTextSharp创建命名目的地? [英] How can I create named destinations with iTextSharp?
问题描述
我正在尝试使用C#和iTextSharp 5库将PDF书签转换为命名目的地。不幸的是,iTextSharp似乎没有将命名目标写入目标PDF文件。
I am trying to convert PDF bookmarks into named destinations with C# and iTextSharp 5 library. Unfortunately iTextSharp seems not to write named destinations into the target PDF file.
using System;
using System.Collections.Generic;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.IO;
namespace PDFConvert
{
class Program
{
static void Main(string[] args)
{
String InputPdf = @"test.pdf";
String OutputPdf = "out.pdf";
PdfReader reader = new PdfReader(InputPdf);
var fileStream = new FileStream(OutputPdf, FileMode.Create, FileAccess.Write, FileShare.None);
var list = SimpleBookmark.GetBookmark(reader);
PdfStamper stamper = new PdfStamper(reader, fileStream);
foreach (Dictionary<string, object> entry in list)
{
object o;
entry.TryGetValue("Title", out o);
String title = o.ToString();
entry.TryGetValue("Page", out o);
String location = o.ToString();
String[] aLoc = location.Split(' ');
int page = int.Parse(aLoc[0]);
PdfDestination dest = new PdfDestination(PdfDestination.XYZ, float.Parse(aLoc[2]), float.Parse(aLoc[3]), float.Parse(aLoc[4]));
stamper.Writer.AddNamedDestination(title, page, dest);
// stamper.Writer.AddNamedDestinations(SimpleNamedDestination.GetNamedDestination(reader, false), reader.NumberOfPages);
}
stamper.Close();
reader.Close();
}
}
}
我已经尝试使用 PdfWriter
而不是 PdfStamper
,结果相同。我肯定会调用 stamper.Writer.AddNamedDestination(title,page,dest);
但我的目标文件中没有NamedDestinations的迹象。
I already tried to use PdfWriter
instead of PdfStamper
, with the same result. I have definitely calls of stamper.Writer.AddNamedDestination(title, page, dest);
but no sign of NamedDestinations in my target file.
推荐答案
我找到了一个使用iText 7而不是5的解决方案。不幸的是语法完全不同。在下面的代码中,我只考虑我的PDF的二级书签(大纲)。
I have found a solution using iText 7 instead of 5. Unfortunately the syntax is completely different. In my code below I only consider the second level Bookmarks ("Outline") of my PDF.
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Navigation;
using System;
namespace PDFConvert
{
class Program
{
static void Main(string[] args)
{
String InputPdf = @"test.pdf";
String OutputPdf = "out.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfReader(InputPdf), new PdfWriter(OutputPdf));
PdfOutline outlines = pdfDoc.GetOutlines(false);
// first level
foreach (var outline in outlines.GetAllChildren())
{
// second level
foreach (var second in outline.GetAllChildren())
{
String title = second.GetTitle();
PdfDestination dest = second.GetDestination();
pdfDoc.AddNamedDestination(title, dest.GetPdfObject());
}
}
pdfDoc.Close();
}
}
}
这篇关于如何使用iTextSharp创建命名目的地?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!