在Word文档中添加图像

时间:2019-05-03 10:33:08

标签: c# image ms-word openxml docx

当我在Word文档中添加图像时,当我打开Word时,它向我显示XML错误。无法打开文件,因为内容有问题。

看到错误-> Word Error

我从下面的链接获得了参考。

  

Adding image to word document using OpenXML

并且来自Microsoft网站

  

https://docs.microsoft.com/en-us/office/open-xml/how-to-insert-a-picture-into-a-word-processing-document

我的代码如下:将Open XML添加到您的项目引用中。

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

namespace InsertImageWord
{
    class Program
    {
        static void Main(string[] args)
        {
            //References
            //https://www.e-iceblue.com/Tutorials/Spire.Doc/OpenXML/How-to-Insert-a-picture-into-a-word-processing-document.html
            //https://coders-corner.net/2015/04/11/open-xml-add-a-picture/
            //https://docs.microsoft.com/en-us/office/open-xml/how-to-insert-a-picture-into-a-word-processing-document
            //file name
            string folder = @"E:\TestImage";
            string fileName = folder + @"\BlankDocument.doc";
            string imageFileName = folder + @"\DesertTest.png";

            //create file
            using (var file = WordprocessingDocument.Create(
                fileName, WordprocessingDocumentType.Document))
            {
                file.AddMainDocumentPart();

                //add image part and add image from file
                ImagePart imagePart = file.MainDocumentPart.AddImagePart(ImagePartType.Png);

                using (FileStream stream = new FileStream(imageFileName, FileMode.Open))
                {
                    imagePart.FeedData(stream);
                }

                //set content
                var text = new Text("Hello Open XML world");
                var run = new Run(text);
                var paragraph = new Paragraph(run);
                var body = new Body(paragraph);
                var document = new Document(body);

                //add image
                Drawing imageElement = GetImageElement(
                    file.MainDocumentPart.GetIdOfPart(imagePart),
                    imageFileName,
                    "my image",
                    22,
                    22);

                body.AppendChild(new Paragraph(new Run(imageElement)));

                //save
                file.MainDocumentPart.Document = document;
                file.MainDocumentPart.Document.Save();
            }
        }

        private static Drawing GetImageElement(
            string imagePartId,
            string fileName,
            string pictureName,
            double width,
            double height)
        {
            double englishMetricUnitsPerInch = 914400;
            double pixelsPerInch = 96;

            //calculate size in emu
            double emuWidth = width * englishMetricUnitsPerInch / pixelsPerInch;
            double emuHeight = height * englishMetricUnitsPerInch / pixelsPerInch;

            var element = new Drawing(
                new DW.Inline(
                    new DW.Extent { Cx = (Int64Value)emuWidth, Cy = (Int64Value)emuHeight },
                    new DW.EffectExtent { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L },
                    new DW.DocProperties { Id = (UInt32Value)1U, Name = pictureName },
                    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 = fileName },
                                    new PIC.NonVisualPictureDrawingProperties()),
                                new PIC.BlipFill(
                                    new A.Blip(
                                        new A.BlipExtensionList(
                                            new A.BlipExtension { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" }))
                                    {
                                        Embed = imagePartId,
                                        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 = (Int64Value)emuWidth, Cy = (Int64Value)emuHeight }),
                                    new A.PresetGeometry(
                                        new A.AdjustValueList())
                                    { Preset = A.ShapeTypeValues.Rectangle })))
                        {
                            Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"
                        }))
                {
                    DistanceFromTop = 0U,
                    DistanceFromBottom = 0U,
                    DistanceFromLeft = 0U,
                    DistanceFromRight = 0U,
                    EditId = "50D07946"
                });
            return element;
        }

    }
}

请帮助我。在此先感谢

1 个答案:

答案 0 :(得分:1)

您的imageparttype必须与您的图像的模仿类型匹配 enter image description here enter image description here