2017-08-30 26 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(); 
     } 
    } 
}