I am trying top create a word file with the header and footer and footer must have a Image can any one help me to do that.
I am using Open XML to create word file .
You can try this. You need to create a DocumentResource (Item->Add new) and associate an image.
private static Footer BuildFooter(FooterPart hp, string title)
{
ImagePart ip = hp.AddImagePart(ImagePartType.Jpeg);
string imageRelationshipID = hp.GetIdOfPart(ip);
using (Stream imgStream = ip.GetStream())
{
System.Drawing.Bitmap logo = DocumentResources._default;
logo.Save(imgStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
Footer h = new Footer();
DocumentFormat.OpenXml.Wordprocessing.Paragraph p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
Run r = new Run();
Drawing drawing = BuildImage(imageRelationshipID, "_default.jpg", 200, 30);
r.Append(drawing);
p.Append(r);
r = new Run();
RunProperties rPr = new RunProperties();
TabChar tab = new TabChar();
Bold b = new Bold();
Color color = new Color { Val = "000000" };
DocumentFormat.OpenXml.Wordprocessing.FontSize sz = new DocumentFormat.OpenXml.Wordprocessing.FontSize {Val = Convert.ToString("40")};
Text t = new Text { Text = title };
rPr.Append(b);
rPr.Append(color);
rPr.Append(sz);
r.Append(rPr);
r.Append(tab);
r.Append(t);
p.Append(r);
h.Append(p);
return h;
}
and to build image
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();
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;
}
To call those functions, in your function that build the document
FooterPart hp = mp.AddNewPart<FooterPart>();
string headerRelationshipID = mp.GetIdOfPart(hp);
SectionProperties sectPr = new SectionProperties();
FooterReference footerReference = new FooterReference();
FooterReference.Id = footerRelationshipID;
FooterReference.Type = HeaderFooterValues.Default;
sectPr.Append(footerReference);
b.Append(sectPr);
d.Append(b);
hp.Footer = BuildFooter(hp, "My Test");
Related
I want to create pie chart on Excel using OpenXml. Is there any source from where i can get help?.
I have already developed the Bar Chart.
Here's my reference:
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using C = DocumentFormat.OpenXml.Drawing.Charts;
using DocumentFormat.OpenXml.Drawing.Charts;
using DocumentFormat.OpenXml.Drawing.Spreadsheet;
using DocumentFormat.OpenXml.Drawing;
I'm using here MemoryStream to create excel file:
WorkbookPart workbookPart = null;
using (var memoryStream = new MemoryStream())
{
using (var excel = SpreadsheetDocument.Create(memoryStream, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook, true))
{
workbookPart = excel.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>("rId1");
Worksheet worksheet = new Worksheet();
SheetData sheetData = new SheetData();
worksheet.Append(sheetData);
worksheetPart.Worksheet = worksheet;
string relationshipId = "rId1";// workbookPart.GetIdOfPart(worksheetPart);
Sheets sheets = new Sheets();
uint sheetId = 1;
string sheetName = "Sheet" + sheetId;
Sheet sheet1 = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
sheets.Append(sheet1);
workbookPart.Workbook.Append(sheets);
//// Add a new drawing to the worksheet.
DrawingsPart drawingsPart = worksheetPart.AddNewPart<DrawingsPart>();
worksheetPart.Worksheet.Append(new DocumentFormat.OpenXml.Spreadsheet.Drawing()
{
Id = worksheetPart.GetIdOfPart(drawingsPart)
});
worksheetPart.Worksheet.Save();
string chartTitle = "Generator Utilisation";
Dictionary<string, int> data = new Dictionary<string, int>();
data.Add("Running", 92);
data.Add("Stopped", 8);
InsertPieChartInSpreadSheet(drawingsPart, chartTitle, data, 1, 1, 17, 8);
excel.Close();
}
FileStream fileStream = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "Plant Summary Report.xlsx", FileMode.Create, FileAccess.Write);
memoryStream.WriteTo(fileStream);
fileStream.Close();
memoryStream.Close();
}
Here is InsertPieChartInSpreadSheet method:
private static void InsertPieChartInSpreadSheet(DrawingsPart drawingsPart,string chartTitle, Dictionary<string, int> data, int startRowIndex, int startColumnIndex, int endRowIndex, int endColumnIndex)
{
ChartPart chartPart = drawingsPart.AddNewPart<ChartPart>();
ChartSpace chartSpace = new ChartSpace();
chartSpace.Append(new EditingLanguage() { Val = new StringValue("en-US") });
DocumentFormat.OpenXml.Drawing.Charts.Chart chart = chartSpace.AppendChild<DocumentFormat.OpenXml.Drawing.Charts.Chart>(
new DocumentFormat.OpenXml.Drawing.Charts.Chart());
PlotArea plotArea = chart.AppendChild<PlotArea>(new PlotArea());
Layout layout = plotArea.AppendChild<Layout>(new Layout());
ManualLayout manualLayout1 = new ManualLayout();
LayoutTarget layoutTarget1 = new LayoutTarget() { Val = LayoutTargetValues.Inner };
LeftMode leftMode1 = new LeftMode() { Val = LayoutModeValues.Edge };
TopMode topMode1 = new TopMode() { Val = LayoutModeValues.Edge };
Left left1 = new Left() { Val = 0.5D };
Top top1 = new Top() { Val = 0.2D };
Width width1 = new Width() { Val = 0.95622038461448768D };
Height height1 = new Height() { Val = 0.54928769841269842D };
manualLayout1.Append(layoutTarget1);
manualLayout1.Append(leftMode1);
manualLayout1.Append(topMode1);
manualLayout1.Append(left1);
manualLayout1.Append(top1);
manualLayout1.Append(width1);
manualLayout1.Append(height1);
layout.Append(manualLayout1);
NoFill noFill = new NoFill();
C.ShapeProperties shapeProperties = new C.ShapeProperties();
DocumentFormat.OpenXml.Drawing.Outline outline15 = new DocumentFormat.OpenXml.Drawing.Outline();
DocumentFormat.OpenXml.Drawing.SolidFill noFill17 = new DocumentFormat.OpenXml.Drawing.SolidFill();
RgbColorModelHex schemeColor29 = new RgbColorModelHex() { Val = "FFFFFF" };
noFill17.Append(schemeColor29);
outline15.Append(noFill17);
shapeProperties.Append(noFill);
shapeProperties.Append(outline15);
plotArea.Append(shapeProperties);
PieChart pieChart = plotArea.AppendChild<PieChart>(new PieChart());
PieChartSeries pieChartSeries = pieChart.AppendChild<PieChartSeries>(new PieChartSeries(
new Index() { Val = (UInt32Value)0U },
new Order() { Val = (UInt32Value)0U },
new SeriesText(new NumericValue() { Text = "PieChartSeries" })));
CategoryAxisData catAx = new CategoryAxisData();
StringReference stringReference = new StringReference();
StringCache stringCache = new StringCache();
PointCount pointCount = new PointCount() { Val = (uint)data.Count };
stringCache.Append(pointCount);
uint i = 0;
foreach (var key in data.Keys)
{
stringCache.AppendChild<StringPoint>(new StringPoint() { Index = new UInt32Value(i) }).Append(new NumericValue(key));
i++;
}
stringReference.Append(stringCache);
catAx.Append(stringReference);
pieChartSeries.Append(catAx);
C.Values values = new C.Values();
NumberReference numberReference = new NumberReference();
NumberingCache numberingCache = new NumberingCache();
i = 0;
foreach (var key in data.Keys)
{
numberingCache.AppendChild<NumericPoint>(new NumericPoint() { Index = new UInt32Value(i) }).Append(new NumericValue(data[key].ToString()));
i++;
}
numberReference.Append(numberingCache);
values.Append(numberReference);
pieChartSeries.Append(values);
AddChartTitle(chart, chartTitle);
pieChart.Append(new AxisId() { Val = new UInt32Value(48650112u) });
pieChart.Append(new AxisId() { Val = new UInt32Value(48672768u) });
CategoryAxis catAx1 = plotArea.AppendChild<CategoryAxis>(new CategoryAxis(new AxisId()
{ Val = new UInt32Value(48650112u) }, new Scaling(new Orientation()
{
Val = new EnumValue<DocumentFormat.OpenXml.Drawing.Charts.OrientationValues>(DocumentFormat.OpenXml.Drawing.Charts.OrientationValues.MinMax)
}),
new AxisPosition() { Val = new EnumValue<AxisPositionValues>(AxisPositionValues.Bottom) },
new TickLabelPosition() { Val = new EnumValue<TickLabelPositionValues>(TickLabelPositionValues.NextTo) },
new CrossingAxis() { Val = new UInt32Value(48672768U) },
new Crosses() { Val = new EnumValue<CrossesValues>(CrossesValues.AutoZero) },
new AutoLabeled() { Val = new BooleanValue(true) },
new LabelAlignment() { Val = new EnumValue<LabelAlignmentValues>(LabelAlignmentValues.Center) },
new LabelOffset() { Val = new UInt16Value((ushort)100) }));
// Add the Value Axis.
ValueAxis valAx = plotArea.AppendChild<ValueAxis>(new ValueAxis(new AxisId() { Val = new UInt32Value(48672768u) },
new Scaling(new Orientation()
{
Val = new EnumValue<DocumentFormat.OpenXml.Drawing.Charts.OrientationValues>(
DocumentFormat.OpenXml.Drawing.Charts.OrientationValues.MinMax)
}),
new AxisPosition() { Val = new EnumValue<AxisPositionValues>(AxisPositionValues.Left) },
new MajorGridlines(),
new DocumentFormat.OpenXml.Drawing.Charts.NumberingFormat()
{
FormatCode = new StringValue("General"),
SourceLinked = new BooleanValue(true)
}, new TickLabelPosition()
{
Val = new EnumValue<TickLabelPositionValues>
(TickLabelPositionValues.NextTo)
}, new CrossingAxis() { Val = new UInt32Value(48650112U) },
new Crosses() { Val = new EnumValue<CrossesValues>(CrossesValues.AutoZero) },
new CrossBetween() { Val = new EnumValue<CrossBetweenValues>(CrossBetweenValues.Between) }));
// Add the chart Legend.
Legend legend = chart.AppendChild<Legend>(new Legend(new LegendPosition() { Val = new EnumValue<LegendPositionValues>(LegendPositionValues.Bottom) },
new Layout()));
chart.Append(new PlotVisibleOnly() { Val = new BooleanValue(true) });
chartPart.ChartSpace = chartSpace;
PositionChart(chartPart, drawingsPart, startRowIndex, startColumnIndex, endRowIndex, endColumnIndex);
}
Here's an additional method which will set chart position:
private static void PositionChart(ChartPart chartPart, DrawingsPart drawingsPart, int startRowIndex, int startColumnIndex, int endRowIndex, int endColumnIndex)
{
// Position the chart on the worksheet using a TwoCellAnchor object.
drawingsPart.WorksheetDrawing = new WorksheetDrawing();
TwoCellAnchor twoCellAnchor = drawingsPart.WorksheetDrawing.AppendChild<TwoCellAnchor>(new TwoCellAnchor());
twoCellAnchor.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.FromMarker(new ColumnId(startColumnIndex.ToString()),
new ColumnOffset("581025"),
new RowId(startRowIndex.ToString()),
new RowOffset("114300")));
twoCellAnchor.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.ToMarker(new ColumnId(endColumnIndex.ToString()),
new ColumnOffset("276225"),
new RowId(endRowIndex.ToString()),
new RowOffset("0")));
// Append a GraphicFrame to the TwoCellAnchor object.
DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame graphicFrame =
twoCellAnchor.AppendChild<DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame>(new DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame());
graphicFrame.Macro = "";
graphicFrame.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualGraphicFrameProperties(
new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualDrawingProperties() { Id = new UInt32Value(2u), Name = "Chart 1" },
new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualGraphicFrameDrawingProperties()));
graphicFrame.Append(new Transform(new Offset() { X = 0L, Y = 0L },
new Extents() { Cx = 0L, Cy = 0L }));
graphicFrame.Append(new Graphic(new GraphicData(new ChartReference() { Id = drawingsPart.GetIdOfPart(chartPart) })
{ Uri = "http://schemas.openxmlformats.org/drawingml/2006/chart" }));
twoCellAnchor.Append(new ClientData());
}
This method will add chart title:
private static void AddChartTitle(DocumentFormat.OpenXml.Drawing.Charts.Chart chart, string title)
{
var ctitle = chart.AppendChild(new Title());
var chartText = ctitle.AppendChild(new ChartText());
var richText = chartText.AppendChild(new RichText());
var bodyPr = richText.AppendChild(new BodyProperties());
var lstStyle = richText.AppendChild(new ListStyle());
var paragraph = richText.AppendChild(new Paragraph());
var apPr = paragraph.AppendChild(new ParagraphProperties());
apPr.AppendChild(new DefaultRunProperties());
var run = paragraph.AppendChild(new DocumentFormat.OpenXml.Drawing.Run());
run.AppendChild(new DocumentFormat.OpenXml.Drawing.RunProperties() { Language = "en-CA" });
run.AppendChild(new DocumentFormat.OpenXml.Drawing.Text() { Text = title });
//ctitle.AppendChild(new Overlay() { Val = new BooleanValue(false) });
}
I need to create a Word Document using Open XML SDK. I have the document text and the Footnotes . I am using the below Snippets to Create the Word Document.
I am able to create the document with the text ,But I am not able to add Footnotes to it.
Can you please let us know how to add FootNotes programmatically using Open Xml
public void CreateWordDocument()
{
using (MemoryStream DocxMemory = new MemoryStream())
{
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(DocxMemory, WordprocessingDocumentType.Document, true))
{
// Add a main document part.
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
// Create the document structure and add some text.
this.AddSettingsToMainDocumentPart(mainPart);
StyleDefinitionsPart part = mainPart.StyleDefinitionsPart;
// If the Styles part does not exist, add it.
if (part == null)
{
this.AddStylesPartToPackage(mainPart);
}
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
Paragraph Para = body.AppendChild(new Paragraph());
Run run = Para.AppendChild(new Run());
run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text("This is main text of the document"));
var footnotesPart = mainPart.AddNewPart<FootnotesPart>("rId1");
this.GenerateFooterPartContent(mainPart.FootnotesPart);
mainPart.Document.Save();
wordDocument.Close();
MemoryStream Result = new MemoryStream();
DocxMemory.Seek(0, SeekOrigin.Begin);
DocxMemory.CopyTo(Result);
Result.Position = 0;
////Citation processing
byte[] BufferFileData = new byte[Result.Length];
Result.Read(BufferFileData, 0, (int)Result.Length);
File.WriteAllBytes("Output1.docx", BufferFileData);
}
}
}
private void AddSettingsToMainDocumentPart(MainDocumentPart part)
{
DocumentSettingsPart settingsPart = part.DocumentSettingsPart;
if (settingsPart == null)
settingsPart = part.AddNewPart<DocumentSettingsPart>();
settingsPart.Settings = new Settings(
new Compatibility(
new CompatibilitySetting()
{
Name = new EnumValue<CompatSettingNameValues>
(CompatSettingNameValues.CompatibilityMode),
Val = new StringValue("14"),
Uri = new StringValue
("http://schemas.microsoft.com/office/word")
}
)
);
settingsPart.Settings.Save();
}
private StyleDefinitionsPart AddStylesPartToPackage(MainDocumentPart mainPart)
{
StyleDefinitionsPart part;
part = mainPart.AddNewPart<StyleDefinitionsPart>();
Styles root = new Styles();
root.Save(part);
return part;
}
// Generates content of part.
private void GenerateFooterPartContent(FootnotesPart part)
{
Footnotes footnotes1 = new Footnotes() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "w14 wp14" } };
footnotes1.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
footnotes1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
footnotes1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
footnotes1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
footnotes1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
footnotes1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
footnotes1.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
footnotes1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
footnotes1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
footnotes1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
footnotes1.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
footnotes1.AddNamespaceDeclaration("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
footnotes1.AddNamespaceDeclaration("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
footnotes1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
footnotes1.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");
Footnote footnote1 = new Footnote() { Type = FootnoteEndnoteValues.Separator, Id = -1 };
Paragraph paragraph1 = new Paragraph() { RsidParagraphAddition = "003F1A60", RsidParagraphProperties = "00626544", RsidRunAdditionDefault = "003F1A60" };
Run run1 = new Run();
SeparatorMark separatorMark1 = new SeparatorMark();
run1.Append(separatorMark1);
paragraph1.Append(run1);
footnote1.Append(paragraph1);
Footnote footnote2 = new Footnote() { Type = FootnoteEndnoteValues.ContinuationSeparator, Id = 0 };
Paragraph paragraph2 = new Paragraph() { RsidParagraphAddition = "003F1A60", RsidParagraphProperties = "00626544", RsidRunAdditionDefault = "003F1A60" };
Run run2 = new Run();
ContinuationSeparatorMark continuationSeparatorMark1 = new ContinuationSeparatorMark();
run2.Append(continuationSeparatorMark1);
paragraph2.Append(run2);
footnote2.Append(paragraph2);
Footnote footnote3 = new Footnote() { Id = 1 };
Paragraph paragraph3 = new Paragraph() { RsidParagraphMarkRevision = "009774CC", RsidParagraphAddition = "00626544", RsidParagraphProperties = "00626544", RsidRunAdditionDefault = "00626544" };
ParagraphProperties paragraphProperties1 = new ParagraphProperties();
ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties();
RunFonts runFonts1 = new RunFonts() { AsciiTheme = ThemeFontValues.MinorHighAnsi, HighAnsiTheme = ThemeFontValues.MinorHighAnsi, ComplexScriptTheme = ThemeFontValues.MinorHighAnsi };
FontSize fontSize1 = new FontSize() { Val = "24" };
FontSizeComplexScript fontSizeComplexScript1 = new FontSizeComplexScript() { Val = "24" };
paragraphMarkRunProperties1.Append(runFonts1);
paragraphMarkRunProperties1.Append(fontSize1);
paragraphMarkRunProperties1.Append(fontSizeComplexScript1);
paragraphProperties1.Append(paragraphMarkRunProperties1);
Run run3 = new Run() { RsidRunProperties = "009774CC" };
RunProperties runProperties1 = new RunProperties();
RunFonts runFonts2 = new RunFonts() { AsciiTheme = ThemeFontValues.MinorHighAnsi, HighAnsiTheme = ThemeFontValues.MinorHighAnsi, ComplexScriptTheme = ThemeFontValues.MinorHighAnsi };
FontSize fontSize2 = new FontSize() { Val = "24" };
FontSizeComplexScript fontSizeComplexScript2 = new FontSizeComplexScript() { Val = "24" };
VerticalTextAlignment verticalTextAlignment1 = new VerticalTextAlignment() { Val = VerticalPositionValues.Superscript };
runProperties1.Append(runFonts2);
runProperties1.Append(fontSize2);
runProperties1.Append(fontSizeComplexScript2);
runProperties1.Append(verticalTextAlignment1);
Text text1 = new Text();
text1.Text = "1";
run3.Append(runProperties1);
run3.Append(text1);
Run run4 = new Run() { RsidRunProperties = "009774CC" };
RunProperties runProperties2 = new RunProperties();
RunFonts runFonts3 = new RunFonts() { AsciiTheme = ThemeFontValues.MinorHighAnsi, HighAnsiTheme = ThemeFontValues.MinorHighAnsi, ComplexScriptTheme = ThemeFontValues.MinorHighAnsi };
runProperties2.Append(runFonts3);
Text text2 = new Text() { Space = SpaceProcessingModeValues.Preserve };
text2.Text = " ";
run4.Append(runProperties2);
run4.Append(text2);
Run run5 = new Run() { RsidRunProperties = "009774CC", RsidRunAddition = "009774CC" };
RunProperties runProperties3 = new RunProperties();
RunFonts runFonts4 = new RunFonts() { AsciiTheme = ThemeFontValues.MinorHighAnsi, HighAnsiTheme = ThemeFontValues.MinorHighAnsi, ComplexScriptTheme = ThemeFontValues.MinorHighAnsi };
FontSize fontSize3 = new FontSize() { Val = "21" };
FontSizeComplexScript fontSizeComplexScript3 = new FontSizeComplexScript() { Val = "21" };
runProperties3.Append(runFonts4);
runProperties3.Append(fontSize3);
runProperties3.Append(fontSizeComplexScript3);
Text text3 = new Text();
text3.Text = "This is the foot note text";
run5.Append(runProperties3);
run5.Append(text3);
paragraph3.Append(paragraphProperties1);
paragraph3.Append(run3);
paragraph3.Append(run4);
paragraph3.Append(run5);
footnote3.Append(paragraph3);
footnotes1.Append(footnote1);
footnotes1.Append(footnote2);
footnotes1.Append(footnote3);
part.Footnotes = footnotes1;
}
I managed to add footnotes using the following code.
I hope this helps.
var ms = new MemoryStream();
using (WordprocessingDocument myDoc = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document))
{
MainDocumentPart mainPart = myDoc.AddMainDocumentPart();
var footPart = mainPart.AddNewPart<FootnotesPart>();
footPart.Footnotes = new Footnotes();
mainPart.Document = new Document();
Body body = new Body();
var p = new Paragraph();
var r = new Run();
var t = new Text("123");
r.Append(t);
p.Append(r);
// ADD THE FOOTNOTE
var footnote = new Footnote();
footnote.Id = 1;
var p2 = new Paragraph();
var r2 = new Run();
var t2 = new Text();
t2.Text = "My FootNote Content";
r2.Append(t2);
p2.Append(r2);
footnote.Append(p2);
footPart.Footnotes.Append(footnote);
// ADD THE FOOTNOTE REFERENCE
var fref = new FootnoteReference();
fref.Id = 1;
var r3 = new Run();
r3.RunProperties = new RunProperties();
var s3 = new VerticalTextAlignment();
s3.Val = VerticalPositionValues.Superscript;
r3.RunProperties.Append(s3);
r3.Append(fref);
p.Append(r3);
body.Append(p);
mainPart.Document.Append(body);
mainPart.Document.Save();
ms.Flush();
}
return ms.ToArray();
I'm not an expert on OpenXML but I think you're missing adding an actual reference to the footnote in the body text, I tweaked your code like this and I now get the footnote in the document. Hope it helps or at least gets you started.
Run run = Para.AppendChild(new Run());
run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text("This is main text of the document"));
var footnoteref = new FootnoteReference() { Id = 1 };
run.Append(footnoteref);
I have a task that I have to take go through each slide and input it to a docx file and my condition is that I will not use interop or I can use openXML.
currently i am trying to take image of each slide and insert those images to a document. I got sampleCode from here (with help of spire dll) which produce images of each slide.but the problem is that while creating images the DLL put a watermark at the top of the image (Water Mark Text : Evaluation warning : the docume......) is there any other option to take image of a slide or directly input a slide to a doc file.
and one more thing I can't purchase other license
First: Just pay for the license. The watermark is there for a reason.
To answer your question, an Open XML document is in fact a ZIP file, so it would be quite easy to extract embedded files from there, and even edit them. You just have to extract the file as a ZIP, do your task on them, and zip it again.
You don't need additional libraries to do this, but some may make the zip processing a little easier. If you don't want to use external libraries, you need to use the classes provided under System.IO.Compression.
You can use OpenXML to add image in document, first you need to convert slide to an individual images and then put them one by one
after searching I got following code snippet to insert image in word document
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
using Wp = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using A = DocumentFormat.OpenXml.Drawing;
using Pic = DocumentFormat.OpenXml.Drawing.Pictures;
namespace GeneratedCode
{
public class GeneratedClass
{
// Creates an Body instance and adds its children.
public Body GenerateBody()
{
Body body1 = new Body();
Paragraph paragraph1 = new Paragraph(){ RsidParagraphAddition = "00970886", RsidRunAdditionDefault = "00164292" };
Run run1 = new Run();
RunProperties runProperties1 = new RunProperties();
NoProof noProof1 = new NoProof();
runProperties1.Append(noProof1);
Drawing drawing1 = new Drawing();
Wp.Inline inline1 = new Wp.Inline(){ DistanceFromTop = (UInt32Value)0U, DistanceFromBottom = (UInt32Value)0U, DistanceFromLeft = (UInt32Value)0U, DistanceFromRight = (UInt32Value)0U };
Wp.Extent extent1 = new Wp.Extent(){ Cx = 2009775L, Cy = 2276475L };
Wp.EffectExtent effectExtent1 = new Wp.EffectExtent(){ LeftEdge = 19050L, TopEdge = 0L, RightEdge = 9525L, BottomEdge = 0L };
Wp.DocProperties docProperties1 = new Wp.DocProperties(){ Id = (UInt32Value)1U, Name = "Picture 0", Description = "Authentication.jpg" };
Wp.NonVisualGraphicFrameDrawingProperties nonVisualGraphicFrameDrawingProperties1 = new Wp.NonVisualGraphicFrameDrawingProperties();
A.GraphicFrameLocks graphicFrameLocks1 = new A.GraphicFrameLocks(){ NoChangeAspect = true };
graphicFrameLocks1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main");
nonVisualGraphicFrameDrawingProperties1.Append(graphicFrameLocks1);
A.Graphic graphic1 = new A.Graphic();
graphic1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main");
A.GraphicData graphicData1 = new A.GraphicData(){ Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" };
Pic.Picture picture1 = new Pic.Picture();
picture1.AddNamespaceDeclaration("pic", "http://schemas.openxmlformats.org/drawingml/2006/picture");
Pic.NonVisualPictureProperties nonVisualPictureProperties1 = new Pic.NonVisualPictureProperties();
Pic.NonVisualDrawingProperties nonVisualDrawingProperties1 = new Pic.NonVisualDrawingProperties(){ Id = (UInt32Value)0U, Name = "Authentication.jpg" };
Pic.NonVisualPictureDrawingProperties nonVisualPictureDrawingProperties1 = new Pic.NonVisualPictureDrawingProperties();
nonVisualPictureProperties1.Append(nonVisualDrawingProperties1);
nonVisualPictureProperties1.Append(nonVisualPictureDrawingProperties1);
Pic.BlipFill blipFill1 = new Pic.BlipFill();
A.Blip blip1 = new A.Blip(){ Embed = "rId6" };
A.Stretch stretch1 = new A.Stretch();
A.FillRectangle fillRectangle1 = new A.FillRectangle();
stretch1.Append(fillRectangle1);
blipFill1.Append(blip1);
blipFill1.Append(stretch1);
Pic.ShapeProperties shapeProperties1 = new Pic.ShapeProperties();
A.Transform2D transform2D1 = new A.Transform2D();
A.Offset offset1 = new A.Offset(){ X = 0L, Y = 0L };
A.Extents extents1 = new A.Extents(){ Cx = 2009775L, Cy = 2276475L };
transform2D1.Append(offset1);
transform2D1.Append(extents1);
A.PresetGeometry presetGeometry1 = new A.PresetGeometry(){ Preset = A.ShapeTypeValues.Rectangle };
A.AdjustValueList adjustValueList1 = new A.AdjustValueList();
presetGeometry1.Append(adjustValueList1);
shapeProperties1.Append(transform2D1);
shapeProperties1.Append(presetGeometry1);
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);
SectionProperties sectionProperties1 = new SectionProperties(){ RsidR = "00970886" };
HeaderReference headerReference1 = new HeaderReference(){ Type = HeaderFooterValues.Even, Id = "rId7" };
HeaderReference headerReference2 = new HeaderReference(){ Type = HeaderFooterValues.Default, Id = "rId8" };
FooterReference footerReference1 = new FooterReference(){ Type = HeaderFooterValues.Even, Id = "rId9" };
FooterReference footerReference2 = new FooterReference(){ Type = HeaderFooterValues.Default, Id = "rId10" };
HeaderReference headerReference3 = new HeaderReference(){ Type = HeaderFooterValues.First, Id = "rId11" };
FooterReference footerReference3 = new FooterReference(){ Type = HeaderFooterValues.First, Id = "rId12" };
PageSize pageSize1 = new PageSize(){ Width = (UInt32Value)12240U, Height = (UInt32Value)15840U };
PageMargin pageMargin1 = new PageMargin(){ Top = 1440, Right = (UInt32Value)1440U, Bottom = 1440, Left = (UInt32Value)1440U, Header = (UInt32Value)720U, Footer = (UInt32Value)720U, Gutter = (UInt32Value)0U };
Columns columns1 = new Columns(){ Space = "720" };
DocGrid docGrid1 = new DocGrid(){ LinePitch = 360 };
sectionProperties1.Append(headerReference1);
sectionProperties1.Append(headerReference2);
sectionProperties1.Append(footerReference1);
sectionProperties1.Append(footerReference2);
sectionProperties1.Append(headerReference3);
sectionProperties1.Append(footerReference3);
sectionProperties1.Append(pageSize1);
sectionProperties1.Append(pageMargin1);
sectionProperties1.Append(columns1);
sectionProperties1.Append(docGrid1);
body1.Append(paragraph1);
body1.Append(sectionProperties1);
return body1;
}
}
}
My requirement is : Exporting a dynamic DataTable to Word document with Page Numbers
We need to use Open XML to achieve this.
I have code to export Datatable to Word. And also to insert page numbers.
I got Below code code to export datatable
public void CreateWordtable(string filename,DataTable data)
{
WordprocessingDocument doc = WordprocessingDocument.Create(filename, WordprocessingDocumentType.Document);
MainDocumentPart mainDocPart = doc.AddMainDocumentPart();
mainDocPart.Document = new Document();
Body body = new Body();
mainDocPart.Document.Append(body);
//rinks#::creating new table
DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table();
for (int i = 0; i < data.Rows.Count; ++i)
{
TableRow row = new TableRow();
for (int j = 0; j < data.Columns.Count; j++)
{
TableCell cell = new TableCell();
cell.Append(new Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(data.Rows[i][j].ToString()))));
cell.Append(new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Dxa, Width = "1200" }));
row.Append(cell);
}
table.Append(row);
}
body.Append(table);
doc.MainDocumentPart.Document.Save();
doc.Dispose();
}
And below code is to insert page numbers in a word document
private static void AddPageNumberFooters(WordprocessingDocument parent)
{
string documentPath = #"D:\EmptyDoc.docx";
using (WordprocessingDocument package =
WordprocessingDocument.Open(documentPath, true))
{
var mainDocumentPart = parent.AddMainDocumentPart();
GenerateMainDocumentPart().Save(mainDocumentPart);
var documentSettingsPart =
mainDocumentPart.AddNewPart
<DocumentSettingsPart>("rId1");
GenerateDocumentSettingsPart().Save(documentSettingsPart);
var firstPageFooterPart = mainDocumentPart.AddNewPart<FooterPart>("rId1");
GeneratePageFooterPart("Page 1 of 2").Save(firstPageFooterPart);
var secondPageFooterPart = mainDocumentPart.AddNewPart<FooterPart>("rId2");
GeneratePageFooterPart("Page 2 of 2").Save(secondPageFooterPart);
}
}
private static Document GenerateMainDocumentPart()
{
var element =
new Document(
new Body(
new Paragraph(
new Run(
new Text("Page 1 content"))
),
new Paragraph(
new Run(
new Break() { Type = BreakValues.Page })
),
new Paragraph(
new Run(
new LastRenderedPageBreak(),
new Text("Page 2 content"))
),
new Paragraph(
new Run(
new Break() { Type = BreakValues.Page })
),
new SectionProperties(
new FooterReference()
{
Type = HeaderFooterValues.First,
Id = "rId1"
},
new FooterReference()
{
Type = HeaderFooterValues.Even,
Id = "rId2"
},
new PageMargin()
{
Top = 1440,
Right = (UInt32Value)1440UL,
Bottom = 1440,
Left = (UInt32Value)1440UL,
Header = (UInt32Value)720UL,
Footer = (UInt32Value)720UL,
Gutter = (UInt32Value)0UL
},
new TitlePage()
)));
return element;
}
private static Header GeneratePageHeaderPart(string HeaderText)
{
var element =
new Header(
new Paragraph(
new ParagraphProperties(
new ParagraphStyleId() { Val = "Header" }),
new Run(
new Text(HeaderText))
));
return element;
}
My problem is, I have combine above both methods to export data along with page numbers.
if we know there are 2 pages in the word document, i can insert 2 FooterParts.
But i don't know how many pages will be created after exporting the data.
try the following code to automatically add page numbers:
private static string GenerateFooterPartContent(WordprocessingDocument package, string text = null)
{
FooterPart footerPart1 = package.MainDocumentPart.FooterParts.FirstOrDefault();
if (footerPart1 == null)
{
footerPart1 = package.MainDocumentPart.AddNewPart<FooterPart>();
}
var relationshipId = package.MainDocumentPart.GetIdOfPart(footerPart1);
// Get SectionProperties and set HeaderReference and FooterRefernce with new Id
SectionProperties sectionProperties1 = new SectionProperties();
FooterReference footerReference2 = new FooterReference() { Type = HeaderFooterValues.Default, Id = relationshipId };
sectionProperties1.Append(footerReference2);
package.MainDocumentPart.Document.Body.Append(sectionProperties1);
Footer footer1 = new Footer();
var r = new Run();
PositionalTab positionalTab2 = new PositionalTab() { Alignment = AbsolutePositionTabAlignmentValues.Right,
RelativeTo = AbsolutePositionTabPositioningBaseValues.Margin,
Leader = AbsolutePositionTabLeaderCharValues.None };
r.Append(positionalTab2);
paragraph2.Append(r);
r = new Run(new Text("Page: ") { Space = SpaceProcessingModeValues.Preserve },
// *** Adaptation: This will output the page number dynamically ***
new SimpleField() { Instruction = "PAGE" },
new Text(" of ") { Space = SpaceProcessingModeValues.Preserve },
// *** Adaptation: This will output the number of pages dynamically ***
new SimpleField() { Instruction = "NUMPAGES" });
paragraph2.Append(r);
footer1.Append(paragraph2);
footerPart1.Footer = footer1;
return relationshipId;
}
My Expected out put is
● AA
► BBB
■ CCC
I have tried a lot and but gets the output like this
● AA
● BBB
● CCC
My code is
Document document1 = new Document();
document1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
Body body1 = new Body();
Paragraph paragraph3 = new Paragraph();
ParagraphProperties paragraphProperties1 = new ParagraphProperties();
ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId(){ Val = "ListParagraph" };
Shading shading1 = new Shading(){ Val = ShadingPatternValues.Clear, Color = "auto", Fill = "Blue" };
SpacingBetweenLines spacingBetweenLines1 = new SpacingBetweenLines();
Justification justification1 = new Justification(){ Val = JustificationValues.Left };
NumberingProperties numberingProperties1 = new NumberingProperties();
NumberingLevelReference numberingLevelReference1 = new NumberingLevelReference(){ Val = 0 };
NumberingId numberingId1 = new NumberingId(){ Val = 1 };
numberingProperties1.Append(numberingLevelReference1);
numberingProperties1.Append(numberingId1);
paragraphProperties1.Append(paragraphStyleId1);
paragraphProperties1.Append(shading1);
paragraphProperties1.Append(spacingBetweenLines1);
paragraphProperties1.Append(justification1);
paragraphProperties1.Append(numberingProperties1);
Run run3 = new Run();
Text text2 = new Text();
text2.Text = "AA";
run3.Append(runProperties2);
run3.Append(text2);
paragraph3.Append(paragraphProperties1);
paragraph3.Append(run3);
Paragraph paragraph4 = new Paragraph();
ParagraphProperties paragraphProperties2 = new ParagraphProperties();
ParagraphStyleId paragraphStyleId2 = new ParagraphStyleId(){ Val = "ListParagraph" };
Shading shading2 = new Shading(){ Val = ShadingPatternValues.Clear, Color = "auto", Fill = "Blue" };
SpacingBetweenLines spacingBetweenLines2 = new SpacingBetweenLines();
Justification justification2 = new Justification(){ Val = JustificationValues.Left };
NumberingProperties numberingProperties2 = new NumberingProperties();
NumberingLevelReference numberingLevelReference2 = new NumberingLevelReference(){ Val = 0 };
NumberingId numberingId2 = new NumberingId(){ Val = 2 };
numberingProperties2.Append(numberingLevelReference2);
numberingProperties2.Append(numberingId2);
paragraphProperties2.Append(paragraphStyleId2);
paragraphProperties2.Append(shading2);
paragraphProperties2.Append(spacingBetweenLines2);
paragraphProperties2.Append(justification2);
paragraphProperties2.Append(numberingProperties2);
Run run4 = new Run();
Text text3 = new Text();
text3.Text = "BBB";
run4.Append(runProperties3);
run4.Append(text3);
paragraph4.Append(paragraphProperties2);
paragraph4.Append(run4);
Paragraph paragraph5 = new Paragraph();
ParagraphProperties paragraphProperties3 = new ParagraphProperties();
ParagraphStyleId paragraphStyleId3 = new ParagraphStyleId(){ Val = "ListParagraph" };
Shading shading3 = new Shading(){ Val = ShadingPatternValues.Clear, Color = "auto", Fill = "Blue" };
SpacingBetweenLines spacingBetweenLines3 = new SpacingBetweenLines();
Justification justification3 = new Justification(){ Val = JustificationValues.Left };
NumberingProperties numberingProperties3 = new NumberingProperties();
NumberingLevelReference numberingLevelReference3 = new NumberingLevelReference(){ Val = 0 };
NumberingId numberingId3 = new NumberingId(){ Val = 3 };
numberingProperties3.Append(numberingLevelReference3);
numberingProperties3.Append(numberingId3);
paragraphProperties3.Append(paragraphStyleId3);
paragraphProperties3.Append(shading3);
paragraphProperties3.Append(spacingBetweenLines3);
paragraphProperties3.Append(justification3);
paragraphProperties3.Append(numberingProperties3);
Run run5 = new Run();
Text text4 = new Text();
text4.Text = "CCC";
run5.Append(runProperties4);
run5.Append(text4);
paragraph5.Append(paragraphProperties3);
paragraph5.Append(run5);
body1.Append(paragraph1);
body1.Append(paragraph2);
body1.Append(paragraph3);
body1.Append(paragraph4);
body1.Append(paragraph5);
document1.Append(body1);
document1.Append(openXmlUnknownElement2);
mainDocumentPart1.Document = document1;
Numbering numbering1 = new Numbering();
numbering1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
AbstractNum abstractNum1 = new AbstractNum(){ AbstractNumberId = 0 };
MultiLevelType multiLevelType1 = new MultiLevelType(){ Val = MultiLevelValues.HybridMultilevel };
Level level1 = new Level(){ LevelIndex = 0 };
StartNumberingValue startNumberingValue1 = new StartNumberingValue(){ Val = 1 };
NumberingFormat numberingFormat1 = new NumberingFormat(){ Val = NumberFormatValues.Bullet };
LevelText levelText1 = new LevelText(){ Val = "●" };
LevelJustification levelJustification1 = new LevelJustification(){ Val = LevelJustificationValues.Left };
NumberingSymbolRunProperties numberingSymbolRunProperties1 = new NumberingSymbolRunProperties();
RunFonts runFonts6 = new RunFonts(){ Hint = FontTypeHintValues.Default, Ascii = "Arial", HighAnsi = "Arial" };
numberingSymbolRunProperties1.Append(runFonts6);
level1.Append(startNumberingValue1);
level1.Append(numberingFormat1);
level1.Append(levelText1);
level1.Append(levelJustification1);
level1.Append(numberingSymbolRunProperties1);
abstractNum1.Append(multiLevelType1);
abstractNum1.Append(level1);
NumberingInstance numberingInstance1 = new NumberingInstance(){ NumberID = 1 };
AbstractNumId abstractNumId1 = new AbstractNumId(){ Val = 0 };
numberingInstance1.Append(abstractNumId1);
AbstractNum abstractNum2 = new AbstractNum(){ AbstractNumberId = 1 };
MultiLevelType multiLevelType2 = new MultiLevelType(){ Val = MultiLevelValues.HybridMultilevel };
Level level2 = new Level(){ LevelIndex = 0 };
StartNumberingValue startNumberingValue2 = new StartNumberingValue(){ Val = 1 };
NumberingFormat numberingFormat2 = new NumberingFormat(){ Val = NumberFormatValues.Bullet };
LevelText levelText2 = new LevelText(){ Val = "►" };
LevelJustification levelJustification2 = new LevelJustification(){ Val = LevelJustificationValues.Left };
NumberingSymbolRunProperties numberingSymbolRunProperties2 = new NumberingSymbolRunProperties();
RunFonts runFonts7 = new RunFonts(){ Hint = FontTypeHintValues.Default, Ascii = "Arial", HighAnsi = "Arial" };
numberingSymbolRunProperties2.Append(runFonts7);
level2.Append(startNumberingValue2);
level2.Append(numberingFormat2);
level2.Append(levelText2);
level2.Append(levelJustification2);
level2.Append(numberingSymbolRunProperties2);
abstractNum2.Append(multiLevelType2);
abstractNum2.Append(level2);
NumberingInstance numberingInstance2 = new NumberingInstance(){ NumberID = 2 };
AbstractNumId abstractNumId2 = new AbstractNumId(){ Val = 6 };
numberingInstance2.Append(abstractNumId2);
AbstractNum abstractNum3 = new AbstractNum(){ AbstractNumberId = 2 };
MultiLevelType multiLevelType3 = new MultiLevelType(){ Val = MultiLevelValues.HybridMultilevel };
Level level3 = new Level(){ LevelIndex = 0 };
StartNumberingValue startNumberingValue3 = new StartNumberingValue(){ Val = 1 };
NumberingFormat numberingFormat3 = new NumberingFormat(){ Val = NumberFormatValues.Bullet };
LevelText levelText3 = new LevelText(){ Val = "■" };
LevelJustification levelJustification3 = new LevelJustification(){ Val = LevelJustificationValues.Left };
NumberingSymbolRunProperties numberingSymbolRunProperties3 = new NumberingSymbolRunProperties();
RunFonts runFonts8 = new RunFonts(){ Hint = FontTypeHintValues.Default, Ascii = "Arial", HighAnsi = "Arial" };
numberingSymbolRunProperties3.Append(runFonts8);
level3.Append(startNumberingValue3);
level3.Append(numberingFormat3);
level3.Append(levelText3);
level3.Append(levelJustification3);
level3.Append(numberingSymbolRunProperties3);
abstractNum3.Append(multiLevelType3);
abstractNum3.Append(level3);
NumberingInstance numberingInstance3 = new NumberingInstance(){ NumberID = 3 };
AbstractNumId abstractNumId3 = new AbstractNumId(){ Val = 3 };
numberingInstance3.Append(abstractNumId3);
numbering1.Append(abstractNum1);
numbering1.Append(numberingInstance1);
numbering1.Append(abstractNum2);
numbering1.Append(numberingInstance2);
numbering1.Append(abstractNum3);
numbering1.Append(numberingInstance3);
numberingDefinitionsPart1.Numbering = numbering1;
You need to append the NumberingInstances AFTER you have appended ALL the AbstractNumbers. They shouldn't be between them.