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

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

Related

C# OpenXML- Copying charts from Word document to another Word docu

Im trying to copy charts from one word document to another, and placing them at a bookmark location using OpenXml. However im unsure of how to append or insert the copied chart to the bookmark. I believe i have to add the chart object to a drawing or another object before adding it to the paragraph, but im having trouble getting this to work. Code below is the base of what im using to test with:
using (WordprocessingDocument doc = WordprocessingDocument.Open(SourceDoc, false))
{
List<ChartPart> chartFind = doc.MainDocumentPart.ChartParts.ToList();
using (WordprocessingDocument copydoc = WordprocessingDocument.Open(stream, true))
{
MainDocumentPart mainPart = copydoc.MainDocumentPart;
Body body = mainPart.Document.GetFirstChild<Body>();
var bmStart = body.Descendants<BookmarkStart>();
var bmEnd = body.Descendants<BookmarkEnd>();
//phone calls Chart
ChartPart PhoneChart = chartFind[0];
ChartPart chartPart = mainPart.AddNewPart<ChartPart>();
chartPart.ChartSpace = (ChartSpace)PhoneChart.ChartSpace.Clone();
foreach (BookmarkStart bookMarkStart in bmStart)
{
if (bookMarkStart.Name == "test")
{
var id = bookMarkStart.Id.Value;
var bookmarkEnd = bmEnd.Where(b => b.Id.Value == id).First();
Paragraph chartPara = new Paragraph();
bookmarkEnd.Parent.InsertAfterSelf(chartPara);
chartPara.InsertAfterSelf(chartPart.ChartSpace);
}
}
}
}
Open XML SDK Productivity Tool was a big help in troubleshooting. I was able add a chart by:
Creating a ChartPart object
Clone the original charts ChartSpace and add it to my ChartPart
Create a Drawing object with a ChartReference with the same ID as my ChartPart in order
to link them
Appending the Drawing object to new run and paragraph before inserting at the bookmark
I did have an issue that wasted a bit of time, which was caused by the data in the charts being linked to an excel document, which i wasnt able to access through my app. In order to display the charts i had to break the external data relationship through:
chartPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/
relationships/oleObject", new System.Uri("NULL", System.UriKind.Relative), "rId2");
the code below for future reference
using (WordprocessingDocument doc = WordprocessingDocument.Open(SourceDoc, false))
{
//List<ChartPart> chartFind = doc.MainDocumentPart.ChartParts.ToList();
//List<Drawing> drawingList = doc.MainDocumentPart.Document.Descendants<Drawing>().ToList();
MainDocumentPart mainPartDoc = doc.MainDocumentPart;
var mainDoc = mainPartDoc.Document;
using (WordprocessingDocument copydoc = WordprocessingDocument.Open(stream, true))
{
MainDocumentPart mainPart = copydoc.MainDocumentPart;
var document = mainPart.Document;
var bmStart = document.Descendants<BookmarkStart>();
var bmEnd = document.Descendants<BookmarkEnd>();
foreach (BookmarkStart bookMarkStart in bmStart)
{
if (bookMarkStart.Name == "test")
{
//find charts and names from original document
List<ChartPart> findCharts = mainPartDoc.ChartParts.ToList();
var partCheck = (from f in findCharts
select f.ChartSpace.GetFirstChild<Chart>().Title.InnerText).ToList();
ChartPart chartPart = mainPart.AddNewPart<ChartPart>();
ChartPart chartSelect = findCharts[3];
//ChartPart chartSelect = mainPartDoc.ChartParts.FirstOrDefault();
chartPart.ChartSpace = (ChartSpace)chartSelect.ChartSpace.Clone();
string relId = mainPart.GetIdOfPart(chartPart);
AutoUpdate autoUpdate1 = new AutoUpdate() { Val = false };
chartPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject",
new System.Uri("NULL", System.UriKind.Relative), "rId2");
Paragraph paragraph = new Paragraph();
Drawing drawing = new Drawing();
Run run = new Run();
Inline inline = new Inline() { DistanceFromTop = (UInt32Value)0U, DistanceFromBottom = (UInt32Value)0U, DistanceFromLeft = (UInt32Value)0U, DistanceFromRight = (UInt32Value)0U, AnchorId = "716A168E", EditId = "2D11B07F" };
Extent extent = new Extent() { Cx = 6572250L, Cy = 2586038L };
EffectExtent effectExtent1 = new EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 5080L };
DocProperties docProperties1 = new DocProperties() { Id = (UInt32Value)13U, Name = "Chart 13" };
NonVisualGraphicFrameDrawingProperties nonVisualGraphicFrameDrawingProperties1 = new NonVisualGraphicFrameDrawingProperties();
dr.Graphic graphic = new dr.Graphic();
graphic.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main");
dr.GraphicData graphicData = new dr.GraphicData() { Uri = "http://schemas.openxmlformats.org/drawingml/2006/chart" };
ChartReference chartReference1 = new ChartReference() { Id = relId };
chartReference1.AddNamespaceDeclaration("c", "http://schemas.openxmlformats.org/drawingml/2006/chart");
chartReference1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
graphicData.Append(chartReference1);
graphic.Append(graphicData);
inline.Append(extent);
inline.Append(effectExtent1);
inline.Append(docProperties1);
inline.Append(nonVisualGraphicFrameDrawingProperties1);
inline.Append(graphic);
drawing.Append(inline);
run.Append(drawing);
paragraph.Append(run);
var id = bookMarkStart.Id.Value;
var bookmarkEnd = bmEnd.Where(i => i.Id.Value == id).First();
bookmarkEnd.Parent.InsertAfterSelf(paragraph);
// mainPart.Document.Body.Append(paragraph);
}
}
}

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.

Add FootNotes to Word Document Programatically using OpenXML SDK 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);

How to copy a slide to a word Document without using interop?

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

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

Categories