本文介绍如何使用 Python 删除 Word 中的空白页。它包含设置环境的详细信息、步骤列表和可运行的示例代码,显示如何使用 Python 删除 Word 中的空白页面。可以按原样使用示例代码来执行任务,但是,如果需要,您可以通过添加不同的条件来即兴发挥。
使用Python删除Word中空白页的步骤
- 设置开发环境使用Aspose.Words for Python 通过 .NET删除空白页
- 将源 Word 文件加载到其中包含空白页的 Document 对象中
- 遍历文档中的所有页面并检查每个部分的内容
- 检查文本和图像是否存在并准备空白页面列表
- 创建一个新的空Word文档
- Append 使用空白页面列表从源 Word 文件中获取包含某些内容的所有页面
- 保存生成的没有空白页的Word文件
这些步骤解释了如何使用Python删除空白Word页面的过程。在此过程中,将加载源 Word 文件,并检查每个页面中的所有部分是否包含文本或图像,以准备空白页面列表。最后,创建一个新文档,并将除空白页之外的所有页面添加到这个新的空文档中。
使用Python删除Word中空白页的代码
import aspose.words as aw | |
import aspose.pydrawing as drawing | |
# Load the license | |
wordLic = aw.License() | |
wordLic.set_license("License.lic") | |
# Load the Word file having blank pages in it | |
originalDocWithFewBlankPages = aw.Document("input.docx") | |
# Declare an array for blank page numbers | |
listOfBlankPageNumbers = [] | |
listOfBlankPageNumbers.append(-1) | |
# Get total pages in the souce Word file | |
totalPagesInOriginalDoc = originalDocWithFewBlankPages.page_count | |
for iCount in range(0, totalPagesInOriginalDoc): # This will loop for page count | |
# Extract each page one by one | |
DocWithOnePage = originalDocWithFewBlankPages.extract_pages(iCount, 1) | |
shapesCounter = 0 | |
pageText = "" | |
# Check text and images in each section | |
for docSection in DocWithOnePage.sections: | |
docSection = docSection.as_section() | |
pageText = pageText + docSection.body.to_string(aw.SaveFormat.TEXT) | |
shapesCounter += docSection.body.get_child_nodes(aw.NodeType.SHAPE, True).count | |
# Check if no content is there | |
if (not pageText) and shapesCounter == 0: | |
# Store the index of blank page numbers | |
listOfBlankPageNumbers.append(iCount) | |
listOfBlankPageNumbers.append(totalPagesInOriginalDoc) | |
# Create a single page document with default forrmat | |
nonEmptyDocument = originalDocWithFewBlankPages.clone(False).as_document() | |
# Clean the document | |
nonEmptyDocument.remove_all_children() | |
# Append the pages with content to the new document | |
for iCount in range(1, len(listOfBlankPageNumbers)): | |
index = listOfBlankPageNumbers[iCount - 1] + 1 | |
count = listOfBlankPageNumbers[iCount] - index | |
if count > 0: | |
nonEmptyDocument.append_document( | |
originalDocWithFewBlankPages.extract_pages(index, count), | |
aw.ImportFormatMode.KEEP_SOURCE_FORMATTING) | |
# Save the document having some content in it | |
nonEmptyDocument.save("NonEmptyPages.docx") | |
print ("Blank pages deleted successfully") |
此示例代码演示如何使用 Python 从 Word 中删除空白页面。在此示例代码中,对每个部分的正文文本和节点类型 SHAPE 进行了测试,但您可以使用其他类型(如 TABLE、COMMENT、FORM_FIELD、SMART_TAG 等)来识别空白页。 append_document() 方法用于将页面添加到新的 Word 文件,而它包含各种重载方法,允许使用不同的参数来自定义页面插入过程。
本文教会了我们如何使用 Python 删除 Word 中的空白页。如果您想在 Word 文件中添加页码,请参阅 如何使用Python在Word中输入页码 上的文章。