# 怎么用Python代碼實現給Word文檔蓋章
## 引言
在數字化辦公場景中,自動生成和修改Word文檔的需求日益增多。其中"文檔蓋章"是常見的業務需求,特別是在合同、證明等正式文件處理場景。本文將詳細介紹如何使用Python代碼實現給Word文檔添加電子印章的功能,涵蓋從基礎實現到高級定制的完整方案。
---
## 一、技術選型與環境準備
### 1.1 Python處理Word文檔的庫選擇
Python中有多個庫可以操作Word文檔,主流選擇包括:
- **python-docx**:最常用的Word文檔操作庫
- **docx2pdf**:用于格式轉換
- **PyMuPDF**:高級PDF/Word處理
- **Office365-REST-Python-Client**:直接操作Office 365文檔
本文將以`python-docx`為主,配合`Pillow`圖像處理庫實現功能。
### 1.2 安裝必要庫
```bash
pip install python-docx Pillow
準備透明背景的PNG格式印章圖片,建議: - 分辨率:300dpi以上 - 尺寸:3cm×3cm左右 - 透明通道:保留印章周圍透明度
from docx import Document
doc = Document()
doc.add_paragraph("這是一份需要蓋章的合同文檔")
doc.save("unsigned.docx")
from docx.shared import Pt, Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH
def add_stamp(doc_path, stamp_path, output_path):
doc = Document(doc_path)
# 添加印章段落
paragraph = doc.add_paragraph()
run = paragraph.add_run()
# 添加圖片
run.add_picture(stamp_path, width=Inches(1.5))
# 設置右對齊
paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
doc.save(output_path)
add_stamp("unsigned.docx", "stamp.png", "signed.docx")
使用表格實現精確定位:
def precise_positioning():
doc = Document()
table = doc.add_table(rows=3, cols=1)
# 在第二行添加印章
cell = table.cell(1, 0)
paragraph = cell.paragraphs[0]
run = paragraph.add_run()
run.add_picture("stamp.png", width=Inches(1.2))
doc.save("positioned.docx")
使用Pillow庫動態生成印章:
from PIL import Image, ImageDraw, ImageFont
import numpy as np
def generate_stamp(text, output_path):
# 創建畫布
size = 400
img = Image.new("RGBA", (size, size), (255, 255, 255, 0))
draw = ImageDraw.Draw(img)
# 繪制圓形
draw.ellipse([(50, 50), (350, 350)], outline="red", width=10)
# 添加文字
font = ImageFont.truetype("simhei.ttf", 36)
draw.text((200, 180), text, font=font, fill="red", anchor="mm")
img.save(output_path)
generate_stamp("電子印章", "dynamic_stamp.png")
def add_transparency():
stamp = Image.open("stamp.png")
data = np.array(stamp)
# 設置透明度
data[..., 3] = data[..., 3] * 0.7
transparent_stamp = Image.fromarray(data)
transparent_stamp.save("transparent_stamp.png")
import os
def batch_stamp(input_dir, output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for file in os.listdir(input_dir):
if file.endswith(".docx"):
doc = Document(os.path.join(input_dir, file))
# 添加印章邏輯...
doc.save(os.path.join(output_dir, f"stamped_{file}"))
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
def add_digital_signature(doc_path, private_key):
with open(doc_path, "rb") as f:
doc_bytes = f.read()
# 計算哈希
digest = hashes.Hash(hashes.SHA256())
digest.update(doc_bytes)
doc_hash = digest.finalize()
# 使用私鑰簽名
signature = private_key.sign(
doc_hash,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
return signature
def add_watermark(doc, text):
for section in doc.sections:
footer = section.footer
paragraph = footer.paragraphs[0] if footer.paragraphs else footer.add_paragraph()
run = paragraph.add_run(text)
run.font.color.rgb = RGBColor(200, 200, 200) # 淺灰色
run.font.size = Pt(40)
from docxtpl import DocxTemplate
def template_stamping():
doc = DocxTemplate("template.docx")
context = {
"stamp": InlineImage(doc, "stamp.png", width=Mm(30))
}
doc.render(context)
doc.save("output.docx")
import requests
def office365_integration():
headers = {
"Authorization": "Bearer <access_token>"
}
# 下載文檔
response = requests.get(
"https://graph.microsoft.com/v1.0/drive/items/<item_id>/content",
headers=headers
)
# 處理文檔并重新上傳...
run.add_picture("stamp.png", width=Inches(1.5), height=Inches(1.5))
doc.protect(WD_PROTECTION.READ_ONLY)
from docx import Document
from docx.shared import Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH
from PIL import Image
class DocumentStamper:
def __init__(self, stamp_path):
self.stamp_path = stamp_path
def process_document(self, input_path, output_path, position="footer"):
doc = Document(input_path)
if position == "footer":
section = doc.sections[0]
footer = section.footer
paragraph = footer.paragraphs[0] if footer.paragraphs else footer.add_paragraph()
else:
paragraph = doc.add_paragraph()
run = paragraph.add_run()
run.add_picture(self.stamp_path, width=Inches(1.5))
paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
doc.save(output_path)
return True
# 使用示例
stamper = DocumentStamper("company_stamp.png")
stamper.process_document("contract.docx", "signed_contract.docx")
本文詳細介紹了使用Python實現Word文檔蓋章的完整方案,從基礎實現到企業級應用都有涉及。關鍵點包括: 1. 正確選擇和處理印章圖片 2. 掌握文檔定位技術 3. 實現安全增強功能 4. 考慮企業級集成方案
隨著數字化轉型的深入,這類自動化辦公技術將發揮越來越重要的作用。建議讀者根據實際需求選擇合適的實現方案,并持續關注相關技術的最新發展。 “`
這篇文章提供了從基礎到高級的完整實現方案,包含約2300字內容,采用Markdown格式編寫,包含代碼示例、技術說明和實用建議。您可以根據需要調整代碼細節或補充特定業務場景的說明。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。