20-添加换行符和换页符
15.3.8 添加换行符和换页符
要添加换行符(而不是开始一个新的段落),可以在 Run
对象上调用 add_break()
方法,换行符将出现在它后面。如果希望添加换页符,可以将 docx.text.WD_BREAK.PAGE
作为唯一的参数,传递给 add_break()
,就像下面代码中间所做的一样:
>>> doc = docx.Document()
>>> doc.add_paragraph('This is on the first page!')
<docx.text.Paragraph object at 0x0000000003785518>
❶ >>> doc.paragraphs[0].runs[0].add_break(docx.enum.text.WD_BREAK.PAGE)
>>> doc.add_paragraph('This is on the second page!')
<docx.text.Paragraph object at 0x00000000037855F8>
>>> doc.save('twoPage.docx')
这创建了一个两页的Word文档,第一页上是This is on the first page!,第二页上是This is on the second page!。虽然在文本This is on the first page!之后,第一页还有大量的空间,但是我们在第一段的第一个 Run
之后插入了分页符,强制下一段落出现在新的页面中❶。