OpenXML 和 C# docx 文件的默认字体是 Times New Roman

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

我使用带有 Nuget 包 openXML 工具的 .NET 5.0 在 C# 中编写了一些代码,由于某种原因,当我将文件合并在一起时,字体在合并之前会自行更改为 Times New Roman在校准中。这是我的代码:

 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);

}

根据我的研究,OpenXml SDK目前不支持svg格式的图片。

你可以从下面的link中得知:

Add SVG as ImagePartType for Office 2016 support

不过,我找到了另一种方法,可以将 svg 图片插入到 docx 文件中。

首先,请安装nuget-package->Aspose.Words.

其次,你可以试试下面的代码来做

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");

最后,可以得到一个docx文件和一个svg文件组合而成的docx文件。

此外,生成的docx文件会有Aspose.Words左右的广告格式。您可以转到插入 > 页眉或页脚,然后 select 删除页眉或删除页脚将其删除。