/// <summary> /// Add picture /// </summary> /// <param name="picture"></param> /// <returns></returns> private string AddPicture(DocumentFormat.OpenXml.Drawing.Pictures.Picture picture) { foreach (OpenXmlElement element in picture.Elements()) { if (element is DocumentFormat.OpenXml.Drawing.Pictures.BlipFill) { DocumentFormat.OpenXml.Drawing.Blip blip = ((DocumentFormat.OpenXml.Drawing.Pictures.BlipFill)element).Blip; if (blip != null) { OpenXmlPart image = document.MainDocumentPart.GetPartById(blip.Embed.Value); string fileName = Path.Combine(imageDirectory, Path.GetFileName(image.Uri.ToString())); fileName = Util.StreamToFile(image.GetStream(), fileName, FileMode.CreateNew, null); return(fileName); } } } return(""); }
/// <summary> /// The create image paragraph. /// </summary> /// <param name="relationshipId"> /// The relationship id. /// </param> /// <param name="name"> /// The name. /// </param> /// <param name="description"> /// The description. /// </param> /// <param name="width"> /// The width. /// </param> /// <param name="height"> /// The height. /// </param> /// <returns> /// </returns> private DocumentFormat.OpenXml.Wordprocessing.Paragraph CreateImageParagraph( string relationshipId, string name, string description, double width, double height) { // http://msdn.microsoft.com/en-us/library/documentformat.openxml.drawing.extents.aspx // http://polymathprogrammer.com/2009/10/22/english-metric-units-and-open-xml/ // cx (Extent Length) // Specifies the length of the extents rectangle in EMUs. This rectangle shall dictate the size of the object as displayed (the result of any scaling to the original object). // Example: Consider a DrawingML object specified as follows: // <… cx="1828800" cy="200000"/> // The cx attributes specifies that this object has a height of 1828800 EMUs (English Metric Units). end example] // The possible values for this attribute are defined by the ST_PositiveCoordinate simple type (§20.1.10.42). // cy (Extent Width) // Specifies the width of the extents rectangle in EMUs. This rectangle shall dictate the size of the object as displayed (the result of any scaling to the original object). // Example: Consider a DrawingML object specified as follows: // < … cx="1828800" cy="200000"/> // The cy attribute specifies that this object has a width of 200000 EMUs (English Metric Units). end example] // The possible values for this attribute are defined by the ST_PositiveCoordinate simple type (§20.1.10.42). var paragraph1 = new DocumentFormat.OpenXml.Wordprocessing.Paragraph { RsidParagraphAddition = "00D91137", RsidRunAdditionDefault = "00AC08EB" }; var run1 = new Run(); var runProperties1 = new RunProperties(); var noProof1 = new NoProof(); runProperties1.Append(noProof1); var drawing1 = new Drawing(); var inline1 = new Inline { DistanceFromTop = 0U, DistanceFromBottom = 0U, DistanceFromLeft = 0U, DistanceFromRight = 0U }; var extent1 = new Extent { Cx = 5753100L, Cy = 3600450L }; extent1.Cx = (long)(width * 914400); extent1.Cy = (long)(height * 914400); var effectExtent1 = new EffectExtent { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L }; var docProperties1 = new DocProperties { Id = 1U, Name = name, Description = description }; var nonVisualGraphicFrameDrawingProperties1 = new NonVisualGraphicFrameDrawingProperties(); var graphicFrameLocks1 = new GraphicFrameLocks { NoChangeAspect = true }; graphicFrameLocks1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main"); nonVisualGraphicFrameDrawingProperties1.Append(graphicFrameLocks1); var graphic1 = new Graphic(); graphic1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main"); var graphicData1 = new GraphicData { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" }; var picture1 = new Picture(); picture1.AddNamespaceDeclaration("pic", "http://schemas.openxmlformats.org/drawingml/2006/picture"); var nonVisualPictureProperties1 = new NonVisualPictureProperties(); var nonVisualDrawingProperties1 = new NonVisualDrawingProperties { Id = 0U, Name = name, Description = description }; var nonVisualPictureDrawingProperties1 = new NonVisualPictureDrawingProperties(); var pictureLocks1 = new PictureLocks { NoChangeAspect = true, NoChangeArrowheads = true }; nonVisualPictureDrawingProperties1.Append(pictureLocks1); nonVisualPictureProperties1.Append(nonVisualDrawingProperties1); nonVisualPictureProperties1.Append(nonVisualPictureDrawingProperties1); var blipFill1 = new BlipFill(); var blip1 = new Blip { Embed = relationshipId }; var blipExtensionList1 = new BlipExtensionList(); var blipExtension1 = new BlipExtension { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" }; var useLocalDpi1 = new UseLocalDpi { Val = false }; useLocalDpi1.AddNamespaceDeclaration("a14", "http://schemas.microsoft.com/office/drawing/2010/main"); blipExtension1.Append(useLocalDpi1); blipExtensionList1.Append(blipExtension1); blip1.Append(blipExtensionList1); var sourceRectangle1 = new SourceRectangle(); var stretch1 = new Stretch(); var fillRectangle1 = new FillRectangle(); stretch1.Append(fillRectangle1); blipFill1.Append(blip1); blipFill1.Append(sourceRectangle1); blipFill1.Append(stretch1); var shapeProperties1 = new ShapeProperties { BlackWhiteMode = BlackWhiteModeValues.Auto }; var transform2D1 = new Transform2D(); var offset1 = new Offset { X = 0L, Y = 0L }; var extents1 = new Extents { Cx = extent1.Cx, Cy = extent1.Cy }; transform2D1.Append(offset1); transform2D1.Append(extents1); var presetGeometry1 = new PresetGeometry { Preset = ShapeTypeValues.Rectangle }; var adjustValueList1 = new AdjustValueList(); presetGeometry1.Append(adjustValueList1); var noFill1 = new NoFill(); var outline1 = new Outline(); var noFill2 = new NoFill(); outline1.Append(noFill2); shapeProperties1.Append(transform2D1); shapeProperties1.Append(presetGeometry1); shapeProperties1.Append(noFill1); shapeProperties1.Append(outline1); picture1.Append(nonVisualPictureProperties1); picture1.Append(blipFill1); picture1.Append(shapeProperties1); graphicData1.Append(picture1); graphic1.Append(graphicData1); inline1.Append(extent1); inline1.Append(effectExtent1); inline1.Append(docProperties1); inline1.Append(nonVisualGraphicFrameDrawingProperties1); inline1.Append(graphic1); drawing1.Append(inline1); run1.Append(runProperties1); run1.Append(drawing1); paragraph1.Append(run1); return paragraph1; }
/// <summary> /// Creates an image paragraph. /// </summary> /// <param name="relationshipId">The relationship id.</param> /// <param name="name">The name.</param> /// <param name="description">The description.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <returns>The <see cref="Paragraph" /> containing the image.</returns> private DocumentFormat.OpenXml.Wordprocessing.Paragraph CreateImageParagraph( string relationshipId, string name, string description, double width, double height) { // http://msdn.microsoft.com/en-us/library/documentformat.openxml.drawing.extents.aspx // http://polymathprogrammer.com/2009/10/22/english-metric-units-and-open-xml/ // cx (Extent Length) // Specifies the length of the extents rectangle in EMUs. This rectangle shall dictate the size of the object as displayed (the result of any scaling to the original object). // Example: Consider a DrawingML object specified as follows: // <… cx="1828800" cy="200000"/> // The cx attributes specifies that this object has a height of 1828800 EMUs (English Metric Units). end example] // The possible values for this attribute are defined by the ST_PositiveCoordinate simple type (§20.1.10.42). // cy (Extent Width) // Specifies the width of the extents rectangle in EMUs. This rectangle shall dictate the size of the object as displayed (the result of any scaling to the original object). // Example: Consider a DrawingML object specified as follows: // < … cx="1828800" cy="200000"/> // The cy attribute specifies that this object has a width of 200000 EMUs (English Metric Units). end example] // The possible values for this attribute are defined by the ST_PositiveCoordinate simple type (§20.1.10.42). var paragraph1 = new DocumentFormat.OpenXml.Wordprocessing.Paragraph { RsidParagraphAddition = "00D91137", RsidRunAdditionDefault = "00AC08EB" }; var run1 = new Run(); var runProperties1 = new RunProperties(); var noProof1 = new NoProof(); runProperties1.AppendChild(noProof1); var drawing1 = new Drawing(); var inline1 = new Inline { DistanceFromTop = 0U, DistanceFromBottom = 0U, DistanceFromLeft = 0U, DistanceFromRight = 0U }; var extent1 = new Extent { Cx = 5753100L, Cy = 3600450L }; extent1.Cx = (long)(width * 914400); extent1.Cy = (long)(height * 914400); var effectExtent1 = new EffectExtent { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L }; var docProperties1 = new DocProperties { Id = 1U, Name = name, Description = description }; var nonVisualGraphicFrameDrawingProperties1 = new NonVisualGraphicFrameDrawingProperties(); var graphicFrameLocks1 = new GraphicFrameLocks { NoChangeAspect = true }; graphicFrameLocks1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main"); nonVisualGraphicFrameDrawingProperties1.AppendChild(graphicFrameLocks1); var graphic1 = new Graphic(); graphic1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main"); var graphicData1 = new GraphicData { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" }; var picture1 = new Picture(); picture1.AddNamespaceDeclaration("pic", "http://schemas.openxmlformats.org/drawingml/2006/picture"); var nonVisualPictureProperties1 = new NonVisualPictureProperties(); var nonVisualDrawingProperties1 = new NonVisualDrawingProperties { Id = 0U, Name = name, Description = description }; var nonVisualPictureDrawingProperties1 = new NonVisualPictureDrawingProperties(); var pictureLocks1 = new PictureLocks { NoChangeAspect = true, NoChangeArrowheads = true }; nonVisualPictureDrawingProperties1.AppendChild(pictureLocks1); nonVisualPictureProperties1.AppendChild(nonVisualDrawingProperties1); nonVisualPictureProperties1.AppendChild(nonVisualPictureDrawingProperties1); var blipFill1 = new BlipFill(); var blip1 = new Blip { Embed = relationshipId }; var blipExtensionList1 = new BlipExtensionList(); var blipExtension1 = new BlipExtension { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" }; var useLocalDpi1 = new UseLocalDpi { Val = false }; useLocalDpi1.AddNamespaceDeclaration("a14", "http://schemas.microsoft.com/office/drawing/2010/main"); blipExtension1.AppendChild(useLocalDpi1); blipExtensionList1.AppendChild(blipExtension1); blip1.AppendChild(blipExtensionList1); var sourceRectangle1 = new SourceRectangle(); var stretch1 = new Stretch(); var fillRectangle1 = new FillRectangle(); stretch1.AppendChild(fillRectangle1); blipFill1.AppendChild(blip1); blipFill1.AppendChild(sourceRectangle1); blipFill1.AppendChild(stretch1); var shapeProperties1 = new ShapeProperties { BlackWhiteMode = BlackWhiteModeValues.Auto }; var transform2D1 = new Transform2D(); var offset1 = new Offset { X = 0L, Y = 0L }; var extents1 = new Extents { Cx = extent1.Cx, Cy = extent1.Cy }; transform2D1.AppendChild(offset1); transform2D1.AppendChild(extents1); var presetGeometry1 = new PresetGeometry { Preset = ShapeTypeValues.Rectangle }; var adjustValueList1 = new AdjustValueList(); presetGeometry1.AppendChild(adjustValueList1); var noFill1 = new NoFill(); var outline1 = new Outline(); var noFill2 = new NoFill(); outline1.AppendChild(noFill2); shapeProperties1.AppendChild(transform2D1); shapeProperties1.AppendChild(presetGeometry1); shapeProperties1.AppendChild(noFill1); shapeProperties1.AppendChild(outline1); picture1.AppendChild(nonVisualPictureProperties1); picture1.AppendChild(blipFill1); picture1.AppendChild(shapeProperties1); graphicData1.AppendChild(picture1); graphic1.AppendChild(graphicData1); inline1.AppendChild(extent1); inline1.AppendChild(effectExtent1); inline1.AppendChild(docProperties1); inline1.AppendChild(nonVisualGraphicFrameDrawingProperties1); inline1.AppendChild(graphic1); drawing1.AppendChild(inline1); run1.AppendChild(runProperties1); run1.AppendChild(drawing1); paragraph1.AppendChild(run1); return(paragraph1); }
private static Drawing BuildImage(string imageRelationshipID, string imageName, int pixelWidth, int pixelHeight) { int emuWidth = (int)(pixelWidth * EMU_PER_PIXEL); int emuHeight = (int)(pixelHeight * EMU_PER_PIXEL); Drawing drawing = new Drawing(); d.Wordprocessing.Inline inline = new d.Wordprocessing.Inline { DistanceFromTop = 0, DistanceFromBottom = 0, DistanceFromLeft = 0, DistanceFromRight = 0 }; d.Wordprocessing.Anchor anchor = new d.Wordprocessing.Anchor(); d.Wordprocessing.SimplePosition simplePos = new d.Wordprocessing.SimplePosition { X = 0, Y = 0 }; d.Wordprocessing.Extent extent = new d.Wordprocessing.Extent { Cx = emuWidth, Cy = emuHeight }; d.Wordprocessing.DocProperties docPr = new d.Wordprocessing.DocProperties { Id = 1, Name = imageName }; d.Graphic graphic = new d.Graphic(); // We don’t have to hard code a URI anywhere else in the document but if we don’t do it here // we end up with a corrupt document. d.GraphicData graphicData = new d.GraphicData { Uri = GRAPHIC_DATA_URI }; d.Pictures.Picture pic = new d.Pictures.Picture(); d.Pictures.NonVisualPictureProperties nvPicPr = new d.Pictures.NonVisualPictureProperties(); d.Pictures.NonVisualDrawingProperties cNvPr = new d.Pictures.NonVisualDrawingProperties { Id = 2, Name = imageName }; d.Pictures.NonVisualPictureDrawingProperties cNvPicPr = new d.Pictures.NonVisualPictureDrawingProperties(); d.Pictures.BlipFill blipFill = new d.Pictures.BlipFill(); d.Blip blip = new d.Blip { Embed = imageRelationshipID }; d.Stretch stretch = new d.Stretch(); d.FillRectangle fillRect = new d.FillRectangle(); d.Pictures.ShapeProperties spPr = new d.Pictures.ShapeProperties(); d.Transform2D xfrm = new d.Transform2D(); d.Offset off = new d.Offset { X = 0, Y = 0 }; d.Extents ext = new d.Extents { Cx = emuWidth, Cy = emuHeight }; d.PresetGeometry prstGeom = new d.PresetGeometry { Preset = d.ShapeTypeValues.Rectangle }; d.AdjustValueList avLst = new d.AdjustValueList(); xfrm.Append(off); xfrm.Append(ext); prstGeom.Append(avLst); stretch.Append(fillRect); spPr.Append(xfrm); spPr.Append(prstGeom); blipFill.Append(blip); blipFill.Append(stretch); nvPicPr.Append(cNvPr); nvPicPr.Append(cNvPicPr); pic.Append(nvPicPr); pic.Append(blipFill); pic.Append(spPr); graphicData.Append(pic); graphic.Append(graphicData); inline.Append(extent); inline.Append(docPr); inline.Append(graphic); drawing.Append(inline); return drawing; }
public static Wp.Drawing GetAnchorPicture(String imagePartId, uint width = 1500, uint height = 1500, uint horizontalOffset = 0, uint verticalOffset = 0, String pictureName = "Picture") { Wp.Drawing _drawing = new Wp.Drawing(); DWp.Anchor _anchor = new DWp.Anchor() { DistanceFromTop = (OXML.UInt32Value) 0U, DistanceFromBottom = (OXML.UInt32Value) 0U, DistanceFromLeft = (OXML.UInt32Value) 0U, DistanceFromRight = (OXML.UInt32Value) 0U, SimplePos = false, RelativeHeight = (OXML.UInt32Value) 0U, BehindDoc = true, Locked = false, LayoutInCell = true, AllowOverlap = true, EditId = "44CEF5E4", AnchorId = "44803ED1" }; DWp.SimplePosition _spos = new DWp.SimplePosition() { X = 0L, Y = 0L }; DWp.HorizontalPosition _hp = new DWp.HorizontalPosition() { RelativeFrom = DWp.HorizontalRelativePositionValues.Column }; DWp.PositionOffset _hPO = new DWp.PositionOffset(); _hPO.Text = horizontalOffset.ToString(); _hp.Append(_hPO); DWp.VerticalPosition _vp = new DWp.VerticalPosition() { RelativeFrom = DWp.VerticalRelativePositionValues.Paragraph }; DWp.PositionOffset _vPO = new DWp.PositionOffset(); _vPO.Text = verticalOffset.ToString(); _vp.Append(_vPO); DWp.Extent _e = new DWp.Extent() { Cx = height, Cy = width }; DWp.EffectExtent _ee = new DWp.EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L }; DWp.WrapTight _wp = new DWp.WrapTight() { WrapText = DWp.WrapTextValues.BothSides }; DWp.WrapPolygon _wpp = new DWp.WrapPolygon() { Edited = false }; DWp.StartPoint _sp = new DWp.StartPoint() { X = 0L, Y = 0L }; DWp.LineTo _l1 = new DWp.LineTo() { X = 0L, Y = 0L }; DWp.LineTo _l2 = new DWp.LineTo() { X = 0L, Y = 0L }; DWp.LineTo _l3 = new DWp.LineTo() { X = 0L, Y = 0L }; DWp.LineTo _l4 = new DWp.LineTo() { X = 0L, Y = 0L }; _wpp.Append(_sp); _wpp.Append(_l1); _wpp.Append(_l2); _wpp.Append(_l3); _wpp.Append(_l4); _wp.Append(_wpp); DWp.DocProperties _dp = new DWp.DocProperties() { Id = 1U, Name = pictureName }; OXML.Drawing.Graphic _g = new OXML.Drawing.Graphic(); OXML.Drawing.GraphicData _gd = new OXML.Drawing.GraphicData() { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" }; OXML.Drawing.Pictures.Picture _pic = new OXML.Drawing.Pictures.Picture(); OXML.Drawing.Pictures.NonVisualPictureProperties _nvpp = new OXML.Drawing.Pictures.NonVisualPictureProperties(); OXML.Drawing.Pictures.NonVisualDrawingProperties _nvdp = new OXML.Drawing.Pictures.NonVisualDrawingProperties() { Id = 0, Name = pictureName }; OXML.Drawing.Pictures.NonVisualPictureDrawingProperties _nvpdp = new OXML.Drawing.Pictures.NonVisualPictureDrawingProperties(); _nvpp.Append(_nvdp); _nvpp.Append(_nvpdp); OXML.Drawing.Pictures.BlipFill _bf = new OXML.Drawing.Pictures.BlipFill(); OXML.Drawing.Blip _b = new OXML.Drawing.Blip() { Embed = imagePartId, CompressionState = OXML.Drawing.BlipCompressionValues.Print }; _bf.Append(_b); OXML.Drawing.Stretch _str = new OXML.Drawing.Stretch(); OXML.Drawing.FillRectangle _fr = new OXML.Drawing.FillRectangle(); _str.Append(_fr); _bf.Append(_str); OXML.Drawing.Pictures.ShapeProperties _shp = new OXML.Drawing.Pictures.ShapeProperties(); OXML.Drawing.Transform2D _t2d = new OXML.Drawing.Transform2D(); OXML.Drawing.Offset _os = new OXML.Drawing.Offset() { X = 0L, Y = 0L }; OXML.Drawing.Extents _ex = new OXML.Drawing.Extents() { Cx = 989965L, Cy = 791845L }; _t2d.Append(_os); _t2d.Append(_ex); OXML.Drawing.PresetGeometry _preGeo = new OXML.Drawing.PresetGeometry() { Preset = OXML.Drawing.ShapeTypeValues.Rectangle }; OXML.Drawing.AdjustValueList _adl = new OXML.Drawing.AdjustValueList(); _preGeo.Append(_adl); _shp.Append(_t2d); _shp.Append(_preGeo); _pic.Append(_nvpp); _pic.Append(_bf); _pic.Append(_shp); _gd.Append(_pic); _g.Append(_gd); _anchor.Append(_spos); _anchor.Append(_hp); _anchor.Append(_vp); _anchor.Append(_e); _anchor.Append(_ee); _anchor.Append(_wp); _anchor.Append(_dp); _anchor.Append(_g); _drawing.Append(_anchor); return(_drawing); }
public static void Fill(OpenXmlElement docNode, XmlElement macroListXml, WordprocessingDocument wdDoc) { /* Форматированный текст для встроенных элементов */ IEnumerable <Paragraph> paragraphs = docNode.Elements <Paragraph>(); foreach (Paragraph paragraph in paragraphs) { IEnumerable <SdtRun> sdtRuns = paragraph.Elements <SdtRun>(); foreach (SdtRun sdtRun in sdtRuns) { // Из SdtProperties взять Tag для идентификации Content Control SdtProperties sdtProperties = sdtRun.GetFirstChild <SdtProperties>(); Tag tag = sdtProperties.GetFirstChild <Tag>(); // Найти в macroListXml Node макропеременной String macroVarValue = FindMacroVar(macroListXml, tag.Val); if (macroVarValue != null) { // Сохранить старый стиль Run SdtContentRun sdtContentRun = sdtRun.GetFirstChild <SdtContentRun>(); OpenXmlElement oldRunProps = sdtContentRun.GetFirstChild <Run>().GetFirstChild <RunProperties>().CloneNode(true); // Очистить Node Content Control sdtContentRun.RemoveAllChildren(); // Создать новую Run Node Run newRun = sdtContentRun.AppendChild(new Run()); // Вернуть старый стиль newRun.AppendChild(oldRunProps); // Вставить текст (без переносов строк!!!) newRun.AppendChild(new Text(macroVarValue)); } } } /* Получить остальные Content Control */ IEnumerable <SdtBlock> sdtBlocks = docNode.Elements <SdtBlock>(); foreach (SdtBlock sdtBlock in sdtBlocks) { // Получить параметры(SdtProperties) Content Control SdtProperties sdtProperties = sdtBlock.GetFirstChild <SdtProperties>(); // Получить Tag для идентификации Content Control Tag tag = sdtProperties.GetFirstChild <Tag>(); // Получить значение макроперенной из macroListXml Console.WriteLine("Tag: " + tag.Val); String macroVarValue = FindMacroVar(macroListXml, tag.Val); // Если макропеременная есть в MacroListXml if (macroVarValue != null) { Console.WriteLine("Value: " + macroVarValue); // Получить блок содержимого Content Control SdtContentBlock sdtContentBlock = sdtBlock.GetFirstChild <SdtContentBlock>(); /* Форматированный текст для абзацев */ if (sdtProperties.GetFirstChild <SdtPlaceholder>() != null && sdtContentBlock.GetFirstChild <Paragraph>() != null) { // Сохранить старый стиль параграфа ParagraphProperties oldParagraphProperties = sdtContentBlock.GetFirstChild <Paragraph>().GetFirstChild <ParagraphProperties>().CloneNode(true) as ParagraphProperties; String oldParagraphPropertiesXml = oldParagraphProperties.InnerXml; // Очистить ноду с контентом sdtContentBlock.RemoveAllChildren(); InsertText(macroVarValue, oldParagraphPropertiesXml, sdtContentBlock); } /* Таблицы */ if (sdtProperties.GetFirstChild <SdtPlaceholder>() != null && sdtContentBlock.GetFirstChild <Table>() != null) { // Получить ноду таблицы Table table = sdtContentBlock.GetFirstChild <Table>(); // Получить все строки таблицы IEnumerable <TableRow> tableRows = table.Elements <TableRow>(); // Получить вторую строку из таблицы TableRow tableRow = tableRows.ElementAt(1) as TableRow; Type tableRowType = tableRow.GetType(); // Получить все стили столбцов List <String> paragraphCellStyles = new List <string>(); IEnumerable <OpenXmlElement> tableCells = tableRow.Elements <TableCell>(); foreach (OpenXmlElement tableCell in tableCells) { String paragraphCellStyleXml = tableCell.GetFirstChild <Paragraph>().GetFirstChild <ParagraphProperties>().InnerXml; paragraphCellStyles.Add(paragraphCellStyleXml); } // Удалить все строки, после первой while (tableRows.Count <TableRow>() > 1) { TableRow lastTableRows = tableRows.Last <TableRow>(); lastTableRows.Remove(); } // Удалить последний элемент, если это не TableRow OpenXmlElement lastNode = table.LastChild; if (lastNode.GetType() != tableRowType) { lastNode.Remove(); } string[] rowDelimiters = new string[] { "|||" }; string[] columnDelimiters = new string[] { "^^^" }; // Получить массив строк из макропеременной String[] rowsXml = macroVarValue.Split(rowDelimiters, StringSplitOptions.None); int i = 0; while (i < rowsXml.Length) { // Получить строку String rowXml = rowsXml[i]; // Добавить ноду строки таблицы TableRow newTableRow = table.AppendChild(new TableRow()); // Получить из строки массив ячеек String[] cellsXml = rowXml.Split(columnDelimiters, StringSplitOptions.None); int j = 0; while (j < cellsXml.Length) { // Получить ячейку String cellXml = cellsXml[j]; // Убрать символ CRLF в конце строки cellXml = cellXml.TrimEnd(new char[] { '\n', '\r' }); // Добавить ноду ячейку в строку таблицы TableCell newTableCell = newTableRow.AppendChild(new TableCell()); // Вставить текст InsertText(cellXml, paragraphCellStyles[j], newTableCell); j++; } i++; } } /* Картинки */ if (sdtProperties.GetFirstChild <SdtContentPicture>() != null) { // Получить путь к файлу String imageFilePath = macroVarValue; // Получить расширение файла String extension = System.IO.Path.GetExtension(imageFilePath).ToLower(); ImagePartType imagePartType; switch (extension) { case "jpeg": imagePartType = ImagePartType.Jpeg; break; case "jpg": imagePartType = ImagePartType.Jpeg; break; case "png": imagePartType = ImagePartType.Png; break; case "bmp": imagePartType = ImagePartType.Bmp; break; case "gif": imagePartType = ImagePartType.Gif; break; default: imagePartType = ImagePartType.Jpeg; break; } ; // Добавить ImagePart в документ ImagePart imagePart = wdDoc.MainDocumentPart.AddImagePart(imagePartType); // Получить картинку using (FileStream stream = new FileStream(imageFilePath, FileMode.Open)) { imagePart.FeedData(stream); } // Вычислить width и height Bitmap img = new Bitmap(imageFilePath); var widthPx = img.Width; var heightPx = img.Height; var horzRezDpi = img.HorizontalResolution; var vertRezDpi = img.VerticalResolution; const int emusPerInch = 914400; const int emusPerCm = 360000; var widthEmus = (long)(widthPx / horzRezDpi * emusPerInch); var heightEmus = (long)(heightPx / vertRezDpi * emusPerInch); // Получить ID ImagePart string relationShipId = wdDoc.MainDocumentPart.GetIdOfPart(imagePart); Paragraph paragraph = sdtContentBlock.GetFirstChild <Paragraph>(); Run run = paragraph.GetFirstChild <Run>(); Drawing drawing = run.GetFirstChild <Drawing>(); Inline inline = drawing.GetFirstChild <Inline>(); Graphic graphic = inline.GetFirstChild <Graphic>(); GraphicData graphicData = graphic.GetFirstChild <GraphicData>(); Picture pic = graphicData.GetFirstChild <Picture>(); BlipFill blipFill = pic.GetFirstChild <BlipFill>(); Blip blip = blipFill.GetFirstChild <Blip>(); string prefix = "r"; string localName = "embed"; string namespaceUri = @"http://schemas.openxmlformats.org/officeDocument/2006/relationships"; OpenXmlAttribute oldEmbedAttribute = blip.GetAttribute("embed", namespaceUri); IList <OpenXmlAttribute> attributes = blip.GetAttributes(); if (oldEmbedAttribute != null) { attributes.Remove(oldEmbedAttribute); } // Удалить хз что, выявлено практическим путем blipFill.RemoveAllChildren <SourceRectangle>(); // Установить новую картинку blip.SetAttribute(new OpenXmlAttribute(prefix, localName, namespaceUri, relationShipId)); blip.SetAttribute(new OpenXmlAttribute("cstate", "", "print")); // Подогнать размеры Extent extent = inline.GetFirstChild <Extent>(); OpenXmlAttribute oldCxExtent = extent.GetAttribute("cx", ""); if (oldCxExtent != null) { var maxWidthEmus = long.Parse(oldCxExtent.Value); if (widthEmus > maxWidthEmus) { var ratio = (heightEmus * 1.0m) / widthEmus; widthEmus = maxWidthEmus; heightEmus = (long)(widthEmus * ratio); } extent.GetAttributes().Remove(oldCxExtent); } OpenXmlAttribute oldCyExtent = extent.GetAttribute("cy", ""); if (oldCyExtent != null) { extent.GetAttributes().Remove(oldCyExtent); } extent.SetAttribute(new OpenXmlAttribute("cx", "", widthEmus.ToString())); extent.SetAttribute(new OpenXmlAttribute("cy", "", heightEmus.ToString())); ShapeProperties shapeProperties = pic.GetFirstChild <ShapeProperties>(); Transform2D transform2D = shapeProperties.GetFirstChild <Transform2D>(); Extents extents = transform2D.GetFirstChild <Extents>(); OpenXmlAttribute oldCxExtents = extents.GetAttribute("cx", ""); if (oldCxExtents != null) { extents.GetAttributes().Remove(oldCxExtents); } OpenXmlAttribute oldCyExtents = extents.GetAttribute("cy", ""); if (oldCyExtents != null) { extents.GetAttributes().Remove(oldCyExtents); } extents.SetAttribute(new OpenXmlAttribute("cx", "", widthEmus.ToString())); extents.SetAttribute(new OpenXmlAttribute("cy", "", heightEmus.ToString())); // Удалить placeholder ShowingPlaceholder showingPlaceholder = sdtProperties.GetFirstChild <ShowingPlaceholder>(); if (showingPlaceholder != null) { sdtProperties.RemoveChild <ShowingPlaceholder>(showingPlaceholder); } } /* Повторяющийся раздел */ if (sdtProperties.GetFirstChild <SdtRepeatedSection>() != null) { // Представить repeatedSection как новый xml документ (сделать корнем) XmlDocument repeatedSectionXml = new XmlDocument(); repeatedSectionXml.LoadXml(macroVarValue); // Получить корневой элемент repeatedSection XmlElement rootRepeatedSectionXml = repeatedSectionXml.DocumentElement; // Получить количество repeatedSectionItem XmlNodeList repeatedSectionItems = rootRepeatedSectionXml.SelectNodes("repeatedSectionItem"); int repeatedItemCount = repeatedSectionItems.Count; Console.WriteLine("Количество repeatedSectionItem: " + repeatedItemCount); /* Блок клонирования ноды повтор. раздела до нужного количества */ for (int i = 0; i < repeatedItemCount; i++) { XmlElement macroListRepeatedSectionItem = rootRepeatedSectionXml.SelectSingleNode(String.Format(@"repeatedSectionItem[@id=""{0}""]", i)) as XmlElement; Console.WriteLine("Item " + i + ": " + macroListRepeatedSectionItem.OuterXml); SdtContentBlock sdtContentBlockRepeatedSectionItem = sdtContentBlock.Elements <SdtBlock>().Last <SdtBlock>().GetFirstChild <SdtContentBlock>(); Fill(sdtContentBlockRepeatedSectionItem, macroListRepeatedSectionItem, wdDoc); if (i + 1 < repeatedItemCount) { SdtBlock clonedRepeatedSectionItem = sdtContentBlock.GetFirstChild <SdtBlock>().Clone() as SdtBlock; sdtContentBlock.AppendChild <SdtBlock>(clonedRepeatedSectionItem); } } /**/ //Fill(sdtContentBlock, macroListRepeatedSection, wdDoc); } } Console.WriteLine(); } }