Aspose Words Python Docx Header Default Font

Hi,

How can I set the default font for my headers to be Calibri when saving a Document?

I have been able to do it for regular paragraphs but it is not working for headings (headings seem to always be defaulted to Times New Roman).

Thanks

@camelBackNotation You should update styles in the document. Please see the following code:

doc = aw.Document()
builder = aw.DocumentBuilder(doc)

# update styles
heading1 = doc.styles.get_by_style_identifier(aw.StyleIdentifier.HEADING1)
heading1.font.bold = True
heading1.font.size = 16
# set other properties of the heading style....
#.......
normal = doc.styles.get_by_style_identifier(aw.StyleIdentifier.NORMAL)
normal.font.bold = False
normal.font.size = 12

builder.paragraph_format.style_identifier = aw.StyleIdentifier.HEADING1
builder.writeln("Heading 1")

builder.paragraph_format.style_identifier = aw.StyleIdentifier.NORMAL
builder.writeln("Text 1")

builder.paragraph_format.style_identifier = aw.StyleIdentifier.HEADING1
builder.writeln("Heading 2")

doc.save("C:\\Temp\\out.docx")

Will this work if I am loading the document from HTML (as opposed to building it programmatically).

e.g. can I add that to the following code? I only want to set the default font when there is not one already set in the HTML element.

def convert_html_to_docx(html_content: str) -> BytesIO:
    doc = aw.Document(BytesIO(html_content.encode("utf-8")))
    doc.copy_styles_from_template(uspto_docx_template)

    docx_bytes_io = BytesIO()
    doc.save(docx_bytes_io, aw.SaveFormat.DOCX)
    docx_bytes_io.seek(0)

    return docx_bytes_io

@camelBackNotation Could you please attach your HTML here for testing? We will check it and provide you more information.

Sure.

'<p>This is the first paragraph</p>\n<h1 style="text-align: center;">Heading 1</h1>\n<p>This is the second paragraph</p>\n<h2>Heading 2</h2>'

@camelBackNotation Font is set explicitly in the Run nodes. So you should use the following code:

doc = aw.Document("C:\\Temp\\in.html")

for node in doc.get_child_nodes(aw.NodeType.PARAGRAPH, True) :
    para = node.as_paragraph()
    if para.paragraph_format.is_heading :
        # clear explicit font formatting of the heading paragraph.
        for run in para.runs :
            run.as_run().font.clear_formatting()

# update styles
heading1 = doc.styles.get_by_style_identifier(aw.StyleIdentifier.HEADING1)
heading1.font.bold = True
heading1.font.size = 16
heading1.font.name = "Calibri"

heading2 = doc.styles.get_by_style_identifier(aw.StyleIdentifier.HEADING2)
heading2.font.bold = True
heading2.font.size = 16
heading2.font.name = "Calibri"

doc.save("C:\\Temp\\out.docx")

Thanks @alexey.noskov

A similar related question. When converting docx to html, is it possible to preserve the font? The font seems to be preserved when going from html to docx.

@camelBackNotation Aspose.Words preserves font and other formatting upon conversion DOCX to HTML.