2017-02-09 70 views
0

我目前正在嘗試使用docxtpl生成word文檔。但是,當樣式名稱包含空格時,我無法確定如何向Richtext對象添加單詞樣式,因爲樣式未在單詞文檔中應用。在使用單個單詞命名樣式的其他情況下,它可以正常工作。 這裏是我當前的代碼:如何將Word樣式應用於Richtext對象? (docxtpl庫)

from bs4 import BeautifulSoup 
from docxtpl import DocxTemplate, RichText 

html = "<html><body><p><p>I am a paragraph generated by python.</p></p><ul><li>List 1 item 1</li><li>List 1 item " \ 
    "2</li></ul><p>Example below:</p><li>List 2 item 1</li><li>List 2 item 1</li><p>End paragraph</p></body></html> " 


def main(): 
    soup = BeautifulSoup(html, 'html.parser').find_all() 
    rt = RichText() 
    for tag in soup: 
     if tag.name == 'p' and tag.parent.name != 'p': 
      print tag.text 
      rt.add(tag.text + "\n\n") 
     elif tag.name == 'li' and tag.parent.name != 'li': 
      rt.add(tag.text + "\n", style='Subtle Reference') 

    output_data = {"data": rt} 
    tpl = DocxTemplate('template.docx') 
    tpl.render(output_data) 
    tpl.save('output.docx') 
Word文檔中

神社代碼:

{{r data}} 

我創建與此gitlab的問題,但不知道有沒有人使用這個庫之前,不得不任何好的解決方法?

回答

1

從示例文件看來,您不能將HTML字符串直接轉換爲RichText()。相反,你必須使用它們的類語法。

下面是一個例子:

rt = RichText('an exemple of ') 

rt.add('a rich text', style='myrichtextstyle') 
rt.add(' with ') 
rt.add('some italic', italic=True) 
rt.add(' and ') 
rt.add('some violet', color='#ff00ff') 
rt.add(' and ') 
rt.add('some striked', strike=True) 
rt.add(' and ') 
rt.add('some small', size=14) 
rt.add(' or ') 
rt.add('big', size=60) 
rt.add(' text.') 
rt.add(' Et voilà ! ') 
rt.add('\n1st line') 
rt.add('\n2nd line') 
rt.add('\n3rd line') 
rt.add('\n\n<cool>') 

context = { 
    'example' : rt, 
} 

tpl.render(context) 
tpl.save('test_files/richtext.docx') 

來源:https://github.com/elapouya/python-docx-template/blob/master/tests/richtext.py

相關問題