Hello,
Hope everyone had a good thanksgiving!
I really like using python-docx but ran into a problem. I have a base template docx file called format.docx with my paragraph styles modified. When I use docx Document() to open base template docx, as a base template with formatting, then use a paragraph to put in text I always get the additional text to start on the second line when I use document.save(). Here is a snippet of the code:
from docx import Document
input_file = open('format.docx', 'r')
document = Document(input_file)
styles = document.styles
# Set style for head paragraph
head_style = styles.add_style('head_paragraph', WD_STYLE_TYPE.PARAGRAPH)
head_style.base_style = styles['Title']
paragraph_style(head_style, font_type, 24, True, 0, 0, False)
# Head paragraph
head = document.add_paragraph(style='head_paragraph')
document.save('newFile.docx')
When I open newFIle.docx, the first line is blank and my text starts on the second line. How do I prevent the newline from showing up?
A new document created using Document() contains a single empty paragraph. The Open XML .docx standard requires at least one paragraph in the w:body element in the XML, so there's no way around that.
You can treat the first paragraph specially, getting it with document.paragraphs[0], adding content to it, and only then adding new paragraphs.
Or, you can call Document._body.clear_content() once at the beginning to empty out all content, including that one blank paragraph. If you save without adding any paragraphs after calling this though the resulting document will raise an error when you try to open it in Word. Also, the _body attribute on Document is an "internal" and subject to change, so you might not want to put it into code that's going into wide production.
Most helpful comment
A new document created using
Document()contains a single empty paragraph. The Open XML .docx standard requires at least one paragraph in thew:bodyelement in the XML, so there's no way around that.You can treat the first paragraph specially, getting it with
document.paragraphs[0], adding content to it, and only then adding new paragraphs.Or, you can call
Document._body.clear_content()once at the beginning to empty out all content, including that one blank paragraph. If you save without adding any paragraphs after calling this though the resulting document will raise an error when you try to open it in Word. Also, the _body attribute on Document is an "internal" and subject to change, so you might not want to put it into code that's going into wide production.