Python docx庫刪除復(fù)制paragraph及行高設(shè)置圖片插入示例
引言
這兩天做一個python小工具,用到了docx庫,涉及到paragraph的刪除、,還有行高設(shè)置等技術(shù),這里做一下記錄。
1、復(fù)制paragraph
即用來原文檔的加粗、斜體,下劃線,顏色等屬性的,官方?jīng)]有提供paragraph的接口,只能自己實(shí)現(xiàn):
# 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
網(wǎng)上有用clear()的,實(shí)際不行。 我刪除一個空行paragraph,用clear不行,還是后來用了下面這個接口才解決:
def delete_paragraph(paragraph): p = paragraph._element p.getparent().remove(p) p._p = p._element = None
3、插入圖片和paragraph行高設(shè)置
由于默認(rèn)的行高限制,我的使用中遇到了麻煩,插入的圖片的時候,圖片部分只能顯示一部分。后來,找到了一個辦法設(shè)置行高屬性:
from docx.enum.text import WD_LINE_SPACING paragraph.paragraph_format.line_spacing_rule = WD_LINE_SPACING.MULTIPLE #根據(jù)實(shí)際大小 output_run = paragraph.add_run("") output_run.add_picture('{}.png'.format(ownerName), width=Pt(50), height=Pt(15))
以上就是Python docx庫刪除復(fù)制paragraph及行高設(shè)置圖片插入示例的詳細(xì)內(nèi)容,更多關(guān)于Python docx庫操作的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python3中編碼獲取網(wǎng)頁的實(shí)例方法
在本篇文章里小編給大家整理了一篇關(guān)于python3中編碼獲取網(wǎng)頁的實(shí)例方法,有興趣的朋友們可以學(xué)習(xí)下。2020-11-11Django模板標(biāo)簽中url使用詳解(url跳轉(zhuǎn)到指定頁面)
這篇文章主要介紹了Django模板標(biāo)簽中url使用詳解(url跳轉(zhuǎn)到指定頁面),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03解決pycharm最左側(cè)Tool Buttons顯示不全的問題
今天小編就為大家分享一篇解決pycharm最左側(cè)Tool Buttons顯示不全的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12Python字符串的創(chuàng)建和駐留機(jī)制詳解
字符串駐留是一種在內(nèi)存中僅保存一份相同且不可變字符串的方法,本文重點(diǎn)給大家介紹Python字符串的創(chuàng)建和駐留機(jī)制,感興趣的朋友跟隨小編一起看看吧2022-02-02Python正則表達(dá)式re.search()用法詳解
re是Python中最常見的正則表達(dá)式模塊,常用方法包括compile,match,findall,finditer,search,split,sub等,下面這篇文章主要給大家介紹了關(guān)于Python正則表達(dá)式re.search()用法詳解的相關(guān)資料,需要的朋友可以參考下2022-09-09