- 2025-04-07 19:06:48
近日遇到一个需求, 要将一些图片按一定要求放到Word文档中. 这些图片格式不统一, 有pdf, 有png, 有jpg. 宽高也各不同, 但要求图片横向放置, 每页一张. 当然, 如果手动操作, 就没有必要记录作法了.
将问题分解一下, 有下列步骤:
- 将pdf转换为图片: 可以借助
xpdf-tools
中的pdftopng
- 如果图片高>宽, 旋转图片: 可以借助
ImageMagick
- 将图片写到html文件中: 使用Word支持的格式
- 使用Word打开html文件, 断开链接, 嵌入图片.另存为Word格式
前两步没有什么要说的.
Word支持的html文件与常规的有所不同, 具体哪些地方不同, 也没有必要仔细研究, 直接将一份简单的Word文件另存为html格式看看就可以知晓了. 我们的需求比较简单, 所以只需要保留其中重要的相关设置, 所得模板如下
html | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <style>
@page WordSection1 {
size:297mm 210mm;
margin: 12.7mm 12.7mm 12.7mm 12.7mm;
mso-page-orientation:landscape;
mso-header-margin:42.55pt;
mso-footer-margin:49.6pt;
mso-paper-source:0;
}
div.WordSection1 {page:WordSection1;}
</style>
<body>
<div class=WordSection1 align=center style='text-align:center'>
<img width=996 height=702 src="1.png">
<img width=996 height=702 src="2.jpg">
</div>
</body> |
可以看到, Word可以识别html文件中自定义的页面设置, 其中可以设置页面大小, 页边距, 页面方向等. 这些设置浏览器未必支持. 需要注意的是, 其中的图片大小, 只能以像素为单位, 且默认根据96dpi计算.
使用Word打开这样的html文件, 可以看到图片, 但只是链接. 如果将Word文件转移到其他位置, 图片就无法显示了. 因此, 我们还需要将图片嵌入Word文件中. 对于Word2016, 依次
文件 | 信息 | 相关文档 | 编辑指向文件的链接
然后
全选 | 断开链接 | 将图片保存在文档中 | 确定
.
脚本
将上面的步骤总结为下面的脚本, 处理起大量的文件来就更容易了.
img2doc.bsh | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | # 定义程序路径
im=/D/ImageMagick-7.1.1-19-Q16-HDRI
xpdf=/D/PDFtools/xpdf-tools-4.05/bin
# 先将pdf转换为相应的png文件
for pdf in *.pdf; do
name=${pdf%.pdf}
$xpdf/pdftopng.exe $pdf $name
mv $name-000001.png $name.png
done
# 根据宽高旋转图片
mkdir -p backup
for img in *.jpg *.png; do
eval $($im/identify.exe -ping -format 'w=%w; h=%h;' $img) # 获取宽高
[[ $h > $w ]] && {
cp $img ./backup/$img
$im/convert.exe -rotate -90 ./backup/$img $img
}
done
# 输出图片及其编号
rm -f _img
for img in *.jpg *.png; do
idx=${img##*_}; idx=${idx%.*}
echo $idx $img >>_img
done
# 排序图片并输出到html文件
sort -n _img | awk '
BEGIN { print "<style>" \
"\n@page WordSection1 {" \
"\n size:297mm 210mm;" \
"\n margin: 12.7mm 12.7mm 12.7mm 12.7mm;" \
"\n mso-page-orientation:landscape;" \
"\n mso-header-margin:42.55pt;" \
"\n mso-footer-margin:49.6pt;" \
"\n mso-paper-source:0;}" \
"\ndiv.WordSection1 {page:WordSection1;}" \
"\n</style>" \
"\n" \
"\n<body>" \
"\n<div class=WordSection1 align=center style=\"text-align:center\">" \
"\n"
}
{ print "<img width=996 height=702 src=\""$2"\">" }
END {print "</div></body>"}
' >_.html |