Python docx库删除复制paragraph及行高设置图片插入示例

引言

这两天做一个python小工具,用到了docx库,涉及到paragraph的删除、,还有行高设置等技术,这里做一下记录。

1、复制paragraph

即用来原文档的加粗、斜体,下划线,颜色等属性的,官方没有提供paragraph的接口,只能自己实现:

# paragraph 的
def get_para_data(output_doc_name, paragraph):
    """
    Write the run to the new file and then set its font, bold, alignment, color etc. data.
    """
    output_para = output_doc_name.add_paragraph()
    for run in paragraph.runs:
        output_run = output_para.add_run(run.text)
        # Run's bold data
        output_run.bold = run.bold
        # Run's italic data
        output_run.italic = run.italic
        # Run's underline data
        output_run.underline = run.underline
        # Run's color data
        output_run.font.color.rgb = run.font.color.rgb
        # Run's font data
        output_run.style.name = run.style.name
    # Paragraph's alignment data
    output_para.paragraph_format.alignment = paragraph.paragraph_format.alignment

2、删除paragraph

网上有用clear()的,实际不行。 我删除一个空行paragraph,用clear不行,还是后来用了下面这个接口才解决:

def delete_paragraph(paragraph):
    p = paragraph._element
    p.getparent().remove(p)
    p._p = p._element = None

3、插入图片和paragraph行高设置

由于默认的行高限制,我的使用中遇到了麻烦,插入的图片的时候,图片部分只能显示一部分。后来,找到了一个办法设置行高属性:

 from docx.enum.text import WD_LINE_SPACING
     paragraph.paragraph_format.line_spacing_rule = WD_LINE_SPACING.MULTIPLE #根据实际大小
     output_run = paragraph.add_run("")
     output_run.add_picture('{}.png'.format(ownerName), width=Pt(50), height=Pt(15))

以上就是Python docx库删除复制paragraph及行高设置图片插入示例的详细内容,更多关于Python docx库操作的资料请关注脚本之家其它相关文章!

你可能感兴趣的:(Python docx库删除复制paragraph及行高设置图片插入示例)