Adding Page Borders, Line Numbers, and Gutters to Word Documents Using Python
本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。
Title: Adding Page Borders, Line Numbers, and Gutters to Word Documents Using Python
Contracts, tender documents, and court filings usually have fixed expectations about the page itself: a frame around the text, a number on every line so clauses can be cited, and extra space on one side for binding. None of that is hard to click through in Word, but a single file often contains dozens of sections that all need to match, and a batch job would mean repeating the same clicks hundreds of times. Page borders, line numbers, and gutters all belong to the same family of settings — section-level page setup. Once written into the file, they produce exactly what a person would get by hand, which makes them a good fit for document generation. This article uses Spire.Doc for Python to cover all three: a single style for the whole frame and per-side styling, line numbering with a chosen start value and interval, and gutter width and position, plus a few details that only show up when the settings are written to disk.
合同、招标书和法庭文件通常对页面本身有固定的要求:文本周围的边框、每一行的编号以便引用条款,以及一侧用于装订的额外空间。在 Word 中通过点击设置这些并不困难,但单个文件通常包含数十个需要保持一致的节,而批量处理意味着要重复数百次相同的点击。页面边框、行号和装订线都属于同一类设置——节级页面设置。一旦写入文件,它们产生的结果与人工操作完全一致,这使得它们非常适合文档生成。本文使用 Spire.Doc for Python 来涵盖这三项内容:整个框架的单一样式及各侧样式、具有选定起始值和间隔的行编号、装订线宽度和位置,以及一些仅在设置写入磁盘时才会显现的细节。
Setting Up the Environment Install Spire.Doc and import the modules: pip install Spire.Doc from spire.doc import * from spire.doc.common import * All three settings live on a section and are reached through document.Sections[i].PageSetup. A document with several sections needs the settings applied to each one.
设置环境 安装 Spire.Doc 并导入模块: pip install Spire.Doc from spire.doc import * from spire.doc.common import * 这三项设置都存在于节(section)中,并通过 document.Sections[i].PageSetup 进行访问。如果文档包含多个节,则需要将设置应用于每一个节。
Adding a Page Border to the Whole Document The straightforward approach is to give all four sides the same style: from spire.doc import * from spire.doc.common import * document = Document() section = document.AddSection() paragraph = section.AddParagraph() paragraph.AppendText(“The frame around this page is defined by the page border settings.”)
Add page borders with a special style and colour.
borders = document.Sections[0].PageSetup.Borders borders.BorderType = BorderStyle.DoubleWave borders.Color = Color.get_LightSeaGreen()
Set the space between the border and the text (0-31 points).
borders.Left.Space = 24 borders.Right.Space = 24 document.SaveToFile(“PageBorders.docx”, FileFormat.Docx2013) document.Close() BorderType applies to all four sides at once and Color changes them together; individual sides can then be adjusted afterwards. Two things tend to trip people up. First, BorderType and Color are writable properties in the current version, so they take an assignment; calling them like methods (BorderType(BorderStyle.DoubleWave)) raises a TypeError. Second, Space is the distance between the border and the body text, measured in points, and it only accepts values from 0 to 31 — passing 50 throws an Arg_ArgumentOutOfRangeException.
为整个文档添加页面边框 最直接的方法是为四条边赋予相同的样式: from spire.doc import * from spire.doc.common import * document = Document() section = document.AddSection() paragraph = section.AddParagraph() paragraph.AppendText(“The frame around this page is defined by the page border settings.”)
添加具有特殊样式和颜色的页面边框。
borders = document.Sections[0].PageSetup.Borders borders.BorderType = BorderStyle.DoubleWave borders.Color = Color.get_LightSeaGreen()
设置边框与文本之间的间距(0-31 磅)。
borders.Left.Space = 24 borders.Right.Space = 24 document.SaveToFile(“PageBorders.docx”, FileFormat.Docx2013) document.Close() BorderType 会同时应用于四条边,Color 也会同时改变它们;之后可以对各个边进行单独调整。有两点容易让人困惑。首先,在当前版本中,BorderType 和 Color 是可写属性,因此它们接受赋值;像调用方法一样调用它们(例如 BorderType(BorderStyle.DoubleWave))会引发 TypeError。其次,Space 是边框与正文之间的距离,以磅为单位,且仅接受 0 到 31 之间的值——传入 50 会抛出 Arg_ArgumentOutOfRangeException。
Styling Each Side Separately Formal documents often want a heavy top rule, a double rule at the bottom, and light dotted sides. Each side carries its own set of properties: from spire.doc import * from spire.doc.common import * document = Document() section = document.AddSection() paragraph = section.AddParagraph() paragraph.AppendText(“Only the top and bottom of this page are framed.”) borders = document.Sections[0].PageSetup.Borders
Style the four sides one by one.
borders.Top.BorderType = BorderStyle.Thick borders.Top.Color = Color.get_Red() borders.Top.LineWidth = 2.0 borders.Top.Space = 24 borders.Bottom.BorderType = BorderStyle.Double borders.Bottom.Color = Color.get_Blue() borders.Bottom.LineWidth = 1.5 borders.Bottom.Space = 24 borders.Left.BorderType = BorderStyle.Dot borders.Left.Color = Color.get_Gray() borders.Left.LineWidth = 1.0 borders.Right.BorderType = BorderStyle.Dot borders.Right.Color = Color.get_Gray() borders.Right.LineWidth = 1.0
Measure the border from the text edge instead of the paper edge.
document.Sections[0].PageSetup.PageBorderOffsetFrom = PageBorderOffsetFrom.Text
Draw the frame on every page of the section.
document.Sections[0].PageSetup.PageBordersApplyType = PageBordersApplyType.AllPages document.SaveToFile(“PageBordersSides.docx”, FileFormat.Docx2013) document.Close() Each side exposes BorderType, Color, LineWidth, and Space. LineWidth is measured in points: a value of 2.0 is stored as 16 because the file format counts eighths of a point. Three section-level switches are worth knowing: PageBorderOffsetFrom decides what the border is measured from. The default is the paper edge (PageEdge); switching to Text anchors it to the body text, and the two produce visibly different results. PageBordersApplyType controls where the frame appears: AllPages, FirstPage, and AllExceptFirstPage cover every page, the first page only, or everything but the first page. IsFrontPageBorder is easy to misread. It does not mean “show a border on the first page” — it controls the stacking order, and setting it to True draws the border in front of the text. To remove an existing frame, set the style back to BorderStyle.none; reading borders.NoBorder then returns True.
单独设置每一边的样式 正式文档通常需要顶部加粗线条、底部双线条以及两侧轻细虚线。每一边都有自己的一套属性: from spire.doc import * from spire.doc.common import * document = Document() section = document.AddSection() paragraph = section.AddParagraph() paragraph.AppendText(“Only the top and bottom of this page are framed.”) borders = document.Sections[0].PageSetup.Borders
逐一设置四边的样式。
borders.Top.BorderType = BorderStyle.Thick borders.Top.Color = Color.get_Red() borders.Top.LineWidth = 2.0 borders.Top.Space = 24 borders.Bottom.BorderType = BorderStyle.Double borders.Bottom.Color = Color.get_Blue() borders.Bottom.LineWidth = 1.5 borders.Bottom.Space = 24 borders.Left.BorderType = BorderStyle.Dot borders.Left.Color = Color.get_Gray() borders.Left.LineWidth = 1.0 borders.Right.BorderType = BorderStyle.Dot borders.Right.Color = Color.get_Gray() borders.Right.LineWidth = 1.0
从文本边缘而不是纸张边缘测量边框。
document.Sections[0].PageSetup.PageBorderOffsetFrom = PageBorderOffsetFrom.Text
在该节的每一页上绘制边框。
document.Sections[0].PageSetup.PageBordersApplyType = PageBordersApplyType.AllPages document.SaveToFile(“PageBordersSides.docx”, FileFormat.Docx2013) document.Close() 每一边都公开了 BorderType、Color、LineWidth 和 Space 属性。LineWidth 以磅为单位:值 2.0 被存储为 16,因为文件格式以 1/8 磅为计数单位。有三个节级开关值得了解:PageBorderOffsetFrom 决定了边框的测量基准。默认值是纸张边缘(PageEdge);切换到 Text 则将其锚定在正文文本上,两者会产生明显的视觉差异。PageBordersApplyType 控制框架出现的位置:AllPages、FirstPage 和 AllExceptFirstPage 分别涵盖每一页、仅第一页或除第一页外的所有页面。IsFrontPageBorder 容易被误解。它并不意味着“在第一页显示边框”——它控制的是堆叠顺序,将其设置为 True 会将边框绘制在文本前方。要移除现有框架,请将样式设置回 BorderStyle.none;此时读取 borders.NoBorder 将返回 True。
Adding Line Numbers Line numbers give every clause a reference that can be cited in correspondence and disputes: from spire.doc import * from spire.doc.common import * document = Document() section = document.AddSection()
Enough rendered lines for the interval to actually show a number.
for i in range(1, 15): paragraph = section.AddParagraph() paragraph.AppendText(f”Clause {i}: the parties agree to the following terms and conditions.”) pageSetup = document.Sections[0].PageSetup
Start counting from 1.
pageSetup.LineNumberingStartValue = 1
Only every sixth line is numbered.
pageSetup.LineNumberingStep = 6
Distance between the number and the text, in points.
pageSetup.LineNumberingDistanceFromText = 40
Keep counting across pages; the other modes are RestartPage and RestartSection.
pageSetup.LineNumberingRestartMode = LineNumberingRestartMode.Continuous document.SaveToFile(“LineNumbers.docx”, FileFormat.Docx2013) document.Close() Each parameter covers one decision: LineNumberingStartValue is the number given to the first counted line. The file stores a zero-based offset, so a setting of 1 is written as 0 and a setting of 5 as 4 — do not read the stored value back as the line number itself. LineNumberingStep is the interval: 6 means lines 6, 12, 18
添加行号 行号为每一条条款提供了可在信函和争议中引用的参考: from spire.doc import * from spire.doc.common import * document = Document() section = document.AddSection()
足够的渲染行数以使间隔能够显示编号。
for i in range(1, 15): paragraph = section.AddParagraph() paragraph.AppendText(f”Clause {i}: the parties agree to the following terms and conditions.”) pageSetup = document.Sections[0].PageSetup
从 1 开始计数。
pageSetup.LineNumberingStartValue = 1
仅每六行编号一次。
pageSetup.LineNumberingStep = 6
编号与文本之间的距离,以磅为单位。
pageSetup.LineNumberingDistanceFromText = 40
跨页持续计数;其他模式包括 RestartPage 和 RestartSection。
pageSetup.LineNumberingRestartMode = LineNumberingRestartMode.Continuous document.SaveToFile(“LineNumbers.docx”, FileFormat.Docx2013) document.Close() 每个参数对应一个决策:LineNumberingStartValue 是赋予第一个被计数行的编号。文件存储的是一个从零开始的偏移量,因此设置 1 会被写入为 0,设置 5 会被写入为 4——请勿将存储的值直接读取为行号本身。LineNumberingStep 是间隔:6 表示第 6、12、18 行。