|
@@ -7,6 +7,8 @@ import os
|
|
|
import time
|
|
|
from docx import Document
|
|
|
from docx.oxml.ns import qn # 导入qn函数用于处理中文字体
|
|
|
+from docx.shared import Inches, Cm # 导入Inches和Cm用于设置图片尺寸
|
|
|
+from docx.enum.section import WD_SECTION_START # 导入WD_SECTION_START用于添加新页面
|
|
|
from .logger import logger
|
|
|
|
|
|
def check_variables_in_document(docx_path, variables):
|
|
@@ -190,6 +192,60 @@ def replace_text_in_paragraph(paragraph, variables):
|
|
|
# 记录处理后的段落文本
|
|
|
logger.info(f"处理后段落文本: {paragraph.text}")
|
|
|
|
|
|
+def add_image_page(document, image_path):
|
|
|
+ """
|
|
|
+ 在文档末尾添加新页面并插入图片
|
|
|
+
|
|
|
+ 参数:
|
|
|
+ document: 文档对象
|
|
|
+ image_path: 图片路径
|
|
|
+
|
|
|
+ 返回:
|
|
|
+ 成功返回True,失败返回False
|
|
|
+ """
|
|
|
+ try:
|
|
|
+ logger.info(f"开始添加图片页面: {image_path}")
|
|
|
+
|
|
|
+ if not os.path.exists(image_path):
|
|
|
+ logger.error(f"图片文件不存在: {image_path}")
|
|
|
+ return False
|
|
|
+
|
|
|
+ # 添加分节符,创建新页
|
|
|
+ current_section = document.sections[-1]
|
|
|
+ new_section = document.add_section(WD_SECTION_START.NEW_PAGE)
|
|
|
+
|
|
|
+ # 复制前一节的页面设置
|
|
|
+ new_section.page_height = current_section.page_height
|
|
|
+ new_section.page_width = current_section.page_width
|
|
|
+ new_section.left_margin = current_section.left_margin
|
|
|
+ new_section.right_margin = current_section.right_margin
|
|
|
+ new_section.top_margin = current_section.top_margin
|
|
|
+ new_section.bottom_margin = current_section.bottom_margin
|
|
|
+ new_section.header_distance = current_section.header_distance
|
|
|
+ new_section.footer_distance = current_section.footer_distance
|
|
|
+
|
|
|
+ # 添加空段落
|
|
|
+ document.add_paragraph()
|
|
|
+
|
|
|
+ # 计算合适的图片尺寸
|
|
|
+
|
|
|
+ width_inches = (new_section.page_width.inches -
|
|
|
+ new_section.left_margin.inches -
|
|
|
+ new_section.right_margin.inches) * 1
|
|
|
+
|
|
|
+ # 添加图片到文档,设置宽度
|
|
|
+ try:
|
|
|
+ document.add_picture(image_path, width=Inches(width_inches))
|
|
|
+ logger.info(f"成功添加图片: {os.path.basename(image_path)}")
|
|
|
+ return True
|
|
|
+ except Exception as e:
|
|
|
+ logger.error(f"添加图片失败: {str(e)}")
|
|
|
+ return False
|
|
|
+
|
|
|
+ except Exception as e:
|
|
|
+ logger.error(f"添加图片页面时出错: {str(e)}")
|
|
|
+ return False
|
|
|
+
|
|
|
def process_word_template(template_path, output_path, variables):
|
|
|
"""
|
|
|
处理Word文档,替换其中的模板变量
|
|
@@ -239,6 +295,12 @@ def process_word_template(template_path, output_path, variables):
|
|
|
|
|
|
logger.info(f"处理完成: 共处理了 {paragraph_count} 个段落和 {table_cell_count} 个表格单元格")
|
|
|
|
|
|
+ # 检查是否需要添加图片
|
|
|
+ image_path = os.path.join('image', 'test.jpeg')
|
|
|
+ if os.path.exists(image_path):
|
|
|
+ logger.info(f"发现图片文件: {image_path},准备添加图片页面")
|
|
|
+ add_image_page(doc, image_path)
|
|
|
+
|
|
|
# 保存生成的文档
|
|
|
try:
|
|
|
doc.save(output_path)
|