python-添加页眉,页脚,水印
import json
import os
import win32com
from docx import Document
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.shared import Pt, Inches, Cm
from win32com.client import Dispatch
class DocReport(object):
def __init__(self, **kwargs):
self.file = kwargs.get("file", None)
if self.file is None:
self.file = os.path.abspath("report.docx")
self.document = Document()
def addHeader(self, **kwargs):
"""
添加页眉
:return:
"""
document = self.document
text = kwargs.get("text", None)
image = kwargs.get("image", None)
section = document.sections[0]
header = section.header
if text is not None:
paragraph = header.paragraphs[0]
run = paragraph.add_run()
run.add_text(text)
if image is not None:
paragraph = header.paragraphs[0]
run = paragraph.add_run()
run.add_picture(image)
def addFooter(self, **kwargs):
"""
添加页脚
:return:
"""
document = self.document
text = kwargs.get("text", None)
image = kwargs.get("image", None)
section = document.sections[0]
footer = section.footer
if text is not None:
paragraph = footer.paragraphs[0]
run = paragraph.add_run()
run.add_text(text)
if image is not None:
paragraph = footer.paragraphs[0]
run = paragraph.add_run()
run.add_picture(image, width=Inches(2))
paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT
def getWordAddWatermark(self, file, content=""):
self.document.save(self.file)
wordApp = win32com.client.DispatchEx("Word.Application")
wordApp.Visible = True
wordApp.DisplayAlerts = False
wordApp.Documents.Open(os.path.abspath(file))
activeDoc = wordApp.ActiveDocument
wordApp.ActiveWindow.ActivePane.View.SeekView = 1
for page in range(wordApp.ActiveWindow.Panes(1).Pages.Count):
width = 80 * len(content)
wordApp.Selection.HeaderFooter.Shapes.AddTextEffect(0, content, "等线", 1, False, False, 0, 0).Select()
wordApp.Selection.ShapeRange.Line.Visible = False
wordApp.Selection.ShapeRange.Fill.Transparency = 0.2
wordApp.Selection.ShapeRange.Fill.ForeColor = 0
wordApp.Selection.ShapeRange.Fill.ForeColor.RGB = 12632256
wordApp.Selection.ShapeRange.Fill.ForeColor.TintAndShade = 0
wordApp.Selection.ShapeRange.Rotation = 350
wordApp.Selection.ShapeRange.LockAspectRatio = True
wordApp.Selection.ShapeRange.Width = width
wordApp.Selection.ShapeRange.WrapFormat.Type = 3
wordApp.Selection.ShapeRange.WrapFormat.Side = 3
wordApp.Selection.ShapeRange.Left = 20
wordApp.Selection.ShapeRange.Top = 300
wordApp.ActiveWindow.ActivePane.View.SeekView = 0
activeDoc.Save()
activeDoc.Close()
wordApp.Quit()