• python使用python-docx库处理图片白框问题


    1,背景来源

            使用python-docx对word进行处理的时候,插入BytesIO对象的image后,导出的word中出现白框问题。

    2,涉及使用方法
    • io.BytesIO方法读取image文件:作用【读取image文件后将图片插入到word中】
    • deepcopy深复制:作用【读取模板,因为我有多条记录,会遍历多次模板数据表格】
    • new_paragraph = doc.add_paragraph():作用【word文件中创建一个段落】
    • paragraph.add_run():作用【在段落中创建一个运行】
    • run.add_picture(image_data) :作用【在运行中插入图片,也可以是文本各种】
    3,两种情况

            1,【方案1】首先,在单独的数据表格对象中,插入图片,然后将数据表格插入到word中,最后将word导出。【导出结果:word中图片显示白框

            2,【方案2】首先,获取模板文件中的数据表格,然后遍历所有数据记录,每个数据记录都要对应一个数据表格,将其中的值替换进去,然后将数据表格导入word文件中,最后一步,读取word文件刚刚导入的最后一个数据表格,把image添加进去。【导出结果:图片正常显示

    1. def gbmc_Image_Output_Word(self):
    2. resultData = 【自己写,调自己数据库的数据,或者写死数据】
    3. unit_resultData = 【自己写,调自己数据库的数据,或者写死数据】
    4. # 打开word文档
    5. doc = Document(r"C:\Users\Desktop\word导出.docx")
    6. # 获取模板文件中的第一个表格【这个就是模板数据表格】
    7. template_table = doc.tables[0]
    8. fields = ['name', '***', '***']
    9. result = []
    10. for item in resultData:
    11. result.append(
    12. {
    13. "code": item.code,
    14. "***": item.***,
    15. "***": item.***,
    16. }
    17. )
    18. for dw_item in unit_resultData:
    19. # 添加一个标题段落
    20. title = doc.add_paragraph(dw_item.dwmc)
    21. # 设置标题样式为一级标题(通常是Heading 1)
    22. title.style = doc.styles['Heading 1']
    23. # 设置段落居中对齐
    24. title.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    25. # 设置段前分页
    26. title.paragraph_format.page_break_before = True
    27. for i, item in enumerate(result):
    28. print(f'姓名:{item.get("name")},工号:{item.get("code")}')
    29. # 复制模板表格(深复制)
    30. new_table = deepcopy(template_table)
    31. image_data = None
    32. # 替换表格中的内容
    33. for row in new_table.rows:
    34. for cell in row.cells:
    35. for key in fields:
    36. value = item.get(key)
    37. if '{{' + key + '}}' in cell.text and value is not None:
    38. if key == "image":
    39. try:
    40. image_data = io.BytesIO(response.content) # 这里是image对象,接口获取的图片
    41. except Exception as e:
    42. print(f'获取图片失败,失败原因:{str(e)}')
    43. else:
    44. # cell.text = cell.text.replace('{{' + key + '}}', image_data)
    45. # 清空单元格原有文本
    46. cell.text = ''
    47. # 添加文本并设置属性
    48. paragraph = cell.paragraphs[0] # 获取单元格的第一个段落
    49. paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # 段落居中对齐
    50. run = paragraph.add_run(str(value))
    51. run.bold = True
    52. run.font.size = Pt(12)
    53. run.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # 文本居中对齐
    54. # 去除模板中{{data}}类型的占位符
    55. for row in new_table.rows:
    56. for cell in row.cells:
    57. if '{{' in cell.text and '}}' in cell.text and cell.text != "{{image}}":
    58. cell.text = ""
    59. # 在文件中创建一个段落
    60. new_paragraph = doc.add_paragraph()
    61. # 在段落中插入数据表格
    62. new_paragraph._element.getparent().insert(new_paragraph._element.getparent().index(new_paragraph._element) + 1, new_table._element)
    63. if image_data: # 【对已经导入word后的数据表格对图片进行处理,重点代码!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!】
    64. table = doc.tables[-1]
    65. for row in table.rows:
    66. for cell in row.cells:
    67. if "{{image}}" in cell.text:
    68. cell.text = ""
    69. if not cell.paragraphs:
    70. cell.add_paragraph()
    71. # 获取单元格的第一个段落
    72. run = cell.paragraphs[0].add_run()
    73. run.add_picture(image_data, width=Inches(1.0)) # 同时指定宽度和高度
    74. # 设置段落格式,确保段落不被拆分到不同的页面
    75. paragraph_format = new_paragraph.paragraph_format
    76. paragraph_format.keep_together = True # 设置段落保持在一起
    77. # 在文件中添加两个段落,不放任何内容
    78. doc.add_paragraph()
    79. doc.add_paragraph()
    80. print("数据已导入")
    81. # 删除读取的模板表格
    82. template_table._element.getparent().remove(template_table._element)
    83. # # 生成目录
    84. # table_of_contents = generate_table_of_contents(doc)
    85. # 保存文档到内存中
    86. output_file = io.BytesIO()
    87. doc.save(output_file)
    88. output_file.seek(0)
    89. doc_path = "测试版.docx"
    90. # 发送文档作为附件
    91. return send_file(output_file, as_attachment=True, download_name=doc_path)

  • 相关阅读:
    MFC读取obj格式文件2
    C++:vector
    Git-概念与架构
    PMP每日一练 | 考试不迷路-8.5(包含敏捷+多选)
    MQ基础(RabbitMQ)
    【云原生 | 拓展02】在单台宿主机上管理Docker容器
    KMeans算法与GMM混合高斯聚类
    Django(三、数据的增删改查、Django生命周期流程图)
    【JVM】JVM详解
    将MindSpore运行结果输出到log文件
  • 原文地址:https://blog.csdn.net/m0_67601373/article/details/140370512