Dynamic font sizing on word template

Hi Team,

We have a base document in which looks like the attached file. Based out of user inputs from web application we will generate a document based out of the base document for the user, here we need to set this changes to the document dynamically in dot net code. For instance following contents in the attached sample template will undergo following changes.

Title header here - Font size to be changed to 12
Envelop pointed to person - Font size to be changed to 10
Envelop address here Line 2 - Font size to be changed to 12
All Para header and content - Font size to be changed to 8

Content in the header shouldn’t be disturbed. Could be please suggest a code logic to achieve this considering we have control of the base document.

Sample Template with content.docx (62.9 KB)

Thanks,
Karthikeyan

@Karthik_Test_account,
Please use the following code to get desired result:

Document doc = new Document("Sample Template with content.docx");
            
foreach (Paragraph p in doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true))
    p.ParagraphFormat.Style.Font.Size = 8;

Paragraph paragraph = (Paragraph)doc.FirstSection.Body.GetChild(NodeType.Paragraph, 0, true);
paragraph.ParagraphFormat.Style.Font.Size = 12;

paragraph = (Paragraph)doc.FirstSection.Body.GetChild(NodeType.Paragraph, 1, true);
paragraph.ParagraphFormat.Style.Font.Size = 12;
foreach (Run r in paragraph.GetChildNodes(NodeType.Run, true))
{
    r.Font.Size = 10;
    if (r.Text.Contains(ControlChar.LineBreak))
        break;
}

doc.Save("Sample Template with content-output.docx");

Please note that “Envelop pointed to person” line and “Envelop address here Line 2” are located in the same paragraph in your sample template.

Thank you @sergey.lobanov.

Is there a way to apply some styling to a particular paragraph based upon its name or some bookmark name ? If yes can you please share a code sample for that

@Karthik_Test_account,
You can get access to a paragraph by the name of a bookmark, located in this paragraph. For example, if you create a bookmark in the “Title header” paragraph of your sample document, you can change its font size using the following code:

Bookmark b = doc.Range.Bookmarks["Header"]; //"Header" is a name of the bookmark
((Paragraph)b.BookmarkStart.ParentNode).ParagraphFormat.Style.Font.Size = 12;