Hi Team,
How to delete specific pages from a Word document
For example, if you have a 10-page document and want to delete pages 2, 5, 7, and 10, is it possible? If so, please share the relevant code.
Regards,
Mahi
Hi Team,
How to delete specific pages from a Word document
For example, if you have a 10-page document and want to delete pages 2, 5, 7, and 10, is it possible? If so, please share the relevant code.
Regards,
Mahi
@Mahi39 There is no direct way to remove pages from MS Word document. However, Aspose.Words provides a method for extracting page range from the document Document.ExtractPages. So to achieve what you need you can use code like the following:
Document doc = new Document("C:\\Temp\\in.docx");
Document doc1 = GetPagesExcept(doc, new int[] {0,2,8});
doc1.save("C:\\Temp\\out.docx");
private static Document GetPagesExcept(Document doc, int[] excludePages) throws Exception
{
int startPageIndex = 0;
int pageCount = doc.getPageCount();
if(excludePages[excludePages.length-1]>=pageCount)
throw new IndexOutOfBoundsException("Page index is out of range");
Document mainDocument = (Document)doc.deepClone(false);
for (int page : excludePages) {
if(page==startPageIndex) {
startPageIndex++;
continue;
}
int chunkCount = page - startPageIndex;
Document chunk = doc.extractPages(startPageIndex, chunkCount);
mainDocument.appendDocument(chunk, ImportFormatMode.USE_DESTINATION_STYLES);
startPageIndex = page+1;
}
return mainDocument;
}