在Word 文档中,文本框是一种可移动和可调整大小的容器,用于输入文本、图片等内容。又要分为横排文本框和竖排文本框两种布局。用户在不需要重新排版的情况下,可以轻松将文本框的内容移到不同的位置。在这篇文章中,我们将介绍如何使用 Spire.Doc for Python 在 Word 中插入文本框、删除文本框。
- Python新建Word文本框
- Python删除 Word文本框
安装 Spire.Doc for Python
本教程需要 Spire.Doc for Python 和 plum-dispatch v1.7.4。您可以通过以下 pip 命令将它们轻松安装到 VS Code 中。
pip install Spire.Doc
Python新建Word文本框
Spire.Doc for Python 提供Paragraph.AppendTextBox() 方法可以将文本框添加到指定段落。然后往文本框内插入文本、图片等,也支持设置文本框的环绕方式及相关属性。创建文本框的详细步骤如下:
- 创建一个 Document 对象,并通过 Document.LoadFromFile() 加载文档。
- 通过 Document.Sections.get_Item() 获取特定的章节。
- 使用 Section.Paragraphs[] 属性获取指定的段落。
- 使用 Paragraph.AppendTextBox() 在指定段落添加文本框
- 通过 TextBox 对象下的其他属性设置文本框的样式和位置。
- 试用 TextBox.Body.AddParagraph() 在文本框内添加段落
- 使用 Paragraph.AppendPicture() 添加图片,并设置图片宽高。
- 再次使用 TextBox.Body.AddParagraph() 在文本框中添加段落,之后在段落内添加文本内容
- 使用 Document.SaveToFile() 方法保存文件。
- 关闭并释放 Document 资源
Python:
from spire.doc import *
from spire.doc.common import *
outputFile = "Textbox.docx"
# 创建Document对象并加载文档
document = Document()
document.LoadFromFile("F:\\data\\川菜.docx")
# 获取第一个section
section = document.Sections.get_Item(0)
# 通过下标获取section的指定段落
paragraph = section.Paragraphs[1] if section.Paragraphs.Count > 0 else section.AddParagraph()
# 插入文本框,并设置宽高
textBox = paragraph.AppendTextBox(240, 200)
# 设置文本框环绕模式和水平位置
textBox.TextWrappingStyle = TextWrappingStyle.Square
textBox.HorizontalAlignment = ShapeHorizontalAlignment.Right
# 设置文本框轮廓样式
textBox.Format.LineColor = Color.get_Gray()
textBox.Format.LineStyle = TextBoxLineStyle.Simple
# 设置文本框的填充颜色
textBox.Format.FillColor = Color.get_DarkSeaGreen()
# 在文本框中添加段落
para = textBox.Body.AddParagraph()
# 在段落内部的第一个位置插入图片并居中
pic = para.AppendPicture("F:\\data\\冒菜.jpg")
para.Format.HorizontalAlignment = HorizontalAlignment.Center
# 设定图片宽高
pic.Width = 200
pic.Height = 150
# 再添加一个段落设置文本
para = textBox.Body.AddParagraph()
# 在段落内添加文本并设置居中
txtrg = para.AppendText("冒菜")
para.Format.HorizontalAlignment = HorizontalAlignment.Center
# 设置字体样式
txtrg.CharacterFormat.FontName = "simsun"
txtrg.CharacterFormat.FontSize = 14
txtrg.CharacterFormat.TextColor = Color.get_White()
# 保存文件
document.SaveToFile(outputFile, FileFormat.Docx)
# 关闭并释放资源
document.Close()
document.Dispose()
运行后的文本框效果图:
Python 删除 Word 中的文本框
使用Spire.Doc for Python仅需三行代码即可删除word文档里面的文本框。开发者可以依自己的项目需求,删除指定文本框和一次性删除全部文本框:
- 创建一个 Document 对象。
- 使用 Document.LoadFromFile() 方法加载一个 Word 文件。
- 通过 Document.TextBoxes.RemoveAt() 方法移除指定索引的文本框或者使用 Document.TextBoxes.Clear() 方法删除全部文本框。
- 使用 Document.SaveToFile() 保存文档。
- 关闭并释放资源。
Python:
from spire.doc import *
from spire.doc.common import *
outputFile = "移除文本框.docx"
inputFile = "F:\data\Textbox.docx"
# 创建Document对象并加载文件
doc = Document()
doc.LoadFromFile(inputFile)
# 获取文档中的文本框集合
doc.TextBoxes.RemoveAt(0)
# 清除所有文本框
# Doc.TextBoxes.Clear()
# 保存文件
doc.SaveToFile(outputFile, FileFormat.Docx)
# 关闭并释放文件
doc.Close()
doc.Dispose()
本文完