2014年10月21日 星期二

健保e化抽審-1(PDF Merge & Bookmark)

private void button17_Click(object sender, EventArgs e)
{
  Dictionary<PrintDocument, byte[]> myFiles = new Dictionary<PrintDocument, byte[]>();

  myFiles.Add(new PrintDocument { Title = "title1", ChapterName = "chapterName1", ChapterNumber = 1 }, File.ReadAllBytes(@"C:\temp\title1.pdf"));
  myFiles.Add(new PrintDocument { Title = "title2", ChapterName = "chapterName1", ChapterNumber = 1 }, File.ReadAllBytes(@"C:\temp\title2.pdf"));
  myFiles.Add(new PrintDocument { Title = "title3", ChapterName = "chapterName1", ChapterNumber = 1 }, File.ReadAllBytes(@"C:\temp\title3.pdf"));

  File.WriteAllBytes(@"C:\temp\test.pdf", MergeFilesAndAddBookmarks(myFiles));
}

public static byte[] MergeFilesAndAddBookmarks(Dictionary<PrintDocument, byte[]> sourceFiles)
{
  using (var ms = new MemoryStream())
  {
    using (var document = new iTextSharp.text.Document())
    {
      using (var copy = new iTextSharp.text.pdf.PdfCopy(document, ms))
      {
        //Order the files by chapternumber
        var files = sourceFiles.GroupBy(f => f.Key.ChapterNumber);

        document.Open();
        
        var outlines = new List<Dictionary<string, object>>();

        var pageIndex = 1;

        foreach (var chapterGroup in files)
        {
          var map = new Dictionary<string, object>();
          outlines.Add(map);
          map.Add("Title", chapterGroup.First().Key.ChapterName);
          var kids = new List<Dictionary<string, object>>();
          map.Add("Kids", kids);

          foreach (var sourceFile in chapterGroup)
          {
            using (var reader = new iTextSharp.text.pdf.PdfReader(sourceFile.Value))
            {
              //Add the pages
              var n = reader.NumberOfPages;

              for (var page = 0; page < n;)
              {
                if (page == 0)
                {
                  var kid = new Dictionary<string, object>();
                  kids.Add(kid);
                  kid["Title"] = sourceFile.Key.Title;
                  kid["Action"] = "GoTo";
                  kid["Page"] = String.Format("{0} Fit", pageIndex);
                }
                copy.AddPage(copy.GetImportedPage(reader, ++page));
              }

              pageIndex += n;
              reader.Close();
            }
          }
        }

        copy.Outlines = outlines;
        document.Close();
        copy.Close();
        ms.Close();
      }
    }
    return ms.ToArray();
  }
}

public class PrintDocument
{
  public string Title { get; set; }
  public string ChapterName { get; set; }
  public int ChapterNumber { get; set; }
}
參考資料
[1] 使用ASP .NET (C#) 產生PDF檔的好幫手—iTextSharp library (上)
[2] 使用ASP .NET (C#) 產生PDF檔的好幫手—iTextSharp library (下)

沒有留言:

張貼留言