2 Star 16 Fork 1

Nagisa / ygo-CardPrinter

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
ygo-CardPrinter.py 4.36 KB
一键复制 编辑 原始数据 按行查看 历史
import os
from docx import Document
from docx.shared import Mm
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.enum.table import WD_ROW_HEIGHT_RULE
import tkinter
from tkinter import filedialog
from config import config
def get_path():
"""遍历文件夹,返回图片路径"""
tkinter.Tk().withdraw() # 创建一个Tkinter.Tk()实例,隐藏
directory_path = filedialog.askdirectory(title='选择图片所在文件夹') # 选择文件夹
path_list = []
file_num = 0
for root, dirs, items in os.walk(directory_path):
for item in items:
path = os.path.join(root, item)
suffix = os.path.splitext(path)[-1]
if suffix not in ('.png', '.jpg', '.jpeg'): # 图片格式限定
continue
file_num += 1
print(file_num, path)
path_list.append(path)
return path_list
def set_cell_margins(cell, **kwargs):
"""
控制表格的内容与单元格间距
注意:此函数访问了保护成员变量,因为官方未提供相关功能
"""
tc = cell._tc
tc_pr = tc.get_or_add_tcPr()
tc_mar = OxmlElement('w:tcMar')
for m in ["top", "start", "bottom", "end"]:
if m in kwargs:
node = OxmlElement(f"w:{m}")
node.set(qn('w:w'), str(kwargs.get(m)))
node.set(qn('w:type'), 'dxa')
tc_mar.append(node)
tc_pr.append(tc_mar)
def generate_docx():
"""生成docx文档"""
# 创建word
doc = Document()
# 调节页边距
sections = doc.sections
for section in sections:
section.top_margin = Mm(config.top_margin)
section.bottom_margin = Mm(config.bottom_margin)
section.left_margin = Mm(config.left_margin)
section.right_margin = Mm(config.right_margin)
# 纸张大小
section_page = sections[0]
section_page.page_height = Mm(config.page_height)
section_page.page_width = Mm(config.page_width)
# 遍历图片总数,保存路径
path_list = get_path()
file_num = len(path_list)
if file_num == 0:
print('该目录无匹配文件!')
input('\n请按回车键或关闭窗口退出……')
return
# 判断表格行数,若不满3则加1
if file_num % 3 != 0:
items_row = file_num // 3 + 1
else:
items_row = file_num // 3
# 创建表格
table = doc.add_table(rows=items_row, cols=3)
# 表格自动调整尺寸
table.autofit = config.cell_autofit
# 在表格中添加图片
for row in range(0, items_row):
if not config.cell_autofit:
table.rows[row].height_rule = WD_ROW_HEIGHT_RULE.EXACTLY # 设置行高为固定值
table.rows[row].height = Mm(config.card_height) # 表格的行高
for col in range(0, 3):
cell = table.cell(row, col)
if not config.cell_autofit:
cell.width = Mm(config.card_weight) # 表格的列宽
set_cell_margins(cell, top=0, start=0, bottom=0, end=0) # 设置表格单元格的间距
cell_paragraph = cell.paragraphs[0] # 段落
cell_paragraph.paragraph_format.space_before = Mm(0) # 表格段前间距
cell_paragraph.paragraph_format.space_after = Mm(0) # 表格段后间距
cell_run_paragraph = cell_paragraph.add_run() # 文字段落后追加段落
index = row * 3 + col
if index > len(path_list) - 1: # 表格单元格数大于图片数
continue
cell_run_paragraph.add_picture(
path_list[index],
height=Mm(config.card_height),
width=Mm(config.card_weight)) # 插入图片(指定宽高,缩放尺寸不合适的图片)
print(f'\r正在插入图片…… ({index + 1}/{file_num})', end="")
print('\n正在保存……')
doc.save('output' + '.docx')
input('\n保存完成!请按回车键或关闭窗口退出……')
if __name__ == '__main__':
try:
# 从 setting.ini 载入配置
config.load()
except Exception as e:
print(f'载入配置出错,您可以删除setting.ini文件,重新运行程序,配置文件将按默认设置重新生成。错误详情:{e}')
input('\n请按回车键或关闭窗口退出……')
else:
print('请在弹出的对话框中选择图片文件夹')
generate_docx()
Python
1
https://gitee.com/pth2000/ygo-CardPrinter.git
git@gitee.com:pth2000/ygo-CardPrinter.git
pth2000
ygo-CardPrinter
ygo-CardPrinter
master

搜索帮助