Search code examples
c#.netvisual-studioopenxml-powertools

OpenXML and C# default font of a docx file is in Times New Roman


I have wrote some code in C# using .NET 5.0 with Nuget package openXML tools and for some reason when I merge the files together the font it merges itself in changes into Times New Roman on its own when the documents before merging were in calibri. Here is my code:

 public static void MergeDocuments(string[] fileNames, string outputFilePath)
{
    using (var outputFileStream = new FileStream(outputFilePath, FileMode.Create, FileAccess.ReadWrite))
    {
        var sources = new List<Source>();

        foreach (string fileName in fileNames)
        {
            byte[] allBytes = File.ReadAllBytes(fileName);

            var openXmlPowerToolsDocument = new OpenXmlPowerToolsDocument(allBytes);

            var source = new Source(new WmlDocument(openXmlPowerToolsDocument), true);

            sources.Add(source);
        }

        MergeXmlDocuments(outputFileStream, sources);
    }

}

public static void MergeXmlDocuments(Stream outStream, List<Source> sources)
{
    WmlDocument buildDocument = DocumentBuilder.BuildDocument(sources);
    buildDocument.WriteByteArray(outStream);
} 

static void Main(string[] args)
{

    string[] files = {"cover.docx", "q3_0_0_5_0.docx", "q2.docx"};
    string outFileName = "merged.docx";
    List<Source> sources = null;
    sources = new List<Source>() // initialize sources that would like to be merged
    {
        new Source(new WmlDocument("../../cover.docx"), true),
        new Source(new WmlDocument("../../q3_0_0_5_0.docx"), true),
        new Source(new WmlDocument("../../q2.docx"), true),

    };

    MergeDocuments(files, outFileName);

}


Solution

  • Based on my research, the OpenXml SDK does not currently have support for the svg format picture.

    You can know it from the following link:

    Add SVG as ImagePartType for Office 2016 support

    However, I find another method to insert the svg pciture to the docx file.

    First, please install nuget-package->Aspose.Words.

    Second, you can try the following code to do it.

    using Aspose.Words;
    using DocumentBuilder = Aspose.Words.DocumentBuilder;
       
    
        Document doc = new Document("D:\\1.docx");
        DocumentBuilder builder = new DocumentBuilder(doc);
        doc.Cleanup();
        builder.InsertImage("D:\\1.svg");
        builder.Writeln();
        doc.Save("test.docx");
    

    Finally, you can get a docx file combined by a docx file and a svg file.

    Besides, the generate docx file will have the advertising format about Aspose.Words. You can Go to Insert > Header or Footer, and then select Remove Header or Remove Footer to remove it.