使用Python docx在Word中自动调整图片

问题描述 投票:0回答:1

我正在尝试使用 python docx 将图片插入到 word 文档中。我的问题是我的程序以原始分辨率插入图片,因此它们太大了。我知道我可以设置高度和宽度参数,但我要插入不同尺寸的图片,所以我不想设置固定分辨率。当直接将图片添加到 Word 文档(不使用 Python)时,默认情况下使用以下 VBA 代码执行此操作:

ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=2, NumColumns:=1, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:=wdAutoFitFixed

我的代码如下:

import docx
from docx.shared import Inches,Pt
from docx.shared import *
import os
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.style import WD_STYLE_TYPE

doc = docx.Document()
section = doc.sections[0]
header = section.header
header_para = header.paragraphs[0]
header_para.style = doc.styles.add_style('Style Name', WD_STYLE_TYPE.PARAGRAPH)
font = header_para.style.font 
font.size = Pt(20)
font.bold = True
header_para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
header_para.text = ("Header")
f = ('Capture.PNG')
caption = os.path.basename(f)
f_name, f_ext = os.path.splitext(caption)
table = doc.add_table(rows=2, cols=1)
table.allow_autofit = False
table.style = 'Table Grid'
run1 = table.cell(0,0).paragraphs[0].add_run()
run2p = table.cell(1,0).paragraphs[0]
run2 = table.cell(1,0).paragraphs[0].add_run()
run1.add_picture(f, height = Inches(3.38), width = Inches(6))
run2.text = (f_name)
run2p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
doc.add_paragraph()
output = 'file.docx'
doc.save(output)

我尝试将“table.allow_autofit”参数设置为“True”和“False”,但这没有用。

python vba ms-word docx
1个回答
0
投票

这不是完美的解决方案,但也许这种方法可以帮助您:

from PIL import Image
from docx.text.paragraph import Paragraph


class PixelsToInches:
   
    def __init__(self, pixels: int):
        self._pixels = pixels

    def value(self) -> float:
        """
        Inches value
        :return:
        """
        PIXEL_IN_INCHES = 0.0104166667
        return self._pixels * PIXEL_IN_INCHES


class PicturePixelMeasure:
    
    def __init__(self, content: io.BytesIO):
        self._content = Image.open(content)

    def width(self) -> int:
        width, _ = self._content.size
        return width

    def height(self) -> int:
        _, height = self._content.size
        return height

def inserting_picture(picture_base64: str, paragraph: Paragraph):
    DEFAULT_INCHES_WIDTH = 5
    binary_picture = io.BytesIO(base64.b64decode(picture))
    picture_px_measure = PicturePixelMeasure(binary_picture)            
    picture_width_px_to_inch = PixelsToInches(picture_px_measure.width())
    picture_height_px_to_inch = PixelsToInches(picture_px_measure.height())
    run = paragraph.add_run()
    if (
         picture_width_px_to_inch.value() > DEFAULT_PICTURE_INCHES_WIDTH or
         picture_height_px_to_inch.value() > DEFAULT_PICTURE_INCHES_HEIGHT
    ):
        run.add_picture(
            binary_picture,
            width=Inches(5)
        )
     else:
        run.add_picture(
            binary_picture,
            width=Inches(picture_width_px_to_inch.value()),
            height=Inches(picture_height_px_to_inch.value())
        )
    
© www.soinside.com 2019 - 2024. All rights reserved.