Apply FontSize for the contents inside the run using Open XML SDK 2.0

Description:

In this blog you will see how to apply FontSize for the contents inside the  run using Open XML SDK 2.0

Assembly:

DocumentFormat.OpenXml.dll

Namesapces:

using DocumentFormat.OpenXml;

using DocumentFormat.OpenXml.Packaging;

using DocumentFormat.OpenXml.Wordprocessing;

Code:

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using DocumentFormat.OpenXml;

using DocumentFormat.OpenXml.Packaging;

using DocumentFormat.OpenXml.Wordprocessing;

using System.IO.Packaging;

 

namespace OpenXMLConsole

{

    class Program

    {

        static void Main(string[] args)

        {

            string path = @"E:\OpenXMLFontSize.docx";

          

            //// Creates the new instance of the WordprocessingDocument class from the specified file

            //// WordprocessingDocument.Open(String, Boolean) method

            //// Parameters:

            //// string path - path is a string which contains the path of the document

            //// bool isEditable

            using (WordprocessingDocument doc = WordprocessingDocument.Create(path, WordprocessingDocumentType.Document))

            {

                //// Defines the MainDocumentPart             

 

                MainDocumentPart mainDocumentPart = doc.AddMainDocumentPart();

                mainDocumentPart.Document = new Document();

                Body body = mainDocumentPart.Document.AppendChild(new Body());

                Paragraph para = body.AppendChild(new Paragraph());

                Run run =para.AppendChild(new Run());

                RunProperties runProperties = run.AppendChild(new RunProperties());

                FontSize fontSize = new FontSize();

                fontSize.Val = "40";

                runProperties.AppendChild(fontSize);

                run.AppendChild(new Text("Welcome!!!!!"));

                mainDocumentPart.Document.Save();             

            }

        }

    }

}



XML:

 

<?xml version="1.0" encoding="utf-8"?>

<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">

  <w:body>

    <w:p>

      <w:r>

        <w:rPr>

          <w:sz w:val="40" />

        </w:rPr>

        <w:t>Welcome!!!!!</w:t>

      </w:r>

    </w:p>

  </w:body>

</w:document>



Output:

u.jpg


Note:


val (Half Point Measurement): Specifies a positive measurement specified in half-points (1/144 of an inch).
The value in the val attribute is 40, which is equivalent to 20 points (40 half-points).