write to powerpoint pptx from c# using openxml - c#

I am writing a data in to a pptx last slide using openxml in csharp and below is code to save the ppt
public static void CreateTableInLastSlide(PresentationDocument presentationDocument)
{
// Get the presentation Part of the presentation document
PresentationPart presentationPart = presentationDocument.PresentationPart;
// Get the Slide Id collection of the presentation document
var slideIdList = presentationPart.Presentation.SlideIdList;
if (slideIdList == null)
{
throw new NullReferenceException("The number of slide is empty, please select a ppt with a slide at least again");
}
// Get all Slide Part of the presentation document
var list = slideIdList.ChildElements
.Cast<SlideId>()
.Select(x => presentationPart.GetPartById(x.RelationshipId))
.Cast<SlidePart>();
// Get the last Slide Part of the presentation document
var tableSlidePart = (SlidePart)list.Last();
// Declare and instantiate the graphic Frame of the new slide
P.GraphicFrame graphicFrame = tableSlidePart.Slide.CommonSlideData.ShapeTree.AppendChild(new P.GraphicFrame());
ApplicationNonVisualDrawingPropertiesExtension applicationNonVisualDrawingPropertiesExtension = new ApplicationNonVisualDrawingPropertiesExtension();
P14.ModificationId modificationId1 = new P14.ModificationId() { Val = 3229994563U };
modificationId1.AddNamespaceDeclaration("p14", "http://schemas.microsoft.com/office/powerpoint/2010/main");
applicationNonVisualDrawingPropertiesExtension.Append(modificationId1);
graphicFrame.NonVisualGraphicFrameProperties = new DocumentFormat.OpenXml.Presentation.NonVisualGraphicFrameProperties
(new A.NonVisualDrawingProperties() { Id = 5, Name = "table 1" },
new A.NonVisualGraphicFrameDrawingProperties(new A.GraphicFrameLocks() { NoGrouping = true }),
new ApplicationNonVisualDrawingProperties(new ApplicationNonVisualDrawingPropertiesExtensionList(applicationNonVisualDrawingPropertiesExtension)));
graphicFrame.Transform = new Transform(new Offset() { X = 10, Y = 10 });
graphicFrame.Graphic = new A.Graphic(new A.GraphicData(GenerateTable()) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/table" });
presentationPart.Presentation.Save();
}
the file is saved with required data but
While opening the powerpoint I get the following error:
Powerpoint found a problem with content in "Sample.pptx". Power point can attempt to repair the presentation.
Once repaired, the content is shown ok. but since the file is corrupted when i run the code it is not updating with the latest data nexttime.
Please help me to solve the issue
-tried to open in different version of office but no luck
-created the template from different versions still the issue occurs

Related

Add date on Presentations (Open XML SDK) on C#

My reference is Presentations (Open XML SDK)
With the code-behind below I add the date on existing PowerPoint.
This code working and in the first slide the date is added, but it's possible customize the point on the page where to insert this date? The font and size ?
This is current output:
Thank you in advance for help.
string fileName = #"C:\\inetpub\\wwwroot\\aspnet\\Template\\01_FOCUS.pptx";
using (PresentationDocument oPDoc = PresentationDocument.Open(fileName, true))
{
PresentationPart oPPart = oPDoc.PresentationPart;
SlideIdList slideIdList = oPPart.Presentation.SlideIdList;
SlidePart sp = slideIdList.ChildElements
.Cast<SlideId>()
.Select(x => oPPart.GetPartById(x.RelationshipId))
.Cast<SlidePart>().First();
AddDateToSlidePart(sp);
}
public static void AddDateToSlidePart(SlidePart slidePart1)
{
Slide slide1 = slidePart1.Slide;
CommonSlideData commonSlideData1 = slide1.GetFirstChild<CommonSlideData>();
ShapeTree shapeTree1 = commonSlideData1.GetFirstChild<ShapeTree>();
DocumentFormat.OpenXml.Presentation.Shape shape1 =
new DocumentFormat.OpenXml.Presentation.Shape();
DocumentFormat.OpenXml.Presentation.NonVisualShapeProperties nonVisualShapeProperties1 =
new DocumentFormat.OpenXml.Presentation.NonVisualShapeProperties();
DocumentFormat.OpenXml.Presentation.NonVisualDrawingProperties nonVisualDrawingProperties1 =
new DocumentFormat.OpenXml.Presentation.NonVisualDrawingProperties() { Id = (UInt32Value)4U, Name = "Date Placeholder 3" };
DocumentFormat.OpenXml.Presentation.NonVisualShapeDrawingProperties nonVisualShapeDrawingProperties1 =
new DocumentFormat.OpenXml.Presentation.NonVisualShapeDrawingProperties();
DocumentFormat.OpenXml.Drawing.ShapeLocks shapeLocks1 =
new DocumentFormat.OpenXml.Drawing.ShapeLocks() { NoGrouping = true };
nonVisualShapeDrawingProperties1.Append(shapeLocks1);
ApplicationNonVisualDrawingProperties applicationNonVisualDrawingProperties1 =
new ApplicationNonVisualDrawingProperties();
PlaceholderShape placeholderShape1 =
new PlaceholderShape() { Type = PlaceholderValues.DateAndTime, Size = PlaceholderSizeValues.Half, Index = (UInt32Value)10U };
applicationNonVisualDrawingProperties1.Append(placeholderShape1);
nonVisualShapeProperties1.Append(nonVisualDrawingProperties1);
nonVisualShapeProperties1.Append(nonVisualShapeDrawingProperties1);
nonVisualShapeProperties1.Append(applicationNonVisualDrawingProperties1);
DocumentFormat.OpenXml.Presentation.ShapeProperties shapeProperties1 =
new DocumentFormat.OpenXml.Presentation.ShapeProperties();
DocumentFormat.OpenXml.Presentation.TextBody textBody1 =
new DocumentFormat.OpenXml.Presentation.TextBody();
DocumentFormat.OpenXml.Drawing.BodyProperties bodyProperties1 =
new DocumentFormat.OpenXml.Drawing.BodyProperties();
DocumentFormat.OpenXml.Drawing.ListStyle listStyle1 =
new DocumentFormat.OpenXml.Drawing.ListStyle();
DocumentFormat.OpenXml.Drawing.Paragraph paragraph1 =
new DocumentFormat.OpenXml.Drawing.Paragraph();
DocumentFormat.OpenXml.Drawing.Field field1 =
new DocumentFormat.OpenXml.Drawing.Field() { Id = "{528B97E8-8E4B-4D32-BA17-4F287283DFD6}", Type = "datetime1" };
DocumentFormat.OpenXml.Drawing.RunProperties runProperties1 =
new DocumentFormat.OpenXml.Drawing.RunProperties() { Language = "it-IT" };
DocumentFormat.OpenXml.Drawing.Text text1 =
new DocumentFormat.OpenXml.Drawing.Text();
text1.Text = DateTime.Now.ToString("dd/mm/yyyy");
field1.Append(runProperties1);
field1.Append(text1);
DocumentFormat.OpenXml.Drawing.EndParagraphRunProperties endParagraphRunProperties1 =
new DocumentFormat.OpenXml.Drawing.EndParagraphRunProperties() { Language = "it-IT" };
paragraph1.Append(field1);
paragraph1.Append(endParagraphRunProperties1);
textBody1.Append(bodyProperties1);
textBody1.Append(listStyle1);
textBody1.Append(paragraph1);
shape1.Append(nonVisualShapeProperties1);
shape1.Append(shapeProperties1);
shape1.Append(textBody1);
shapeTree1.Append(shape1);
}
The OpenXML SDK Productivity tool (downloadable from the Microsoft site) is your friend here. When I need to do something like this, I:
Create the document I want
Open it in the appropriate tool (PowerPoint in this case).
Make a tiny change (to "dirty" the document and make PowerPoint believe it needs to be changed).
Save the result
Make the changes to the document that I want to see, and save the result with a new name
Open the OpenXML Productivity Tool and click the "Compare Files" tool.
The reason I force a save (in steps 3/4) is so that PowerPoint can add all of it's PowerPoint-ness to the document I created. The second save (step 5) will necessarily have all of that, so I want the two documents as close as possible - with only the "changes to the document that I want to see" being the difference between the two documents.
At this point, you should see a path to a solution to your problem. That tool is indispensable when working with OOXML.

How to add custom tags to powerpoint slides using OpenXml in c#

I'm trying to add custom tags to PowerPoint slides using OpenXml component in c#.
But after adding the tags dynamically, the presentation gets corrupted and is causing the powerpoint to stop working.
Following is the code I'm using for adding the tags:
public static void AddSlideTag(string presentationPath, string tagValue)
{
using (PresentationDocument presentation = PresentationDocument.Open(presentationPath, true))
{
var presPart = presentation.PresentationPart;
// Copy each slide in the source presentation, in order, to
// the destination presentation.
var slideIndex = 0;
foreach (var openXmlElement in presPart.Presentation.SlideIdList)
{
var slideId = (SlideId)openXmlElement;
// Create a unique relationship id.
var sp = (SlidePart)presPart.GetPartById(slideId.RelationshipId);
//create userDefinedTag
Tag slideObjectTag = new Tag() { Name = "CustomTag", Val = tagValue};
UserDefinedTagsPart userDefinedTagsPart1 = sp.AddNewPart<UserDefinedTagsPart>();
if (userDefinedTagsPart1.TagList == null)
userDefinedTagsPart1.TagList = new TagList();
userDefinedTagsPart1.TagList.Append(slideObjectTag);
//add tag to CustomerDataList element
var id = sp.GetIdOfPart(userDefinedTagsPart1);
if (sp.Slide.CommonSlideData == null)
{
sp.Slide.CommonSlideData = new CommonSlideData();
}
if (sp.Slide.CommonSlideData.CustomerDataList == null)
sp.Slide.CommonSlideData.CustomerDataList = new CustomerDataList();
CustomerDataTags tags = new CustomerDataTags();
tags.Id = id;
sp.Slide.CommonSlideData.CustomerDataList.AppendChild(tags);
slideIndex++;
sp.Slide.Save();
}
presPart.Presentation.Save();
}
}
It seems like the xml of the slides is broken after executing this code, but I cannot figure out what is the problem.
Does anyone know what is wrong with the code above, or what is causing the powerpoint to gets corrupted after running this code? Am I missing something here?
I'm using DocumentFormat.OpenXml.2.5 package.

C# add simple title for spreadsheet chart OpenXml

Hi!!
i'm able to write charts to my XLSX file. But i'm stuck adding a simple title for every chart. No styles just simple plain text.
My code is like this:
String Dtitulo = "Hello chart";
DocumentFormat.OpenXml.Drawing.Charts.Title chartTitle = new DocumentFormat.OpenXml.Drawing.Charts.Title();
chartTitle.ChartText = new ChartText();
chartTitle.ChartText.RichText = new RichText();
DocumentFormat.OpenXml.Drawing.Paragraph parrafoTitulo = new DocumentFormat.OpenXml.Drawing.Paragraph();
DocumentFormat.OpenXml.Drawing.Run run = parrafoTitulo.AppendChild(new DocumentFormat.OpenXml.Drawing.Run());
run.AppendChild(new DocumentFormat.OpenXml.Drawing.Text(Dtitulo));
chartTitle.ChartText.RichText.AppendChild<DocumentFormat.OpenXml.Drawing.Paragraph>(parrafoTitulo);
chart.Title = chartTitle;
But when i open my file with excel says "file is corrupt" or something like that.
A bit late but I was faced with the same task, and I created an excel sheet and added manually a chart with a chart title, then opened the xml to understand what tags were needed. And after a while I got it working. moved everything in a small function as below:
So you can provide your chart object and the title you want to the below function and it will add the chart title.
Note:Im using Open XML SDK 2.0 for Microsoft Office
private 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 });
}
And if you want a full example, you can review the official one here, and inject the above function in the right place (after the creation of the chart object) and it will add the chart title.

How to insert custom page number in Aspose.Words

I want to add custom page numbers (like 1/2,2/2) to word document with using Aspose.Words. But I couldn't find any sample for c# language. I tried to overrite footer but i couldn't give a format to page numbers.
Pls help!
Thanks!
edit
After i tried first answer,it worked as what i want but another problem came up. I adding child documents to main document. I can only formatting main document's number. Child documents still have ordinary page number.
Here a sample of code;
public void AddChildDocs (System.IO.Stream parentStream, List<System.IO.Stream> childStreams)
{
doc = new Aspose.Words.Document(parentStream);
if (Items.Count > 0)
{
WordReplacer evaluator = new WordReplacer(this);
doc.Range.Replace(new Regex(ReplaceRegex), evaluator, false);
}
foreach (var item in childStreams)
{
Aspose.Words.Document childDoc = new Aspose.Words.Document(item);
if (Items.Count > 0)
{
WordReplacer evaluator = new WordReplacer(this);
childDoc.Range.Replace(new Regex(ReplaceRegex), evaluator, false);
}
doc.AppendDocument(childDoc, ImportFormatMode.KeepSourceFormatting);
}
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
builder.InsertField("PAGE", "");
builder.Write(" / ");
builder.InsertField("NUMPAGES", "");
}
You can get idea from this page in Aspose documentation. Below is the sample code taken from the same page, but only related to custom page numbers.
String src = dataDir + "Page numbers.docx";
String dst = dataDir + "Page numbers_out.docx";
// Create a new document or load from disk
Aspose.Words.Document doc = new Aspose.Words.Document(src);
// Create a document builder
Aspose.Words.DocumentBuilder builder = new DocumentBuilder(doc);
// Go to the primary footer
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
// Add fields for current page number
builder.InsertField("PAGE", "");
// Add any custom text
builder.Write(" / ");
// Add field for total page numbers in document
builder.InsertField("NUMPAGES", "");
// Import new document
Aspose.Words.Document newDoc = new Aspose.Words.Document(dataDir + "new.docx");
// Link the header/footer of first section to previous document
newDoc.FirstSection.HeadersFooters.LinkToPrevious(true);
doc.AppendDocument(newDoc, ImportFormatMode.UseDestinationStyles);
// Save the document
doc.Save(dst);
I work with Aspose as Developer Evangelist.
Here is the code to set custom page number in aspose.word, when you set page margins and starting page number then it automatically get next page when that particular page area is finished. Try this it will work...
section.PageSetup.PaperSize = PaperSize.Letter;
section.PageSetup.LeftMargin = 10;
section.PageSetup.RightMargin = 10;
section.PageSetup.TopMargin = 00;
section.PageSetup.BottomMargin = 0;
section.PageSetup.HeaderDistance = 50;
section.PageSetup.FooterDistance = 50;
section.PageSetup.Borders.Color = Color.Black;
section.PageSetup.PageStartingNumber = 1;

Creating statecharts in Visio using c#

Can anyone point me to an example of how to programatically create a statechart in visio?
I can create blank pages, drop shapes, open template etc, but when I try to add transitions it complains that the page is not the right type.
Can't find a sample anywhere.
Alternatively: I can save the user actions to create the chart as a macro. Can I run that programatically?
Thanks.
< edit >
Step away from the PC for 2 minutes and you realise you should have put the code snippet in the question and not try to put it in comments. Forest: meet trees...
Visio.Document umlStencil = visioApp.Documents.OpenEx(#"UMLSTA_M.vss", (short)VisOpenSaveArgs.visOpenDocked);
Visio.Page page = visioDoc.Pages.Add();
Visio.Shape s1 = page.Drop(umlStencil[#"State"], 5.0, 5.0);
Visio.Shape s2 = page.Drop(umlStencil[#"State"], 5.0, 5.0);
Visio.Shape transition = page.Drop(umlStencil[#"Transition"], 1.0, 1.0);
As you can see, pretty similar to the snippet in the answer below.
< / edit >
This is the code that I ran with Visual Studio 2010 against both Visio 2007 and Visio 2010.
var visioApp = new Visio.Application();
// Load the UML Statechart stencil (docked)
var stencil_open_flags = Visio.VisOpenSaveArgs.visOpenDocked;
var umlStencil = visioApp.Documents.OpenEx(#"UMLSTA_M.vss", (short)stencil_open_flags);
// create a new empty doc based on the UML Model Template
var doc = visioApp.Documents.AddEx("UMLMOD_U.VST", Visio.VisMeasurementSystem.visMSUS, 0, 0);
var page = doc.Pages.Add();
// Find and manually change the diagram's title
var watermark = page.Shapes["Watermark Title"];
var LockTextEdit_cell = watermark.CellsU["LockTextEdit"];
LockTextEdit_cell.FormulaForceU = "GUARD(0)";
watermark.Text = "MyTitle";
LockTextEdit_cell.FormulaForceU = "GUARD(1)";
// Find the masters we need
var state_master = umlStencil.Masters["State"];
var transition_master = umlStencil.Masters["Transition"];
// Drop the masters into the page
var s1 = page.Drop(state_master, 5.0, 5.0);
var s2 = page.Drop(state_master, 1.0, 1.0);
var transition = page.Drop(transition_master, 3.0, 3.0);

Categories