这篇文章主要介绍如何使用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 }