Python spire.doc 转换docx文档中表格的单元格为图片并消除图片空白部分(支持公式)
读取word中表格,并将指定单元格转化成图片,并消除图片的空白部分:

转换后的图片:

from spire.doc import *
from PIL import Image
import numpy as np
import os
import time
#清除图片空白部分
def remove_background(image_path, output_path):
    # 打开图像
    image = Image.open(image_path)
    
    # 转换为灰度图
    gray_image = image.convert('L')
    
    # 转换为 NumPy 数组
    np_image = np.array(gray_image)
    
    # 设置阈值,识别非空白区域
    threshold = 250
    non_white_pixels = np_image < threshold
    
    # 查找非空白区域的边界
    rows = np.any(non_white_pixels, axis=1)
    cols = np.any(non_white_pixels, axis=0)
    
    top, bottom = np.where(rows)[0][[0, -1]]
    left, right = np.where(cols)[0][[0, -1]]
    
    # 裁剪图像
    cropped_image = image.crop((left, top, right + 1, bottom + 1))
    
    # 保存新图像
    cropped_image.save(output_path)
# 加载 Word 文档
document = Document()
document.LoadFromFile("test3.docx")
# 指定输出文件夹存在
#output_dir = "output/Tables"
#os.makedirs(output_dir, exist_ok=True)
# 遍历所有节并提取表格数据
for s in range(document.Sections.Count):
    section = document.Sections[s]
    tables = section.Tables
    for i in range(tables.Count):
        #if i!=2:
        #    continue
        table = tables[i]
        for j in range(table.Rows.Count):
            row = table.Rows[j]
            print("--------行高:",row.Height)
            for k in range(row.Cells.Count):
                cell = row.Cells[k]
                print("---单元格:",j,k)
                print("---单元格宽:",cell.Width)
                # 创建临时文档保存表格内容
                temp_doc = Document()
                temp_section = temp_doc.AddSection()
                
                # 创建一个表格对象
                tb = Table(temp_doc, True)
                tb.TableFormat.Borders.BorderType = BorderStyle.Single
                #tb.TableFormat.Borders.Color = Color.get_White()
                #tb.TableFormat.HorizontalAlignment = RowAlignment.Center  //Left  Right
                #tb.VerticalAlignment=VerticalAlignment.Bottom
                # 添加一行,包含0个单元格
                tbrow = tb.AddRow(False, 0)
                
                cell.CellFormat.VerticalAlignment=VerticalAlignment.Middle
                tbrow.Cells.Add(cell.Clone())
                tbrow.Height=row.Height+30  #适当增加高度
                # 将表格添加到节中
                temp_section.Tables.Add(tb)
                #temp_doc.SaveToFile(f"testdoc{j}{k}.docx")  #保存为文件
                # 保存为图片
                # 遍历文档中的所有页面
                for ii in range(temp_doc.GetPageCount()):
                    # 将指定页面转换为位图(bitmap)
                    imageStream = temp_doc.SaveImageToStreams(ii, ImageType.Bitmap)
                    fnames=[]
                    # 将位图(bitmap)保存为PNG文件
                    with open(f'tu-{j}{k}{ii}.png'.format(ii),'wb') as imageFile:
                        imageFile.write(imageStream.ToArray())
                    #消除空白
                    remove_background(f'tu-{j}{k}{ii}.png', f'tu-{j}{k}{ii}.png')
                # 释放资源
                temp_doc.Close()
document.Close()
                
            
        
浙公网安备 33010602011771号