2017-08-30 27 views
0

我想用C#和iTextSharp 5库将PDF书签转换为命名的目的地。不幸的是,iTextSharp似乎不会将命名的目标写入目标PDF文件。如何使用iTextSharp创建命名的目的地?

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的标志。

+0

我删除了你的问题的一部分,因为它会冒险,你得到一个结束标志()。您知道iText(Sharp)带有AGPL许可证,*不是* GPL或BSD? –

回答

1

我找到了使用iText 7而不是5的解决方案。不幸的是,语法完全不同。在我的代码中,我只考虑了我的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(); 
     } 
    } 
}