学习C#调用OpenXml操作word文档的基本用法(31:学习图形类-1)

  文本运行类Run的子类型Drawing用于保存word文档中的图片、图表、形状等图形对象,命名空间为DocumentFormat.OpenXml.Wordprocessing,对应document.xml文件内的元素如下图所示。本文学习使用Drawing类将图片保存到Word文档的基本用法。

  图形类Drawing的类继承链为OpenXmlElement ->
OpenXmlCompositeElement-> Drawing,其主要属性包括以下两个:
  1)Anchor属性:浮动式布局,精确控制图形在页面上的绝对位置,并可选择是否随文字移动;
  2)Inline属性:嵌入式布局,将图形视为一个大的文本字符,跟随文字流排列,并影响行高。
  以嵌入式布局为例,将参考文献5中的图片作为配图插入word文档的末尾,示例代码及运行效果如下所示:

csharp 复制代码
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(sfd.FileName, WordprocessingDocumentType.Document))
{
    MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
    mainPart.Document = new Document();
    Body body = mainPart.Document.AppendChild(new Body());

    Paragraph paragraph = body.AppendChild(new Paragraph());
    Run run = paragraph.AppendChild(new Run());

    for (int i = 0; i < txtContent.Lines.Length; i++)
    {
        Text text = new Text();
        text.Space = SpaceProcessingModeValues.Preserve;
        text.Text = txtContent.Lines[i];
        run.AppendChild(text);

        run.Append(new Break());
    }

    run.Append(new Text("----------------------------------日期:"));

    if (rbShortDate.Checked)
    {
        run.Append(new YearShort());
        run.Append(new Text("-"));
        run.Append(new MonthShort());
        run.Append(new Text("-"));
        run.Append(new DayShort());
    }

    if (rbLongDate.Checked)
    {
        run.Append(new YearLong());
        run.Append(new Text("-"));
        run.Append(new MonthLong());
        run.Append(new Text("-"));
        run.Append(new DayLong());
    }

    run.Append(new Break());

    ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
    using (FileStream stream = new FileStream(picImage.Tag as string, FileMode.Open,FileAccess.Read))
    {
        imagePart.FeedData(stream);
    }
    string relationshipId = mainPart.GetIdOfPart(imagePart);

    Drawing drawing = CreateImageDrawing(relationshipId);
    run.Append(drawing);               
}

public Drawing CreateImageDrawing(string relationshipId)
{
    return new Drawing(
     new DW.Inline(
         new DW.Extent() { Cx = 990000L, Cy = 792000L },
         new DW.EffectExtent()
         {
             LeftEdge = 0L,
             TopEdge = 0L,
             RightEdge = 0L,
             BottomEdge = 0L
         },
         new DW.DocProperties()
         {
             Id = (UInt32Value)1U,
             Name = "Picture 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 = "New Bitmap Image.jpg"
                         },
                         new PIC.NonVisualPictureDrawingProperties()),
                     new PIC.BlipFill(
                         new A.Blip(
                             new A.BlipExtensionList(
                                 new A.BlipExtension()
                                 {
                                     Uri =
                                        "{28A0092B-C50C-407E-A947-70E740481C1C}"
                                 })
                         )
                         {
                             Embed = relationshipId,
                             CompressionState =
                             A.BlipCompressionValues.Print
                         },
                         new A.Stretch(
                             new A.FillRectangle())),
                     new PIC.ShapeProperties(
                         new A.Transform2D(
                             new A.Offset() { X = 0L, Y = 0L },
                             new A.Extents() { Cx = 990000L, Cy = 792000L }),
                         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,
         EditId = "50D07946"
     });
}

参考文献

1https://github.com/dotnet/Open-XML-SDK

2https://learn.microsoft.com/zh-cn/office/open-xml/open-xml-sdk

3https://learn.microsoft.com/zh-cn/dotnet/api/documentformat.openxml.wordprocessing.style?view=openxml-3.0.1

4https://blog.csdn.net/i042416/article/details/126228816

5https://baike.baidu.com/item/静夜思/214

相关推荐
qq_4663024510 小时前
如何在word中添加代码
word
一棵星14 小时前
记一次 Word 转 PDF 功能故障排查与修复
pdf·word
拆房老料2 天前
ONLYOFFICE AI Agent 深度解析:在线 Office 正从编辑器走向智能工作平台
人工智能·中间件·编辑器·word·开源软件
186******205313 天前
PDF 转 Word 高效办公实战指南
pdf·word
patrickpdx4 天前
Word批量修改指定字符的字体
word·word2016
asdzx675 天前
使用 Spire.WordJS 在 React 中实现在线 Word 文档编辑
前端·react.js·word
速易达网络5 天前
在线web文本图片绘图系统
word
zavoryn6 天前
Word 图片如何进入 RAG:Apache POI、MinIO 与 URL 映射
word·agent·rag
AI导出鸭PC端6 天前
预览即导出:告别AI文档格式崩塌,网页预览效果1:1落地Word
人工智能·pdf·word·流程图·豆包·ai导出鸭
asdzx676 天前
使用 Python 精准操控 Word 字体:获取与替换方案
python·c#·word