none
Two questions about a specific docx file RRS feed

  • Question

  • Hello

    I have created this file using openxml sdk. This is highlight of main parts of code:

                            MemoryStream stream = new MemoryStream();
                            using (WordprocessingDocument myDoc = WordprocessingDocument.Create( stream, WordprocessingDocumentType.Document,true))
                            {
                                MainDocumentPart mainPart = myDoc.AddMainDocumentPart();
                                mainPart.Document = new Document();
                                Body body = new Body();
                                mainPart.Document.Body = body;
    
                                Paragraph P1 = new Paragraph(new Run(new Text()));
                                body.AppendChild(P1);
    
    
                                mainPart.Document.Save();
                            }
    
                            stream.Seek(0, SeekOrigin.Begin);
    

    My two questions:

    1- When opening the file using Microsoft word, I receive a warning about file is corrupt, but word can recover it. What shall I do to eliminate this error message?

    2- Height of table rows is almost twice of text content. How can I remove empty space under text in table cells?

    Thanks

    Saturday, January 27, 2018 5:14 PM

Answers

  • Since none of the code you posted has anything to do with inserting a table, table rows or cells, it is impossible to tell what your code is doing wrong. A guess, based on points (a) and (b), is that you have a loop that uses 1-based indexing when it needs to use 0-based indexing, and
     1. only starts populating table cells from cell 2 ("1" in a 0-based list)
     2. populates from cell 2 to cell 11, rather than cell 1 to cell 10.

    I looked at the XML for the first row in your table and noticed the following:
     a. the XML for the first cell is like this:

    <w:tc>
      <w:tcPr><w:tcW w:w="350" w:type="dxa" /><w:shd w:val="clear" w:fill="f0f0f0" /><w:vAlign w:val="center" />
      </w:tcPr>
    </w:tc>

    This is enough to make the whole file invalid and cause an XML-related message when you open it. You need the XML Element for a paragraph in there - at least something like this:

    <w:tc>
      <w:tcPr><w:tcW w:w="350" w:type="dxa" /><w:shd w:val="clear" w:fill="f0f0f0" /><w:vAlign w:val="center" />
      </w:tcPr>
      <w:p/>
    </w:tc>

     b. You seem to have specified column widths for 10 columns, but there are actually 11 cells. That does not cause an error but it may not be what you want.

     c. The paragraphs in the cells do not have any references to paragraph styles. When Word opens the file, it will probably decide that the paragraphs should be formatted using the "Normal" style. If it has "space after" defined in its paragraph settings, that space after will be applied to the paragraphs in each cell. I think that by default, Normal currently has 8pt space following the paragraph, so that is probably what you are seeing. The "correct" way to fix that is probably to define a style, add it to the document and apply that style to each paragraph, but I am not familiar enough with the OOXML SDK to tell you how to do that. I can only tell you what the resulting XML needs to look like (approximately). So another way would be to add the following Paragraph parameter to each paragraph:
    <w:spacing w:after="0"/>

    e.g. if you already have

    <w:p>
      <w:pPr><other stuff></w:pPr>
    </w:p>

    then change it to 

    <w:p>
      <w:pPr><other stuff><w:spacing w:after="0"/></w:pPr>
    </w:p>

    If you do not have a <w:pPr/> element for the paragraph, e.g. you have

    <w:p></w:p>

    then change it to 

    <w:p><w:pPr><w:spacing w:after="0"/></w:pPr></w:p>

    These problems could be repeated in rows after row 1, or there could be additional problems.


    Peter Jamieson



    • Marked as answer by Alireza78 Monday, January 29, 2018 6:54 PM
    • Edited by Peter Jamieson Wednesday, January 31, 2018 6:33 PM
    Sunday, January 28, 2018 12:12 PM
  • Sorry it took a while - perhaps you have found a fix already anyway?

    Going through the XML and comparing it with an example created via the User Interface, it seems that the following things need to be there to make Word open the .docx. I cannot give you the precise values that need to be in there, but perhaps you can determine what your code needs to add to ensure these elements and attributes are present:In the <wp:anchor> element, you need a relativeHeight attribute, e.g.

    <wp:anchor distT="0" distL="0" simplePos="0" behindDoc="0" locked="0" relativeHeight="251658240" layoutInCell="0" allowOverlap="1"
     xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing">

    I do not know what the parameter should be - as far as I know it is a Z-ordering so it may just need to be present.

    Immediately below that, you need the following elements 

    <wp:simplePos x="0" y="0"/>
    <wp:positionH relativeFrom="column">
      <wp:posOffset>4445</wp:posOffset>
    </wp:positionH>
    <wp:positionV relativeFrom="paragraph">
      <wp:posOffset>3175</wp:posOffset>
    </wp:positionV>

    Below the <wp:extent> element you need the following:

    <wp:wrapSquare wrapText="bothSides"/>
    <wp:docPr id="1" name="Picture 2"/>

    (There may be other elements than "wrapsquare" that are more appropriate in your case - I have not checked. In the docrPr element, the id and name attributes need to be there. My guess is that the id attribute value is supposed to match the id value in the pic:cNvPr element further down, and possibly selects a specific image in the images subfolder within your .docx. The name is probably "any name you want")

    That is enough here to allow Word to open the file. If you find you have to do this stuff yourself, making the document example as simple as possible (ideally, a single table cell) makes it a lot easier to investigate what is wrong. IME detecting schema errors is the easier part, as Word's dialog box usually indicates a line and character number in that case. Beyond that, you tend to get the "line 0, character 0" response which isn't helpful. 

    Manual insertion via the UI inserts other elements but they do not appear to be essential.

    To pick up on an earlier point, I do not know why your code worked before but now does not. I wondered whether it might be to do with different versions of the Office Open XML SDK (say, 2.5 and 2.8) generating different code, particularly since the handling of graphics in Word has changed over the last few major versions. But that's also just a guess.



    Peter Jamieson

    Friday, February 2, 2018 10:49 AM
  • The image will end up inside the cell if you change

    LayoutInCell = false,

    to

    LayoutInCell =true,


    Peter Jamieson

    • Marked as answer by Alireza78 Tuesday, February 6, 2018 1:18 PM
    Tuesday, February 6, 2018 12:11 PM

All replies

  • Since none of the code you posted has anything to do with inserting a table, table rows or cells, it is impossible to tell what your code is doing wrong. A guess, based on points (a) and (b), is that you have a loop that uses 1-based indexing when it needs to use 0-based indexing, and
     1. only starts populating table cells from cell 2 ("1" in a 0-based list)
     2. populates from cell 2 to cell 11, rather than cell 1 to cell 10.

    I looked at the XML for the first row in your table and noticed the following:
     a. the XML for the first cell is like this:

    <w:tc>
      <w:tcPr><w:tcW w:w="350" w:type="dxa" /><w:shd w:val="clear" w:fill="f0f0f0" /><w:vAlign w:val="center" />
      </w:tcPr>
    </w:tc>

    This is enough to make the whole file invalid and cause an XML-related message when you open it. You need the XML Element for a paragraph in there - at least something like this:

    <w:tc>
      <w:tcPr><w:tcW w:w="350" w:type="dxa" /><w:shd w:val="clear" w:fill="f0f0f0" /><w:vAlign w:val="center" />
      </w:tcPr>
      <w:p/>
    </w:tc>

     b. You seem to have specified column widths for 10 columns, but there are actually 11 cells. That does not cause an error but it may not be what you want.

     c. The paragraphs in the cells do not have any references to paragraph styles. When Word opens the file, it will probably decide that the paragraphs should be formatted using the "Normal" style. If it has "space after" defined in its paragraph settings, that space after will be applied to the paragraphs in each cell. I think that by default, Normal currently has 8pt space following the paragraph, so that is probably what you are seeing. The "correct" way to fix that is probably to define a style, add it to the document and apply that style to each paragraph, but I am not familiar enough with the OOXML SDK to tell you how to do that. I can only tell you what the resulting XML needs to look like (approximately). So another way would be to add the following Paragraph parameter to each paragraph:
    <w:spacing w:after="0"/>

    e.g. if you already have

    <w:p>
      <w:pPr><other stuff></w:pPr>
    </w:p>

    then change it to 

    <w:p>
      <w:pPr><other stuff><w:spacing w:after="0"/></w:pPr>
    </w:p>

    If you do not have a <w:pPr/> element for the paragraph, e.g. you have

    <w:p></w:p>

    then change it to 

    <w:p><w:pPr><w:spacing w:after="0"/></w:pPr></w:p>

    These problems could be repeated in rows after row 1, or there could be additional problems.


    Peter Jamieson



    • Marked as answer by Alireza78 Monday, January 29, 2018 6:54 PM
    • Edited by Peter Jamieson Wednesday, January 31, 2018 6:33 PM
    Sunday, January 28, 2018 12:12 PM
  • Hi Alireza78,

    With the part of code, We are not able to find the issue for the corruption in your file.

    I suggest you to Share your sample project with us and the Word file on which you run the code.

    We will try to run the project and try to make a test with that file.

    It will be helpful for us to find the issue in your code and we can provide a solid suggestions to solve the issue.

    Thanks for your understanding.

    Regards

    Deepak


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, January 29, 2018 3:22 AM
    Moderator
  • Hello

    Code is quite complicated. I tried to summarize it and problem of corrupted file was solved in simplified version. So, I must work on it for a little bit more and hopefully I will solve it by myself or I will ask a separate question after finding exact location of problem. Now, My second question may be answered easily regarding the following simplified code:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using DocumentFormat.OpenXml;
    using DocumentFormat.OpenXml.Wordprocessing;
    using DocumentFormat.OpenXml.Packaging;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                MemoryStream stream = new MemoryStream();
                using (WordprocessingDocument myDoc = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document, true))
                {
                    MainDocumentPart mainPart = myDoc.AddMainDocumentPart();
                    mainPart.Document = new Document();
                    Body body = new Body();
                    mainPart.Document.Body = body;
    
                    Paragraph P = new Paragraph(new Run(new Text()));
                    body.AppendChild(P);
    
                    Table table = new Table();
                    body.AppendChild(table);
    
                    TableProperties tableProperties1 = new TableProperties();
                    table.Append(tableProperties1);
    
                    TableGrid tableGrid1 = new TableGrid();
                    table.Append(tableGrid1);
    
                    List<int> Widths = new List<int>() {800,800,800,800,800,800 };
    
                    foreach (int s1 in Widths)
                    {
                        tableGrid1.Append(new GridColumn() { Width = (s1).ToString() });
                    }
    
                    DocumentFormat.OpenXml.Wordprocessing.TableRow tableRow1 = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
                    table.Append(tableRow1);
    
                    for (short i = 0; i < 6; i++)
                    {
                        TableCell tc = CreateCell(TableVerticalAlignmentValues.Center, "f0f0f0", Widths[i]);
                        tc.Append(CreateParagrapgh(i.ToString(), JustificationValues.Center, "Calibri", 20, "808080", false, false, false, false, UnderLineSettings.None, false));
                        tableRow1.AppendChild(tc);
                    }
    
                    
    
                    Paragraph P1 = new Paragraph(new Run(new Text()));
                    body.AppendChild(P1);
    
                    mainPart.Document.Save();
                }
    
                stream.Seek(0, SeekOrigin.Begin);
                using (FileStream file = new FileStream("D:\\r.docx", FileMode.Create, System.IO.FileAccess.Write))
                    stream.CopyTo(file);
    
    
            }
    
            private static Paragraph CreateParagrapgh(string text, JustificationValues HorizontalAlign, string font, int Size_HalfPoints, string Color, bool IsItalic, bool IsBold, bool IsSubscript, bool IsSuperscript, UnderLineSettings Underline, bool isStrike)
            {
                RunProperties runProp = new RunProperties();
                if (!string.IsNullOrEmpty(font))
                {
                    runProp.AppendChild(new RunFonts() { Ascii = font });
                    runProp.AppendChild(new FontSize() { Val = new StringValue(Size_HalfPoints.ToString()) });
                }
                else
                {
                    runProp.AppendChild(new RunFonts() { Ascii = "Calibri" });
                    runProp.AppendChild(new FontSize() { Val = new StringValue("22") });
                }
    
                if (!string.IsNullOrEmpty(Color))
                    runProp.AppendChild(new Color() { Val = Color });
                else
                    runProp.AppendChild(new Color() { Val = "000000" });
    
                if (IsBold)
                    runProp.AppendChild(new Bold() { });
                if (IsItalic)
                    runProp.AppendChild(new Italic { });
    
                if (IsSubscript)
                    runProp.AppendChild(new VerticalTextAlignment() { Val = VerticalPositionValues.Subscript });
                if (IsSuperscript)
                    runProp.AppendChild(new VerticalTextAlignment() { Val = VerticalPositionValues.Superscript });
    
                if (Underline == UnderLineSettings.Single | Underline == UnderLineSettings.SingleAccounting)
                    runProp.AppendChild(new Underline() { Val = UnderlineValues.Single });
                if (Underline == UnderLineSettings.Double | Underline == UnderLineSettings.DoubleAccounting)
                    runProp.AppendChild(new Underline() { Val = UnderlineValues.Double });
    
                if (isStrike)
                    runProp.AppendChild(new Strike());
    
    
                runProp.AppendChild(new Text(text));
                Run run = new Run();
                run.PrependChild<RunProperties>(runProp);
    
                Paragraph P = new Paragraph();
                ParagraphProperties Prp = new ParagraphProperties();
                Prp.AppendChild(new Justification() { Val = HorizontalAlign });
    
                P.AppendChild(Prp);
                P.AppendChild(run);
    
                return P;
            }
            private static TableCell CreateCell(TableVerticalAlignmentValues VAlign, string BGColor, int width)
            {
                Shading shading1 = new Shading() { Val = ShadingPatternValues.Clear };
                if (!string.IsNullOrEmpty(BGColor))
                    shading1.Fill = BGColor;
    
                TableCellProperties tableCellProperties1 = new TableCellProperties();
                tableCellProperties1.Append(new TableCellWidth() { Width = width.ToString(), Type = TableWidthUnitValues.Dxa });
                tableCellProperties1.Append(shading1);
                tableCellProperties1.Append(new TableCellVerticalAlignment() { Val = VAlign });
    
    
                TableCell tableCell1 = new TableCell();
                tableCell1.RemoveAllChildren();
                tableCell1.Append(tableCellProperties1);
                return tableCell1;
            }
    
        }
    
    
        public enum UnderLineSettings
        {
            None = 0,
            Single = 1,
            SingleAccounting = 33,
            Double = 2,
            DoubleAccounting = 34
        }
    }

    My question: How can I reduce row height to exactly fit content? Seems row height is set for two lines while my ctext is one line.

    Thanks in advance.
    • Edited by Alireza78 Monday, January 29, 2018 5:37 PM
    Monday, January 29, 2018 5:36 PM
  • Hello and thanks for your cooperation

    A part of your guesses were completely correct. I modified number of "Column widths" to match number of "Columns" AND I added an empty paragraph to empty cells. The result:

    I noticed that there is a problem in cells that contain anchor for drawings. In first try I removed every drawing from docx file and file was OK without any corrupt warning. Greate.

    Then I added drawings again and this time corrupted file was so damaged that word could not even recover it. So, now the only problem lies in 3 images inserted in file.

    I have uploaded the file called R2 in the same location and this is the part of code used for inserting the images:

            private static void AddImageToBody(string relationshipId, int Width, int Height, int deltax, int deltay, OpenXmlElement AnchorBase)
            {
                DW.Anchor anchor1 = new DW.Anchor()
                {
                    DistanceFromTop = (UInt32Value)0U,
                    //DistanceFromBottom = (UInt32Value)0U,
                    DistanceFromLeft = (UInt32Value)0U,
                    //DistanceFromRight = (UInt32Value)0U,
                    SimplePos = false,
                    //RelativeHeight = (UInt32Value)251658240U,
                    BehindDoc = false,
                    Locked = false,
                    LayoutInCell = false,
                    AllowOverlap = true//,
                    //EditId = "50D07946"
                };
    
                PIC.NonVisualPictureProperties NVPP = new PIC.NonVisualPictureProperties
                    (
                        new PIC.NonVisualDrawingProperties() { Id = (UInt32Value)0U, Name = "New Bitmap Image.jpg" },
                        new PIC.NonVisualPictureDrawingProperties()
                    );
                PIC.BlipFill BF = 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())
                    );
                PIC.ShapeProperties SP = new PIC.ShapeProperties(new A.Transform2D(new A.Offset() { X = deltax * 9525, Y = deltay * 9525 }, new A.Extents() { Cx = Width * 9525, Cy = Height * 9525 }), new A.PresetGeometry(new A.AdjustValueList()) { Preset = A.ShapeTypeValues.Rectangle });
                A.GraphicData GD = new A.GraphicData(new PIC.Picture(NVPP, BF, SP)) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" };
    
                anchor1.Append(new DW.Extent() { Cx = Width * 9525, Cy = Height * 9525 });
                //anchor1.Append(new DW.EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L });
                //anchor1.Append(new DW.DocProperties() { Id = (UInt32Value)1U, Name = "Picture 1" });
                anchor1.Append(
                    new DW.NonVisualGraphicFrameDrawingProperties(new A.GraphicFrameLocks() { NoChangeAspect = true })
                    );
                anchor1.Append(new A.Graphic(GD));
                Drawing drawing1 = new Drawing();
                drawing1.Append(anchor1);
    
                AnchorBase.ChildElements[0].AppendChild(drawing1);
            }

    I have adopted the code from this address. You see some lines are commented out, that is because I had no profound understanding of all parts of this code and I managed to make the things work by try and error on main code. This used to work in previous version, but not anymore with modified file.

    If you look at the xml file in this online viewer , you will notice that indentation of xml tags is changed in cells that have anchor object as a child, but I can't figure it out what the problem is.

    I will be thankful if you could take a look.

    Man thanks in advance

    Monday, January 29, 2018 6:54 PM
  •  I have had a look at this and generated my own sample file with similar XML encoding for comparison, but so far I have not been able to see exactly what is causing the problem.

    One thing I noticed is that the sequence of the generatd XML is not the same as the sequence that Word generates. In fact, I noticed this before with the simpler cells which had no image content (or anchors to be precise). What I mean is that within the cell, you often have a <w:r> run where the <w:t> is actually enclosed in the <w:rPr> Element, e.g.

    <w:r>
      <w:rPr>
        ...some run parameters
        <w:t>some text</w:t>
      </w:rPr>
    </w:r>

    Personally, I did not think that was allowed, and I was surprised that it worked, but had to assume that it must be OK according to the schema.

    I think it should be

    <w:r>
      <w:rPr>
        ...some run parameters
      </w:rPr>
      <w:t>some text</w:t>
    </w:r>

    But the same thing is happening with the images (i.e. the <w:drawing> is inside the <w::rPr> instead of after it. Perhaps Word allows text to be inside the rPr but not drawing. I don't know. As usual, Word sometimes indicates the location of an XML error (useful) and sometimes does not (useless) so it is hard to pin down.

    Anyway, I have not had time to look at your code to see what might be causing that result, but that is the first place I would look.

    The other question I have for you is whether in fact you are inserting the shapes the way you really want them. Often, people use inline shapes because then the table cell expands to fit them. With floating images I do not believe that happens. However, the XML coding for inline shapes is somewhat different from the code for floating shapes and the C# code would probably need to be rather different too.

    I will try to have another look tomorrow and see if I can spot what I have missed so far. 


    Peter Jamieson

    Tuesday, January 30, 2018 6:11 PM
  • Thanks for your reply

    About Text element inside of RunProperties, instead of inside of Run, You are right. Again it was adopted from online samples, and it was the only way it used to work. By the way, Now I have modified it.

    				<w:tc>
    					<w:tcPr>
    						<w:tcW w:w="350" w:type="dxa" />
    						<w:shd w:val="clear" w:fill="f0f0f0" />
    						<w:vAlign w:val="center" />
    					</w:tcPr>
    					<w:p>
    						<w:pPr>
    							<w:jc w:val="center" />
    						</w:pPr>
    						<w:r>
    							<w:rPr>
    								<w:rFonts w:ascii="Calibri" />
    								<w:sz w:val="20" />
    								<w:color w:val="808080" />
    							</w:rPr>
    							<w:t></w:t>
    						</w:r>
    					</w:p>
    				</w:tc>

    And I also have modified the insertion point of drawing object:

    					<w:tc>
    						<w:tcPr>
    							<w:tcW w:w="2130" w:type="dxa" />
    							<w:shd w:val="clear" w:fill="FFFFFF" />
    							<w:vAlign w:val="bottom" />
    							<w:tblBorders />
    							<w:vMerge w:val="restart" />
    						</w:tcPr>
    						<w:p>
    							<w:pPr>
    								<w:jc w:val="center" />
    							</w:pPr>
    							<w:r>
    								<w:rPr>
    									<w:rFonts w:ascii="Calibri" />
    									<w:sz w:val="22" />
    									<w:color w:val="000000" />
    								</w:rPr>
    								<w:t></w:t>
    							</w:r>
    							<w:drawing>
    								<wp:anchor distT="0" distL="0" simplePos="0" behindDoc="0" locked="0" layoutInCell="0" allowOverlap="1"
    									xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing">
    									<wp:extent cx="3276600" cy="1809750" />
    									<wp:cNvGraphicFramePr>
    										<a:graphicFrameLocks noChangeAspect="1"
    											xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" />
    										</wp:cNvGraphicFramePr>
    										<a:graphic
    											xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
    											<a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">
    												<pic:pic
    													xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture">
    													<pic:nvPicPr>
    														<pic:cNvPr id="0" name="New Bitmap Image.jpg" />
    														<pic:cNvPicPr />
    													</pic:nvPicPr>
    													<pic:blipFill>
    														<a:blip r:embed="Ra4be2fb8a4fc4e70" cstate="print"
    															xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
    															<a:extLst>
    																<a:ext uri="{28A0092B-C50C-407E-A947-70E740481C1C}" />
    															</a:extLst>
    														</a:blip>
    														<a:stretch>
    															<a:fillRect />
    														</a:stretch>
    													</pic:blipFill>
    													<pic:spPr>
    														<a:xfrm>
    															<a:off x="0" y="0" />
    															<a:ext cx="3276600" cy="1809750" />
    														</a:xfrm>
    														<a:prstGeom prst="rect">
    															<a:avLst />
    														</a:prstGeom>
    													</pic:spPr>
    												</pic:pic>
    											</a:graphicData>
    										</a:graphic>
    									</wp:anchor>
    								</w:drawing>
    							</w:p>
    						</w:tc>

    I have also uploaded the modified file, called R3.docx to the same location.

    Many thanks for your patient answers.

    Tuesday, January 30, 2018 9:18 PM
  • Sorry it took a while - perhaps you have found a fix already anyway?

    Going through the XML and comparing it with an example created via the User Interface, it seems that the following things need to be there to make Word open the .docx. I cannot give you the precise values that need to be in there, but perhaps you can determine what your code needs to add to ensure these elements and attributes are present:In the <wp:anchor> element, you need a relativeHeight attribute, e.g.

    <wp:anchor distT="0" distL="0" simplePos="0" behindDoc="0" locked="0" relativeHeight="251658240" layoutInCell="0" allowOverlap="1"
     xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing">

    I do not know what the parameter should be - as far as I know it is a Z-ordering so it may just need to be present.

    Immediately below that, you need the following elements 

    <wp:simplePos x="0" y="0"/>
    <wp:positionH relativeFrom="column">
      <wp:posOffset>4445</wp:posOffset>
    </wp:positionH>
    <wp:positionV relativeFrom="paragraph">
      <wp:posOffset>3175</wp:posOffset>
    </wp:positionV>

    Below the <wp:extent> element you need the following:

    <wp:wrapSquare wrapText="bothSides"/>
    <wp:docPr id="1" name="Picture 2"/>

    (There may be other elements than "wrapsquare" that are more appropriate in your case - I have not checked. In the docrPr element, the id and name attributes need to be there. My guess is that the id attribute value is supposed to match the id value in the pic:cNvPr element further down, and possibly selects a specific image in the images subfolder within your .docx. The name is probably "any name you want")

    That is enough here to allow Word to open the file. If you find you have to do this stuff yourself, making the document example as simple as possible (ideally, a single table cell) makes it a lot easier to investigate what is wrong. IME detecting schema errors is the easier part, as Word's dialog box usually indicates a line and character number in that case. Beyond that, you tend to get the "line 0, character 0" response which isn't helpful. 

    Manual insertion via the UI inserts other elements but they do not appear to be essential.

    To pick up on an earlier point, I do not know why your code worked before but now does not. I wondered whether it might be to do with different versions of the Office Open XML SDK (say, 2.5 and 2.8) generating different code, particularly since the handling of graphics in Word has changed over the last few major versions. But that's also just a guess.



    Peter Jamieson

    Friday, February 2, 2018 10:49 AM
  • Hello and thanks a lot for your cooperation. In fact I had stopped this part and was working on another essential part for a while. was not expecting you to follow this matter and I'm really happy and grateful for it. I will try it and update here.

    The reason previous versions worked: my guess: when an empty paragraph was not present in empty cells, word was starting another (maybe more intense) version of recovery.

    I will Update you here.

    Friday, February 2, 2018 2:51 PM
  • Hi Alireza78,

    Once you finish your testing, try to update the status of this thread.

    We will try to provide further suggestions, If needed.

    Regards

    Deepak 


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, February 5, 2018 9:08 AM
    Moderator
  • Hello

    Sorry for delay. Thanks to peter, those suggestions worked. I have uploaded the file R4.docx here .

    There are two problems with suggested approach:

    1- picture is inline with text. For this problem, I will make comparisons to standard word document to see how to solve it.

    2- Most important: picture is positioned relative to page, instead of related to cell. This is the way that word also arranges the document, so for this one, I may not be easily able to find solution.

    This is the code:

            private static void AddImageToBody(string relationshipId, int Width, int Height, int deltax, int deltay, OpenXmlElement AnchorBase)
            {
                DW.Anchor anchor1 = new DW.Anchor()
                {
                    DistanceFromTop = (UInt32Value)0U,
                    DistanceFromBottom = (UInt32Value)0U,
                    DistanceFromLeft = (UInt32Value)0U,
                    DistanceFromRight = (UInt32Value)0U,
                    SimplePos = false,
                    RelativeHeight = (UInt32Value)251658240U,
                    BehindDoc = false,
                    Locked = false,
                    LayoutInCell = false,
                    AllowOverlap = true
                };
                anchor1.Append(new DocumentFormat.OpenXml.Drawing.Wordprocessing.SimplePosition() { X=0,Y=0 });
                anchor1.Append(new DW.HorizontalPosition() { RelativeFrom = DW.HorizontalRelativePositionValues.Column, PositionOffset = new DW.PositionOffset() { Text="0" } });
                anchor1.Append(new DW.VerticalPosition() { RelativeFrom = DW.VerticalRelativePositionValues.Paragraph, PositionOffset = new DW.PositionOffset() { Text = "0" } });
                anchor1.Append(new DW.Extent() { Cx = Width * 9525, Cy = Height * 9525 });
                anchor1.Append(new DocumentFormat.OpenXml.Drawing.Wordprocessing.WrapSquare() { WrapText=DW.WrapTextValues.BothSides });
                anchor1.Append(new DW.DocProperties() { Id = (UInt32Value)1U, Name = "Picture 1" });
                anchor1.Append(new DW.NonVisualGraphicFrameDrawingProperties(new A.GraphicFrameLocks() { NoChangeAspect = true }));
    
                #region GraphicData
                PIC.NonVisualPictureProperties NVPP = new PIC.NonVisualPictureProperties
                    (
                        new PIC.NonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "New Bitmap Image.jpg" },
                        new PIC.NonVisualPictureDrawingProperties()
                    );
                PIC.BlipFill BF = 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())
                    );
                PIC.ShapeProperties SP = new PIC.ShapeProperties(new A.Transform2D(new A.Offset() { X = deltax * 9525, Y = deltay * 9525 }, new A.Extents() { Cx = Width * 9525, Cy = Height * 9525 }), new A.PresetGeometry(new A.AdjustValueList()) { Preset = A.ShapeTypeValues.Rectangle });
                A.GraphicData GD = new A.GraphicData(new PIC.Picture(NVPP, BF, SP)) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" };
                anchor1.Append(new A.Graphic(GD));
                #endregion
    
                Drawing drawing1 = new Drawing();
                drawing1.Append(anchor1);
                //This line adds anchor to "Run" element, after run properties
                AnchorBase.ChildElements[1].InsertAt(drawing1,1);
            }

    I will update here as soon as I find the solution and appreciate any help.

    Thanks

    Tuesday, February 6, 2018 12:02 PM
  • The image will end up inside the cell if you change

    LayoutInCell = false,

    to

    LayoutInCell =true,


    Peter Jamieson

    • Marked as answer by Alireza78 Tuesday, February 6, 2018 1:18 PM
    Tuesday, February 6, 2018 12:11 PM
  • Hello

    Layout incell must be true, and, instead of WrapSquare, I used WrapNone (MSDN ).

    Greate. It works.

    Thanks a lot

    Tuesday, February 6, 2018 1:18 PM