PDFKit.NET如何根据PDF文件里的书签对PDF进行分割

作者:控件中国网   出处:控件中国网   2015-09-01 10:16:46   阅读:7

这篇文章主要介绍如何使用PDFKit.NET利用PDF文件里存在的书签,对PDF文件进行分割,也就是说有多少个书签就把PDF分割成多少个单独的PDF文档,具体可以参考下面的代码:

 1 using (FileStream file = new FileStream(
 2             @"..\..\..\inputDocuments\AnnualReportToCongress.pdf",
 3             FileMode.Open, FileAccess.Read))
 4 {
 5     Document document = new Document(file);
 6
 7     BookmarkCollection bookmarks = document.Bookmarks;
 8     for (int index = 0, fromPage = 0; index < bookmarks.Count; index++)
 9     {
10         // determine last page of next part
11         int toPage = -1;
12         if (index == bookmarks.Count - 1)
13         {
14             // last bookmark - so just append all remaining pages
15             toPage = document.Pages.Count;
16         }
17         else
18         {
19             // not the last bookmark - append up to the page where
20             // the next bookmark points to
21             GoToAction action = bookmarks[index + 1].Actions[0] as GoToAction;
22             if (null != action)
23             {
24                 InternalDestination destination = action.Destination as InternalDestination;
25                 if (null != destination)
26                 {
27                     toPage = destination.Page.Index;
28                 }
29             }
30         }
31
32         // create a new part
33         if (-1 != toPage)
34         {
35             Document part = new Document();
36             foreach (Page p in document.Pages)
37             {
38                 part.Pages.Add(p.Clone());
39             }
40
41             string title = bookmarks[index].Title;
42             using (FileStream fileOut = new FileStream(
43                         string.Format(@"..\..\{0}.pdf", title),
44                         FileMode.Create, FileAccess.Write))
45             {
46                 Console.WriteLine("Writing {0} - {1} of {2}", title, index, bookmarks.Count);
47                 part.Write(fileOut);
48             }
49
50             fromPage = toPage;
51         }
52     }
53 }

Copyright© 2006-2015 ComponentCN.com all rights reserved.重庆磐岩科技有限公司(控件中国网) 版权所有 渝ICP备12000264号 法律顾问:元炳律师事务所
客服软件
live chat