事情是这样的
小姑娘还在继续学习,准备下一轮考试。这一次她找了一个培训机构的讲义,原本是分开的20+个word文档,然而合起来后就是有300+页。
她需要把文档打印出来......
那么问题来了
合并后的文档有如下几个问题:
- 图片过大,位置居中
- 时不时的广告图片
- 字体大小混乱、重复
似乎word并没有能够批量选取图片的功能。作为程序员,我的想法是这种机械性的工作,应该也必须能够通过编程解决。所以我向小姑娘领取了任务。
JS似乎行不通
我的技术栈主要有Java和JavaScript,Java首先被我放弃了。
那么只能是JavaScript了。百度把我带到了Office官方网站,里面有提到Office扩展,使用的恰好是JavaScript。似乎有戏,然而我简单浏览了一下文档,似乎挺复杂,我看到了宇宙第一IDE——VS的身影,又犹豫了。
还有没有其他办法——python-docx
不死心的我抛弃了技术栈的限制,python给我一条出路了——python-docx。
文档不长,示例代码很短,试试看呗。
安装...
打开spyder...
编写代码...
运行...
调试...
看效果...
十多分钟就实现了目标
talk is cheap, show me the code
大佬勿喷,python新人
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
from docx import Document
from docx.shared import Inches, Cm, Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_ALIGN_VERTICAL, WD_TABLE_ALIGNMENT
# 读取源文档
document = Document('jiangyi.docx')
for shape in document.inline_shapes:
h = shape.height.cm
w = shape.width.cm
if h < 1:
shape.height = Cm(0)
shape.width = Cm(0)
elif h >= 4 and w >=8:
shape.height = Cm(4)
shape.width = Cm(8)
for s in document.sections:
# print(p.alignment)
for p in s.header.paragraphs:
for r in p.runs:
f = r.font
if f.size.pt if f.size else 0 > 10.5:
f.size = Pt(10.5)
# print(f.size.pt if f.size else 0)
for p in document.paragraphs:
# print(p.alignment)
p.alignment = WD_ALIGN_PARAGRAPH.LEFT
# print(p.text)
for r in p.runs:
f = r.font
if f.size.pt if f.size else 0 > 10.5:
f.size = Pt(10.5)
# print(f.size.pt if f.size else 0)
for t in document.tables:
t.alignment = WD_TABLE_ALIGNMENT.LEFT
t.autofit = True
for r in t.rows:
for c in r.cells:
c.vertical_alignment = WD_ALIGN_VERTICAL.TOP
for cp in c.paragraphs:
# print(cp.alignment)
cp.aligment = WD_ALIGN_PARAGRAPH.LEFT
for r in cp.runs:
f = r.font
if f.size.pt if f.size else 0 > 10.5:
f.size = Pt(10.5)
# print(f.size.pt if f.size else 0)
# 修改完了生成新文档,或者也可以覆盖源文档
document.save('jiangyi-result.docx')
感想
- 作为一个没有写过python的前端工程师来说,书写python代码门槛相当低。排除一些语法差异后,基本上就能写出可以完成任务的代码了。
- python-docx提供了基本的操作word文档的方法,但是对于一篇word文档在python-docx里的存在形式和组成结构,我还没有完全清楚,所以有的功能是没有实现的,比如,将表格中的图片居中。
- 人生苦短,我用python