Add FootNotes to Word Document Programatically using OpenXML SDK C# - c#

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

Related

OpenXml (.net): SimpleField is not formated

I tried to create a word document with page number in Header. I used SimpleField to insert Page number and page count.
But, these fields are not impacted by Color and font size defined in the RunProperties, unlike the text (as it's showed in the picture below).
How to format SimpleField??
Thanks
private static void CreateReport(string filename)
{
using (var mem = new MemoryStream())
{
using (var wordDocument = WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document, true))
{
// Add a main document part.
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
// Create the document structure
mainPart.Document = new Document();
mainPart.Document.Body = new Body();
//Create paragraph for header
var paragraph = new Paragraph();
var run = paragraph.AppendChild(new Run());
run.Append(new RunProperties()
{
Bold = new Bold(),
FontSize = new FontSize() { Val = "48" },
Color = new Color() { Val = "FF0000" /*red*/ }
}
);
run.Append(new Text() { Text = "Page:" });
run.Append(new SimpleField() { Instruction = #"PAGE" });
run.Append(new Text() { Text = "/" });
run.Append(new SimpleField() { Instruction = #"SECTIONPAGES" });
//Add paragraph to header
AddParagraphToHeader(mainPart, paragraph);
//Save document
wordDocument.SaveAs(filename);
}
}
}
private static void AddParagraphToHeader(MainDocumentPart mainPart, Paragraph paragraph)
{
var part = mainPart.AddNewPart<HeaderPart>();
var header = new Header() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "w14 wp14" } };
header.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
header.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
header.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
header.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
header.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
header.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
header.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
header.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
header.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
header.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
header.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
header.AddNamespaceDeclaration("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
header.AddNamespaceDeclaration("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
header.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
header.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");
paragraph.RsidParagraphAddition = "00164C17";
paragraph.RsidRunAdditionDefault = "00164C17";
header.Append(paragraph);
part.Header = header;
var headerPartId = mainPart.GetIdOfPart(part);
mainPart.Document.PrependChild<HeaderReference>((new HeaderReference() { Id = headerPartId }));
}
After fighting with this, I found a solution that works for me -- SimpleField is the wrong thing to use for this scenario, you need to end up with a w:instrText by generating FieldChar and FieldCode objects, which means your code needs to be something like this:
Run PageNumRun = new Run(
new Text() { Text = "PAGE ", Space = SpaceProcessingModeValues.Preserve },
new FieldChar { FieldCharType = FieldCharValues.Begin },
new FieldCode("PAGE"), // This is the "Instruction" from the SimpleField
new FieldChar { FieldCharType = FieldCharValues.End },
new Text() { Text = " OF ", Space = SpaceProcessingModeValues.Preserve },
new FieldChar { FieldCharType = FieldCharValues.Begin },
new FieldCode("NUMPAGES"), // This is the "Instruction" from the SimpleField
new FieldChar { FieldCharType = FieldCharValues.End }
);
This will honor your Run font characteristics for the automatically generated values.

Export Datatable to Word Document With Page Numbers using Open XML

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

OpenXMl Bulleted List with mUltiple Bullet Charcter.?

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.

How to paginate a Word document from c# with Open XML

How to paginate a word document for example
if there are 10 pages:
page 1 of 10
Page 2 of 10 ...
if there are 15 pages
1 of 15 Page
2 of 15 ...
and so on to generate a dynamic number of pages
It has been three years since you asked your question but maybe I can help other people that are facing this problem.
Here is the code that can paginate a word document.
string documentPath = #"C:\Temp\FooterPOC.docx";
using (WordprocessingDocument package =
WordprocessingDocument.Create(
documentPath, WordprocessingDocumentType.Document))
{
{
MainDocumentPart objMainDocumentPart = package.AddMainDocumentPart();
Document objDocument = new Document();
objMainDocumentPart.Document = objDocument;
Body objBody = new Body();
SectionProperties objSectionProperties = new SectionProperties();
FooterPart objFootPart = objMainDocumentPart.AddNewPart<FooterPart>();
Footer objFooter = new Footer();
objFootPart.Footer = objFooter;
Paragraph objParagraph_1 = new Paragraph();
ParagraphProperties objParagraphProperties = new ParagraphProperties();
ParagraphStyleId objParagraphStyleId = new ParagraphStyleId() { Val = "Footer" };
objParagraphProperties.Append(objParagraphStyleId);
Justification objJustification = new Justification() { Val = JustificationValues.Right };
objParagraphProperties.Append(objJustification);
objParagraph_1.Append(objParagraphProperties);
Run objRun_1 = new Run();
Text objText_1 = new Text() { Space = SpaceProcessingModeValues.Preserve };
objText_1.Text = "Página ";
objRun_1.Append(objText_1);
objParagraph_1.Append(objRun_1);
Run objRun_2 = new Run();
FieldChar objFieldChar_1 = new FieldChar() { FieldCharType = FieldCharValues.Begin };
objRun_2.Append(objFieldChar_1);
objParagraph_1.Append(objRun_2);
Run objRun_3 = new Run();
FieldCode objFieldCode_1 = new FieldCode();
objFieldCode_1.Text = "PAGE";
objRun_3.Append(objFieldCode_1);
objParagraph_1.Append(objRun_3);
Run objRun_6 = new Run();
FieldChar objFieldChar_3 = new FieldChar() { FieldCharType = FieldCharValues.End };
objRun_6.Append(objFieldChar_3);
objParagraph_1.Append(objRun_6);
Run objRun_7 = new Run();
Text objText_3 = new Text() { Space = SpaceProcessingModeValues.Preserve };
objText_3.Text = " de ";
objRun_7.Append(objText_3);
objParagraph_1.Append(objRun_7);
Run objRun_8 = new Run();
FieldChar objFieldChar_4 = new FieldChar() { FieldCharType = FieldCharValues.Begin };
objRun_8.Append(objFieldChar_4);
objParagraph_1.Append(objRun_8);
Run objRun_9 = new Run();
FieldCode objFieldCode_2 = new FieldCode();
objFieldCode_2.Text = "NUMPAGES";
objRun_9.Append(objFieldCode_2);
objParagraph_1.Append(objRun_9);
Run objRun_12 = new Run();
FieldChar objFieldChar_6 = new FieldChar() { FieldCharType = FieldCharValues.End };
objRun_12.Append(objFieldChar_6);
objParagraph_1.Append(objRun_12);
objFooter.Append(objParagraph_1);
string strFootrID = objMainDocumentPart.GetIdOfPart(objFootPart);
FooterReference objFooterReference = new FooterReference()
{
Type = HeaderFooterValues.Default,
Id = strFootrID
};
objSectionProperties.Append(objFooterReference);
objBody.Append(objSectionProperties);
objMainDocumentPart.Document.Append(objBody);
}
}
I found this code here. It was a little bit buggy but it helped me a lot!
There were a few lines that i thought it was unnecessary so i removed it and worked great, but i'm only a newbie in openXML so maybe they were in fact necessary.
Cheers!
The Open Xml SDK does NOT provide application behaviors such as layout (ex. pagination of WordprocessingML documents) or recalculation functionality. You can read more # http://blogs.msdn.com/b/brian_jones/archive/2008/10/06/open-xml-format-sdk-2-0.aspx

how to add footer with images in word document in .net

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");

Categories