背景需求
前期实现了图案的点装虚线和现状虚线效果图(PNG透明背景)
点状虚线(PNG透明背景)
线状虚线(PNG透明背景)
我想把图片做到A4纸里,便于打印。
一、WORD模版
已知正方形图案可以1图2图6图24图形式插入竖版WORD
、、
二、裁剪掉白色透明边缘,让图案最大化
'''
把虚线图做到A4的一张二张六张二十四张图中
星火讯飞+deepseek阿夏
20250409
'''
import os,time
from PIL import Image, ImageDraw
import shutil
from docx import Document
from docx.shared import Cm
from PyPDF2 import PdfFileMerger, PdfFileReader
from PIL import ImageFont
import random
# name='01圆形灯笼图片'
name='10_03_02蛋糕点虚线统一图'
# word图名自称1图、2图
x=[1,2,6,24]
# x=[6]
# 插入格子的列数
t=[1,1,2,4]
# t=[2]
# 插入图片尺寸
s=['19.7','14.1','9.4','4.68']
# s=['9.4']
# 图片大,保存时需要延时
y=[3,2,1,1]
for z in range(len(x)):
# 获取123文件夹下的所有图片文件
path=r'C:\Users\jg2yXRZ\OneDrive\桌面\20250401边缘线剪纸'
folder_path =path+fr"\{name}"
w=int(x[z])
v=int(t[z])
ss=float(s[z])
yy=int(y[z])
# 获取包含完整路径的图片文件列表
image_files = [os.path.join(folder_path, f) for f in os.listdir(folder_path)
if f.lower().endswith(('.jpg', '.jpeg', '.png'))]
# image_files = [f for f in os.listdir(folder_path) if f.endswith(('.jpg', '.jpeg', '.png'))]
print(len(image_files))
print(image_files)
# print('----2、读取两个图,分别插入docx,制作PDF---------')
# 将图片拆成6个一组
grouped_files = [image_files[i:i + w] for i in range(0, len(image_files), w)]
print(len(grouped_files))
# # 53
# 创建临时文件夹
new_folder = path+r'\零时文件夹2'
os.makedirs(new_folder, exist_ok=True)
# 处理每一组图片
for group_index, group in enumerate(grouped_files):
# print(group)
# 创建新的Word文档
doc = Document(path+fr'\{w}图.docx')
# print(group)
# 遍历每个单元格,并插入图片
for cell_index, image_file in enumerate(group):
# 计算图片长宽(单位:厘米)
print(image_file)
# 插入图片到单元格
table = doc.tables[0]
cell = table.cell(int(cell_index / v), cell_index % v)
# 如果第一行有4个格子,两个数字都写4
cell_paragraph = cell.paragraphs[0]
cell_paragraph.clear()
run = cell_paragraph.add_run()
run.add_picture(image_file, width=Cm(ss), height=Cm(ss))
# 保存Word文档
doc.save(os.path.join(new_folder, f'{group_index + 1:03d}.docx'))
time.sleep(yy)
# 将10个docx转为PDF
import os
from docx2pdf import convert
from PyPDF2 import PdfFileMerger
pdf_output_path = path+fr'\\{name}{w}图{ss}厘米 {len(grouped_files)}张共{len(image_files)}图.pdf'
# 将所有DOCX文件