You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用DocumentFormat.OpenXML向Word文档插入SVG的实现方法咨询

错误原因

你运行报错的核心原因是DocumentFormat.OpenXml.Drawing.Blip的构造函数不直接接收SVG文本内容,它需要传入的是SVG资源在Word文档包中对应的部件关系ID,SVG需要先作为独立的媒体部件存入docx结构中,再通过ID关联到文档内容里的引用节点。

前置依赖

  • 需使用 v2.12 及以上版本的 DocumentFormat.OpenXml NuGet包
  • 生成的docx支持Word 2016及以上版本原生渲染SVG

最简实现示例

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using A = DocumentFormat.OpenXml.Drawing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;
using System.IO;

// 方法:将SVG插入Word文档
public void InsertSvgToWord(string outputDocPath, string svgContent, int widthPx = 600, int heightPx = 400)
{
    // 像素转换为OpenXML通用EMU单位:96DPI下1px = 9525 EMU
    long widthEmu = widthPx * 9525;
    long heightEmu = heightPx * 9525;

    using (WordprocessingDocument doc = WordprocessingDocument.Create(outputDocPath, WordprocessingDocumentType.Document))
    {
        // 初始化文档基础结构
        MainDocumentPart mainPart = doc.AddMainDocumentPart();
        mainPart.Document = new Document(new Body());

        // 新增SVG媒体部件,写入SVG内容
        ImagePart svgPart = mainPart.AddImagePart(ImagePartType.Svg);
        using (Stream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(svgContent)))
        {
            svgPart.FeedData(stream);
        }
        // 获取SVG部件的关系ID
        string svgRelId = mainPart.GetIdOfPart(svgPart);

        // 构造图片引用节点
        var element = new Drawing(
            new DW.Inline(
                new DW.Extent() { Cx = widthEmu, Cy = heightEmu },
                new DW.EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L },
                new DW.DocProperties() { Id = (UInt32Value)1U, Name = "SVG Image 1" },
                new DW.NonVisualGraphicFrameDrawingProperties(new A.GraphicFrameLocks() { NoChangeAspect = true }),
                new A.Graphic(
                    new A.GraphicData(
                        new PIC.Picture(
                            new PIC.NonVisualPictureProperties(
                                new PIC.NonVisualDrawingProperties() { Id = (UInt32Value)0U, Name = "Image.svg" },
                                new PIC.NonVisualPictureDrawingProperties()),
                            new PIC.BlipFill(
                                new A.Blip() { Embed = svgRelId },
                                new A.Stretch(new A.FillRectangle())),
                            new PIC.ShapeProperties(
                                new A.Transform2D(
                                    new A.Offset() { X = 0L, Y = 0L },
                                    new A.Extents() { Cx = widthEmu, Cy = heightEmu }),
                                new A.PresetGeometry(new A.AdjustValueList()) { Preset = A.ShapeTypeValues.Rectangle }))
                    ) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
            ) { DistanceFromTop = (UInt32Value)0U, DistanceFromBottom = (UInt32Value)0U, DistanceFromLeft = (UInt32Value)0U, DistanceFromRight = (UInt32Value)0U });

        // 将图片插入文档末尾
        mainPart.Document.Body.AppendChild(new Paragraph(new Run(element)));
        mainPart.Document.Save();
    }
}

调用示例

// 替换为你自己的SVG字符串
string yourSvgStr = "<svg width='600' height='400' xmlns='http://www.w3.org/2000/svg'><rect width='100%' height='100%' fill='red'/><circle cx='300' cy='200' r='100' fill='blue'/></svg>";
InsertSvgToWord(@"C:\test\output.docx", yourSvgStr, 600, 400);

如果需要兼容2016以下版本的Word,可以额外添加一个PNG格式的备用图片部件,在Blip节点下补充A.BlipExtensionList关联备用资源即可。

内容的提问来源于stack exchange,提问作者Len White

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 02:15:03