简体   繁体   中英

Adding image in word document

When I add an image to a word document then, when I open word it is showing me an XML error. The file cannot be opened because there is a problem with the content.

See error -> 字错误

I took reference from the below link.

Adding image to word document using OpenXML

and from Microsoft site

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

My Code is as follows : add Open XML to your project reference.

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

    }
}

Please help me out of this. Thanks in Advance

your imageparttype has to match the mimetype of your image 在此处输入图片说明 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM