11using Syncfusion . DocIO ;
22using Syncfusion . DocIO . DLS ;
3+ using Syncfusion . Compression . Zip ;
34using System . IO ;
45
56namespace Split_a_document_by_bookmark
@@ -11,27 +12,34 @@ static void Main(string[] args)
1112 //Load an existing Word document.
1213 using ( FileStream fileStreamPath = new FileStream ( Path . GetFullPath ( @"Data/Template.docx" ) , FileMode . Open , FileAccess . Read , FileShare . ReadWrite ) )
1314 {
14- using ( WordDocument document = new WordDocument ( fileStreamPath , FormatType . Docx ) )
15+ using ( ZipArchive zipArchive = new ZipArchive ( ) )
1516 {
16- //Create the bookmark navigator instance to access the bookmark.
17- BookmarksNavigator bookmarksNavigator = new BookmarksNavigator ( document ) ;
18- BookmarkCollection bookmarkCollection = document . Bookmarks ;
19- //Iterate each bookmark in Word document.
20- foreach ( Bookmark bookmark in bookmarkCollection )
17+
18+
19+ using ( WordDocument document = new WordDocument ( fileStreamPath , FormatType . Docx ) )
2120 {
22- //Move the virtual cursor to the bookmark.
23- bookmarksNavigator . MoveToBookmark ( bookmark . Name ) ;
24- //Get the bookmark content as WordDocumentPart.
25- WordDocumentPart documentPart = bookmarksNavigator . GetContent ( ) ;
26- //Save the WordDocumentPart as separate Word document
27- using ( WordDocument newDocument = documentPart . GetAsWordDocument ( ) )
21+ //Create the bookmark navigator instance to access the bookmark.
22+ BookmarksNavigator bookmarksNavigator = new BookmarksNavigator ( document ) ;
23+ BookmarkCollection bookmarkCollection = document . Bookmarks ;
24+ //Iterate each bookmark in Word document.
25+ foreach ( Bookmark bookmark in bookmarkCollection )
2826 {
29- //Save the Word document to file stream.
30- using ( FileStream outputFileStream = new FileStream ( Path . GetFullPath ( @"Output/" + bookmark . Name + ".docx" ) , FileMode . Create , FileAccess . ReadWrite ) )
27+ //Move the virtual cursor to the bookmark.
28+ bookmarksNavigator . MoveToBookmark ( bookmark . Name ) ;
29+ //Get the bookmark content as WordDocumentPart.
30+ WordDocumentPart documentPart = bookmarksNavigator . GetContent ( ) ;
31+ //Save the WordDocumentPart as separate Word document
32+ using ( WordDocument newDocument = documentPart . GetAsWordDocument ( ) )
3133 {
32- newDocument . Save ( outputFileStream , FormatType . Docx ) ;
34+ //Save the Word document to MemoryStream.
35+ MemoryStream memoryStream = new MemoryStream ( ) ;
36+ newDocument . Save ( memoryStream , FormatType . Docx ) ;
37+ //Add the Word document to Zip archive.
38+ zipArchive . AddItem ( bookmark . Name + ".docx" , memoryStream , true , Syncfusion . Compression . FileAttributes . Normal ) ;
3339 }
3440 }
41+
42+ zipArchive . Save ( Path . GetFullPath ( @"Output/Split-by-Bookmark.zip" ) ) ;
3543 }
3644 }
3745
0 commit comments