学习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

相关推荐
俊哥工具1 天前
电脑怎么玩手机APP?超简单新手教程
pdf·电脑·word·excel·音视频
E_ICEBLUE1 天前
Python 办公自动化:如何轻松调整 Word/PDF 页面大小为 Legal 尺寸
python·pdf·word
vancece1 天前
新时代的 AI 教育体系 - 全开源:Word Teacher 英语口语训练
人工智能·开源·word
aaaffaewrerewrwer2 天前
一个真正可玩、可分享、可自定义的在线单词搜索游戏网站(Word Search Puzzles)
游戏·word
tedcloud1232 天前
codegraph部署教程:构建代码库语义分析环境
服务器·人工智能·word·excel
江畔柳前堤2 天前
XZ09_Word和MD格式转换
开发语言·数据库·人工智能·python·深度学习·word
yurenpai(27届找实习中)2 天前
Spring AI 实战:从零实现 AI 对话的记忆与历史记录管理(附源码级解析)
java·spring·ai·prompt·word
庖丁AI2 天前
文档比对工具怎么选?Word、PDF、扫描件差异检测思路
pdf·word·扫描件·文档比对
tedcloud1233 天前
DeepSeek-TUI部署教程:打造CLI AI助手环境
服务器·人工智能·word·excel·dreamweaver
aihuangwu3 天前
AI导出鸭|ChatGPT与Gemini生成Word文档技术实操
人工智能·ai·chatgpt·word·deepseek·ai导出鸭