乾淨地打掃一份文件

有時你可能需要移除沒有使用的或重複的資訊,以降低輸出文件的大小和處理時間。

儘管您可以手動 tìm並移除未使用的資料,例如風格或清單,或是重複資訊,但使用 Aspose.Words 提供的功能與功能來進行此動作會更方便。

CleanupOptions類別允許您指定資料清理的選項。 要從文件中移除此類重複或未使用的風格和清單,您可以使用 Cleanup 方法。

從文件中移除未使用的資訊

您可以使用 UnusedStylesUnusedBuiltinStyles 屬性來檢測並移除被標記為『未使用的』的風格。

您可以使用 UnusedLists 屬性來檢測並移除標記為未使用的的清單與清單定義。

以下範例顯示如何從文件中移除未使用的樣式:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(MyDir + "Unused styles.docx");
// Combined with the built-in styles, the document now has eight styles.
// A custom style is marked as "used" while there is any text within the document
// formatted in that style. This means that the 4 styles we added are currently unused.
Console.WriteLine($"Count of styles before Cleanup: {doc.Styles.Count}\n" +
$"Count of lists before Cleanup: {doc.Lists.Count}");
// Cleans unused styles and lists from the document depending on given CleanupOptions.
CleanupOptions cleanupOptions = new CleanupOptions { UnusedLists = false, UnusedStyles = true };
doc.Cleanup(cleanupOptions);
Console.WriteLine($"Count of styles after Cleanup was decreased: {doc.Styles.Count}\n" +
$"Count of lists after Cleanup is the same: {doc.Lists.Count}");
doc.Save(ArtifactsDir + "WorkingWithDocumentOptionsAndSettings.CleanupUnusedStylesAndLists.docx");

從文件中移除重複資訊

您也可以使用 DuplicateStyle 屬性將所有重複的樣式替換為原始樣式,並將複製文件從文書中移除。

接下來的程式碼範例說明了如何從文件中移除重複的樣式。

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(MyDir + "Document.docx");
// Count of styles before Cleanup.
Console.WriteLine(doc.Styles.Count);
// Cleans duplicate styles from the document.
CleanupOptions options = new CleanupOptions { DuplicateStyle = true };
doc.Cleanup(options);
// Count of styles after Cleanup was decreased.
Console.WriteLine(doc.Styles.Count);
doc.Save(ArtifactsDir + "WorkingWithDocumentOptionsAndSettings.CleanupDuplicateStyle.docx");