I'm trying to edit a paragraph in pptx through changing its text, font size, font style and alignment.
This is what i have done so far:
**this is the method im using to call the update paragraph**
public static void Main(string[] args)
{
using (PresentationDocument presentationDocument = PresentationDocument.Open("ppturl", true))
{
// Get the presentation part of the presentation document.
PresentationPart presentationPart = presentationDocument.PresentationPart;
// Verify that the presentation part and presentation exist.
if (presentationPart != null && presentationPart.Presentation != null)
{
// Get the Presentation object from the presentation part.
Presentation presentation = presentationPart.Presentation;
// Verify that the slide ID list exists.
if (presentation.SlideIdList != null)
{
SlideId sourceSlide = presentation.SlideIdList.ChildElements[0] as SlideId;
SlidePart slidePart = presentationPart.GetPartById(sourceSlide.RelationshipId) as SlidePart;
updateParagraph(slidePart);
}
}
}
Console.ReadLine();
CreateHostBuilder(args).Build().Run();
}
**Here im extracting the title in the slide because this is what i need.**
public static void updateParagraph(SlidePart slidePart)
{
if (slidePart == null)
{
throw new ArgumentNullException("presentationDocument");
}
if (slidePart.Slide != null)
{
// Find all the title shapes.
var shapes = from shape in slidePart.Slide.Descendants<Shape>()
where IsTitleShape(shape)
select shape;
foreach (P.Shape shape in shapes)
{
D.Paragraph paragraph = shape.TextBody.Elements<D.Paragraph>().FirstOrDefault();
shape.TextBody.RemoveAllChildren<D.Paragraph>();
AddNewParagraph(shape, "This is a new Slide");
}
}
}
**This is where i am trying to add a new paragraph with specific style**
public static void AddNewParagraph(this P.Shape shape, string NewText)
{
D.Paragraph p = new D.Paragraph();
P.TextBody docBody = shape.TextBody;
Justification justification1 = new Justification() { Val = JustificationValues.Center };
p.ParagraphProperties=new D.ParagraphProperties(justification1);
D.Run run = new D.Run(new D.Text(NewText));
D.RunProperties runProp = new D.RunProperties() { Language = "en-US", FontSize = 9, Dirty = false };
run.AppendChild(runProp);
D.Text newText = new D.Text(NewText);
run.AppendChild(newText);
Console.WriteLine("--------------------------------------------------------------");
Console.WriteLine(runProp.FontSize.ToString());
Console.WriteLine("--------------------------------------------------------------");
p.Append(run);
docBody.Append(p);
}
This is giving me an error whenever im trying to open the pptx "repair pptx error".
Can someone please provide a clear solution specific to pptx and not doc.?
Thankful..
You can try using Aspose.Slides for .NET. The following code example shows you how to change some paragraph properties with this library:
using (var presentation = new Presentation("example.pptx"))
{
var firstShape = (IAutoShape) presentation.Slides[0].Shapes[0];
var firstParagraph = firstShape.TextFrame.Paragraphs[0];
var firstPortion = firstParagraph.Portions[0];
firstPortion.Text = "New text.";
firstPortion.PortionFormat.FontHeight = 24;
firstPortion.PortionFormat.FontBold = NullableBool.True;
firstParagraph.ParagraphFormat.Alignment = TextAlignment.Center;
presentation.Save("example.pptx", SaveFormat.Pptx);
}
You can also evaluate Aspose.Slides Cloud SDK for .NET. This REST-based API allows you to make 150 free API calls per month for API learning and presentation processing. The following code example shows you how to change the paragraph settings using Aspose.Slides Cloud:
var slidesApi = new SlidesApi("my_client_id", "my_client_key");
var fileName = "example.pptx";
var slideIndex = 1;
var shapeIndex = 1;
var paragraphIndex = 1;
var portionIndex = 1;
var firstPortion = slidesApi.GetPortion(
fileName, slideIndex, shapeIndex, paragraphIndex, portionIndex);
firstPortion.Text = "New text.";
firstPortion.FontHeight = 24;
firstPortion.FontBold = Portion.FontBoldEnum.True;
slidesApi.UpdatePortion(
fileName, slideIndex, shapeIndex, paragraphIndex, portionIndex, firstPortion);
var firstParagraph = slidesApi.GetParagraph(
fileName, slideIndex, shapeIndex, paragraphIndex);
firstParagraph.Alignment = Paragraph.AlignmentEnum.Center;
slidesApi.UpdateParagraph(
fileName, slideIndex, shapeIndex, paragraphIndex, firstParagraph);
I work as a Support Developer at Aspose.
Related
On the page https://api.libreoffice.org/examples/examples.html#OLE_examples
there are 2 examples of working with the OpenOffice CLI libraries.
These examples show you how to insert a hyperlink into an OO Calc document. But it is not clear how to insert a hyperlink into an OO Writer document.
Here is the code I wrote:
static void Main(string[] args)
{
try
{
unoidl.com.sun.star.uno.XComponentContext localContext =
uno.util.Bootstrap.bootstrap();
unoidl.com.sun.star.lang.XMultiServiceFactory multiServiceFactory = (unoidl.com.sun.star.lang.XMultiServiceFactory)localContext.
getServiceManager();
XComponentLoader componentLoader = (XComponentLoader)
multiServiceFactory.createInstance("com.sun.star.frame.Desktop");
string fileName = "c:\\Users\\sbe.CSOFT-SPB\\Documents\\OO\\1.odt";
//string fileName = "c:\\Users\\sbe.CSOFT-SPB\\Documents\\OO\\t1.ods";
fileName = #"file:///" + fileName.Replace('\\', '/');
XComponent xComponent = componentLoader.loadComponentFromURL(
fileName, "_blank",
0, new unoidl.com.sun.star.beans.PropertyValue[0]);
if (fileName.ToLower().EndsWith(".odt")) // OO Writer document
{
unoidl.com.sun.star.text.XTextDocument xTextDocument =
(unoidl.com.sun.star.text.XTextDocument)xComponent;
unoidl.com.sun.star.text.XText xText = xTextDocument.getText();
unoidl.com.sun.star.text.XSimpleText xSimpleText =
(unoidl.com.sun.star.text.XSimpleText)xText;
unoidl.com.sun.star.text.XTextCursor xCursor = xSimpleText.createTextCursor();
unoidl.com.sun.star.lang.XMultiServiceFactory xServiceMan =
(unoidl.com.sun.star.lang.XMultiServiceFactory)xTextDocument;
// create a TextFrame (
Object objTextFrame = xServiceMan.createInstance("com.sun.star.text.TextFrame");
unoidl.com.sun.star.text.XTextFrame xTextFrame =
(unoidl.com.sun.star.text.XTextFrame)objTextFrame;
unoidl.com.sun.star.awt.Size aSize = new unoidl.com.sun.star.awt.Size(15000, 400);
((unoidl.com.sun.star.drawing.XShape)xTextFrame).setSize(aSize);
// insert the frame
xText.insertTextContent(xCursor, xTextFrame, false); // it's OK
// create a hyperlink
Object aHyperlinkObj = xServiceMan.createInstance("com.sun.star.text.TextField.URL");
xServiceMan.createInstance("com.sun.star.text.TextField.URL");
unoidl.com.sun.star.beans.XPropertySet xPropSet =
(unoidl.com.sun.star.beans.XPropertySet)aHyperlinkObj;
xPropSet.setPropertyValue(
"URL", new uno.Any("http://www.example.org"));
xPropSet.setPropertyValue(
"Representation", new uno.Any("hyperlink"));
// ... and insert
unoidl.com.sun.star.text.XTextContent xContent =
(unoidl.com.sun.star.text.XTextContent)aHyperlinkObj;
xText.insertTextContent(xCursor, xContent, false); // exception on this statemen
}
else // OO Calc document
{
unoidl.com.sun.star.sheet.XSpreadsheetDocument mxDocument =
(unoidl.com.sun.star.sheet.XSpreadsheetDocument)xComponent;
unoidl.com.sun.star.sheet.XSpreadsheets xSheets = mxDocument.getSheets();
unoidl.com.sun.star.container.XIndexAccess xSheetsIA =
(unoidl.com.sun.star.container.XIndexAccess)xSheets;
unoidl.com.sun.star.sheet.XSpreadsheet xSheet =
(unoidl.com.sun.star.sheet.XSpreadsheet)
xSheetsIA.getByIndex(0).Value;
// create a hyperlink
unoidl.com.sun.star.lang.XMultiServiceFactory xServiceMan =
(unoidl.com.sun.star.lang.XMultiServiceFactory)mxDocument;
Object aHyperlinkObj =
xServiceMan.createInstance("com.sun.star.text.TextField.URL");
unoidl.com.sun.star.beans.XPropertySet xPropSet =
(unoidl.com.sun.star.beans.XPropertySet)aHyperlinkObj;
xPropSet.setPropertyValue(
"URL", new uno.Any("http://www.example.org"));
xPropSet.setPropertyValue(
"Representation", new uno.Any("hyperlink"));
// ... and insert
unoidl.com.sun.star.text.XTextContent xContent =
(unoidl.com.sun.star.text.XTextContent)aHyperlinkObj;
unoidl.com.sun.star.table.XCell Ń…Cell = xSheet.getCellByPosition(0, 0);
unoidl.com.sun.star.text.XText xText =
(unoidl.com.sun.star.text.XText)xCell;
unoidl.com.sun.star.text.XTextCursor xTextCursor =
xText.createTextCursor();
xText.insertTextContent(xTextCursor, xContent, false); // it's OK
}
xComponent.dispose();
}
catch (System.Exception e)
{
string message = String.Format("Error.\n{0}\n{1}",
e.Message, e.StackTrace.TrimStart());
Debug.WriteLine(message);
}
}
Inserting a hyperlink into an OO Calc document in this code works, but on the insert statement of a hyperlink into an OO Writer document throws an exception.
In Writer, hyperlinks are not fields, but simply a property of characters.
Basic code:
xCursor.setString("hyperlink")
xCursor.goLeft(9, False)
xCursor.goRight(9, True)
xCursor.HyperLinkURL = "http://www.example.org"
C# CLI code:
xCursor.setString("hyperlink");
xCursor.goLeft(9, false);
xCursor.goRight(9, true);
unoidl.com.sun.star.beans.XPropertySet xPropSet =
(unoidl.com.sun.star.beans.XPropertySet)xCursor;
xPropSet.setPropertyValue("HyperLinkURL", new uno.Any("http://www.example.org"));
I want to update a specific text layer of psd file (always the same (find with his name)) in C#.
I searched and tested a lot of libraries which didn't working.
Recently, I found this library on GitHub : https://github.com/bizzehdee/System.Drawing.PSD
I downloaded sources, try it and in C#, I can access to my specifid layer, but, I can't update it.
In Layer class, there are differents attributs but I don't control them.
I wan't to know if there is anybody who can test it and help me to understand the library.
I asked the author but his last action is in last year...
I hope you can help me !
Thank you very much.
You can try Aspose.PSD. It supports simple text layer editing and editing text layer by portions: https://docs.aspose.com/display/psdnet/Working+With+Text+Layers
// Load a PSD file as an image and cast it into PsdImage
using (PsdImage psdImage = (PsdImage)Image.Load(dataDir + "layers.psd"))
{
foreach (var layer in psdImage.Layers)
{
if (layer is TextLayer)
{
TextLayer textLayer = layer as TextLayer;
textLayer.UpdateText("test update", new Point(0, 0), 15.0f, Color.Purple);
}
}
psdImage.Save(dataDir + "UpdateTextLayerInPSDFile_out.psd");
}
Example with Text Portions:
string sourceFile = dataDir + "text212.psd";
string outputFile = dataDir + "Output_text212.psd";
using (var img = (PsdImage)Image.Load(sourceFile))
{
TextLayer textLayer = (TextLayer)img.Layers[1];
IText textData = textLayer.TextData;
ITextStyle defaultStyle = textData.ProducePortion().Style;
ITextParagraph defaultParagraph = textData.ProducePortion().Paragraph;
defaultStyle.FillColor = Color.DimGray;
defaultStyle.FontSize = 51;
textData.Items[1].Style.Strikethrough = true;
ITextPortion[] newPortions = textData.ProducePortions(new string[]
{
"E=mc", "2\r", "Bold", "Italic\r",
"Lowercasetext"
},
defaultStyle,
defaultParagraph);
newPortions[0].Style.Underline = true; // edit text style "E=mc"
newPortions[1].Style.FontBaseline = FontBaseline.Superscript; // edit text style "2\r"
newPortions[2].Style.FauxBold = true; // edit text style "Bold"
newPortions[3].Style.FauxItalic = true; // edit text style "Italic\r"
newPortions[3].Style.BaselineShift = -25; // edit text style "Italic\r"
newPortions[4].Style.FontCaps = FontCaps.SmallCaps; // edit text style "Lowercasetext"
foreach (var newPortion in newPortions)
{
textData.AddPortion(newPortion);
}
textData.UpdateLayerData();
img.Save(outputFile);
}
I dont use Aspose because it's not free for use.
All you need is AdobeStandard.COM-component.
Photoshop.Application app = new Photoshop.Application();
Photoshop.Document doc = app.Open(#"test.psd");
for(int i = 1; i <= doc.ArtLayers.Count; i++)
{
string name = doc.ArtLayers[i].Name;
if (name.Equals("Title1"))
{
doc.ArtLayers[i].TextItem.Contents = "Hello World";
}
}
My Requirement: Apply fillers via c# coding(Not Design) ie, filterer salaries greater than 7000.
I have a class library and a web form in my project.
I am creating the report on class library and display report by using web form.
When I run my application it shows always the unfiltered data.
What i do to get Filtered data in Viewer.
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Telerik.Reporting.Filter f1 = new Telerik.Reporting.Filter();
f1.Expression = "= Fields.Salary";
f1.Operator = Telerik.Reporting.FilterOperator.GreaterOrEqual;
f1.Value = "=7000";
EmpReport objEmpReport = new EmpReport(); objEmpReport.Filters.Add(f1);
TypeReportSource rptSource = new TypeReportSource(); rptSource.TypeName = typeof(EmpReport).AssemblyQualifiedName; this.ReportViewer1.ReportSource = rptSource;
}
}
working code:
// ...
using Telerik.Reporting;
using Telerik.Reporting.Processing;
// ...
void ExportToPDF(string reportToExport)
{
// all my reports are in trdx format - detect file type and use unpackage below for trdp files.
string currPath = HttpRuntime.AppDomainAppPath; // get the full path so deserialise works
reportToExport = currPath + #"Reports\" + reportToExport; // add folder and report name to path
UriReportSource uriReportSource = new UriReportSource { Uri = reportToExport }; // compressed to 1 line for brevity
Telerik.Reporting.Report myReport = DeserializeReport(uriReportSource); // extract report from xml format (trdx)
// Filters are client side (use params for server side) Here we work with the report object.
// set meaningful field name and values for your code, maybe even pass in as params to this function...
myReport.Filters.Add("UserId", FilterOperator.Equal , "1231");
var instanceReportSource = new Telerik.Reporting.InstanceReportSource(); // report source
instanceReportSource.ReportDocument = myReport; // Assigning Report object to the InstanceReportSource
// kinda optional, lots of examples just used null instead for deviceInfo
System.Collections.Hashtable deviceInfo = new System.Collections.Hashtable(); // set any deviceInfo settings if necessary
ReportProcessor reportProcessor = new ReportProcessor(); // will do work
RenderingResult result = reportProcessor.RenderReport("PDF", instanceReportSource, deviceInfo); // GO!
if (!result.HasErrors)
{
this.Response.Clear();
this.Response.ContentType = result.MimeType;
this.Response.Cache.SetCacheability(HttpCacheability.Private);
this.Response.Expires = -1;
this.Response.Buffer = true;
this.Response.BinaryWrite(result.DocumentBytes);
this.Response.End();
}
else
{
Exception[] ex = result.Errors;
throw new Exception(ex[0].Message);
}
}
Telerik.Reporting.Report DeserializeReport(UriReportSource uriReportSource)
{
var settings = new System.Xml.XmlReaderSettings();
settings.IgnoreWhitespace = true;
using (var xmlReader = System.Xml.XmlReader.Create(uriReportSource.Uri, settings))
{
var xmlSerializer = new Telerik.Reporting.XmlSerialization.ReportXmlSerializer();
var report = (Telerik.Reporting.Report)xmlSerializer.Deserialize(xmlReader);
return report;
}
}
Telerik.Reporting.Report UnpackageReport(UriReportSource uriReportSource)
{
var reportPackager = new ReportPackager();
using (var sourceStream = System.IO.File.OpenRead(uriReportSource.Uri))
{
var report = (Telerik.Reporting.Report)reportPackager.UnpackageDocument(sourceStream);
return report;
}
}
I am trying to fill a word document with data from an XML. I am using openXML to fill the document, which works great and save it as .docx. The thing is I have to open Word and save the document as an .odt and then use the OpenOffice SDK to open the .docx and save it as a pdf. When I don't save the .docx as .odt, the formatting is off.
What I need to be able to do is be able to either convert the .docx to .odt or save it originally as .odt.
Here is what I have right now:
static void Main()
{
string documentText;
XmlDocument xmlDoc = new XmlDocument(); // Create an XML document object
xmlDoc.Load("C:\\Cache\\MMcache.xml"); // Load the XML document from the specified file
XmlNodeList PatientFirst = xmlDoc.GetElementsByTagName("PatientFirst");
XmlNodeList PatientSignatureImg = xmlDoc.GetElementsByTagName("PatientSignatureImg");
byte[] byteArray = File.ReadAllBytes("C:\\Cache\\TransportationRunReporttemplate.docx");
using (MemoryStream stream = new MemoryStream())
{
stream.Write(byteArray, 0, (int)byteArray.Length);
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(stream, true))
{
using (StreamReader reader = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
documentText = reader.ReadToEnd();
}
using (StreamWriter writer = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
{
writer.Write(documentText);
}
}
// Save the file with the new name
File.WriteAllBytes("C:\\Cache\\MYFINISHEDTEMPLATE.docx", stream.ToArray());
}
}
private static void AddPicture(Bitmap bitmap)
{
using (WordprocessingDocument doc = WordprocessingDocument.Open("C:\\Cache\\MYFINISHEDTEMPLATE.docx", true))
{
//Bitmap image = new Bitmap("C:\\Cache\\scribus.jpg");
SdtElement controlBlock = doc.MainDocumentPart.Document.Body
.Descendants<SdtElement>()
.Where
(r =>
r.SdtProperties.GetFirstChild<Tag>().Val == "Signature"
).SingleOrDefault();
// Find the Blip element of the content control.
A.Blip blip = controlBlock.Descendants<A.Blip>().FirstOrDefault();
ImagePart imagePart = doc.MainDocumentPart
.AddImagePart(ImagePartType.Jpeg);
using (MemoryStream stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Jpeg);
stream.Position = 0;
imagePart.FeedData(stream);
}
blip.Embed = doc.MainDocumentPart.GetIdOfPart(imagePart);
/* DW.Inline inline = controlBlock
.Descendants<DW.Inline>().FirstOrDefault();
// 9525 = pixels to points
inline.Extent.Cy = image.Size.Height * 9525;
inline.Extent.Cx = image.Size.Width * 9525;
PIC.Picture pic = inline
.Descendants<PIC.Picture>().FirstOrDefault();
pic.ShapeProperties.Transform2D.Extents.Cy
= image.Size.Height * 9525;
pic.ShapeProperties.Transform2D.Extents.Cx
= image.Size.Width * 9525;*/
}
ConvertToPDF(#"C:\Cache\MYFINISHEDTEMPLATE2.docx",#"C:\Cache\OpenPdf.pdf");
}
public static Bitmap Base64StringToBitmap(string base64String)
{
Bitmap bmpReturn = null;
byte[] byteBuffer = Convert.FromBase64String(base64String);
MemoryStream memoryStream = new MemoryStream(byteBuffer);
memoryStream.Position = 0;
bmpReturn = (Bitmap)Bitmap.FromStream(memoryStream);
memoryStream.Close();
memoryStream = null;
byteBuffer = null;
return bmpReturn;
}
public static void ConvertToPDF(string inputFile, string outputFile)
{
if (ConvertExtensionToFilterType(System.IO.Path.GetExtension(inputFile)) == null)
throw new InvalidProgramException("Unknown file type for OpenOffice. File = " + inputFile);
StartOpenOffice();
//Get a ComponentContext
var xLocalContext =
Bootstrap.bootstrap();
//Get MultiServiceFactory
var xRemoteFactory =
(XMultiServiceFactory)
xLocalContext.getServiceManager();
//Get a CompontLoader
var aLoader =
(XComponentLoader)xRemoteFactory.createInstance("com.sun.star.frame.Desktop");
//Load the sourcefile
XComponent xComponent = null;
try
{
xComponent = InitDocument(aLoader,
PathConverter(inputFile), "_blank");
//Wait for loading
while (xComponent == null)
{
Thread.Sleep(1000);
}
// save/export the document
SaveDocument(xComponent, inputFile, PathConverter(outputFile));
}
finally
{
if (xComponent != null) xComponent.dispose();
}
}
private static void StartOpenOffice()
{
var ps = Process.GetProcessesByName("soffice.exe");
if (ps.Length != 0)
throw new InvalidProgramException("OpenOffice not found. Is OpenOffice installed?");
if (ps.Length > 0)
return;
var p = new Process
{
StartInfo =
{
Arguments = "-headless -nofirststartwizard",
FileName = "soffice.exe",
CreateNoWindow = true
}
};
var result = p.Start();
if (result == false)
throw new InvalidProgramException("OpenOffice failed to start.");
}
private static XComponent InitDocument(XComponentLoader aLoader, string file, string target)
{
var openProps = new PropertyValue[1];
openProps[0] = new PropertyValue { Name = "Hidden", Value = new Any(true) };
XComponent xComponent = aLoader.loadComponentFromURL(
file, target, 0,
openProps);
return xComponent;
}
private static void SaveDocument(XComponent xComponent, string sourceFile, string destinationFile)
{
var propertyValues = new PropertyValue[2];
// Setting the flag for overwriting
propertyValues[1] = new PropertyValue { Name = "Overwrite", Value = new Any(true) };
//// Setting the filter name
propertyValues[0] = new PropertyValue
{
Name = "FilterName",
Value = new Any(ConvertExtensionToFilterType(System.IO.Path.GetExtension(sourceFile)))
};
((XStorable)xComponent).storeToURL(destinationFile, propertyValues);
}
private static string PathConverter(string file)
{
if (file == null || file.Length == 0)
throw new NullReferenceException("Null or empty path passed to OpenOffice");
return String.Format("file:///{0}", file.Replace(#"\", "/"));
}
public static string ConvertExtensionToFilterType(string extension)
{
switch (extension)
{
case ".odt":
case ".doc":
case ".docx":
case ".txt":
case ".rtf":
case ".html":
case ".htm":
case ".xml":
case ".wps":
case ".wpd":
return "writer_pdf_Export";
case ".xls":
case ".xlsb":
case ".ods":
return "calc_pdf_Export";
case ".ppt":
case ".pptx":
case ".odp":
return "impress_pdf_Export";
default: return null;
}
}
}
}
Just for information I cannot use anything that uses Interop because word will not be installed the machine. I am using OpenXML and OpenOffice
This is what I would try (details below):
1) try Doc format instead of DocX
2) switch to Libre Office and try DocX again
2) use the odf-converter to get a better DocX -> ODT conversion.
More details...
There's something called the odf-conveter (opensource) that can convert DocX->ODT which gives you (typically) more accurate DocX->ODT than Open Office. Take a look at odf-conveter-integrator by OONinja for pre-packaged versions.
Also, Libre Office has DocX support ahead of OpenOffice so you might get a better result simply by switching to Libre Office.
A further option is to start from Doc format rather than DocX. In the OpenOffice world that translates much better to ODT and then to PDF.
Hope that helps.
You may try to use Docxpresso to generate your .odt directly from HTML + CSS code and avoid any conversion issue.
Docxpresso is free for non-commercial use.
I have powerponint 97-2003 files(.ppt extension) and I need to extract slide titles programatically using C#.
I have tried using Microsoft.Office.Interop but without success.
I have search with google and as a maximum I have found how to obtain reference to PowerPoint.Slide:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Core;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
namespace Tester
{
class Program
{
static void Main(string[] args)
{
Microsoft.Office.Interop.PowerPoint.Application presentationApp = new Microsoft.Office.Interop.PowerPoint.Application();
try
{
string pptPath = #"D:\somefile.ppt";
TestReadingTitles(presentationApp, pptPath);
}
finally
{
presentationApp.Quit();
}
}
private static void TestReadingTitles(Microsoft.Office.Interop.PowerPoint.Application presentationApp, string pptPath)
{
presentationApp.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
Microsoft.Office.Interop.PowerPoint.Presentations presentations = presentationApp.Presentations;
Microsoft.Office.Core.MsoTriState readOnly = Microsoft.Office.Core.MsoTriState.msoTrue;
Microsoft.Office.Core.MsoTriState untitled = Microsoft.Office.Core.MsoTriState.msoTrue;
Microsoft.Office.Core.MsoTriState withWindow = Microsoft.Office.Core.MsoTriState.msoFalse;
Microsoft.Office.Interop.PowerPoint.Presentation presentation = presentations.Open(pptPath, readOnly, untitled, withWindow);
for (int i = 0; i < presentation.Slides.Count; i++)
{
foreach (PowerPoint.Slide slide in presentation.Slides)
{
string slidetitle = ??????????????????;
}
}
}
}
}
You can extract the titles without looping through the shapes.
private static string ExtractSlideTitlefromSlide(Microsoft.Office.Interop.PowerPoint.Slide slide, string defaultValue)
{
if (slide.Shapes.HasTitle == Office.MsoTriState.msoTrue)
{
if (slide.Shapes.Title.TextFrame.HasText == Office.MsoTriState.msoTrue)
{
return slide.Shapes.Title.TextFrame.TextRange.Text;
}
}
return defaultValue;
}
I have no solution for direct extract slide titles from ppt. This is a workarround - first temproaly convert it into pptx and then extract titles using openxml.
For conversion from ppt to pptx I have used Microsoft Interop which I do not like but I have no better solution.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Presentation;
using D = DocumentFormat.OpenXml.Drawing;
using Shape = DocumentFormat.OpenXml.Presentation.Shape;
namespace Tester
{
class Program
{
static void Main(string[] args)
{
string pptPath = #"D:\mypresentation.ppt";
ReadTitles(pptPath);
}
private static void ReadTitles(string pptPath)
{
IList<string> slideTitles = GetSlidesTitles(pptPath);
Debug.Print("SLIDES TITLES FOR {0}:", pptPath);
foreach (string slideTitle in slideTitles)
{
Debug.Print("\t {0}", slideTitle);
}
}
private static IList<string> GetSlidesTitles(string pptPath)
{
string pptxPath = SaveAsPptx(pptPath);
IList<string> titles = GetSlideTitles(pptxPath);
try
{
File.Delete(pptxPath);
Debug.Print("Temporary pptx file {0} deleted.", pptxPath);
}
catch (Exception e)
{
Debug.Print("Error deleting file {0}. ERROR: {1}", pptxPath, e.Message);
}
return titles;
}
private static string SaveAsPptx(string pptPathIn)
{
Microsoft.Office.Interop.PowerPoint.Application presentationApp = new Microsoft.Office.Interop.PowerPoint.Application();
string pptxPathOut = null;
try
{
string pptDir = Path.GetDirectoryName(pptPathIn);
string pptFileNameOnly = Path.GetFileNameWithoutExtension(pptPathIn);
pptxPathOut = Path.Combine(pptDir, pptFileNameOnly + ".pptx");
presentationApp.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
Microsoft.Office.Interop.PowerPoint.Presentations presentations = presentationApp.Presentations;
Microsoft.Office.Core.MsoTriState readOnly = Microsoft.Office.Core.MsoTriState.msoFalse;
Microsoft.Office.Core.MsoTriState untitled = Microsoft.Office.Core.MsoTriState.msoFalse;
Microsoft.Office.Core.MsoTriState withWindow = Microsoft.Office.Core.MsoTriState.msoFalse;
Debug.Print("Opening ppt file {0} ...", pptPathIn);
Microsoft.Office.Interop.PowerPoint.Presentation presentation = presentations.Open(pptPathIn, readOnly, untitled, withWindow);
Debug.Print("Starting creation of pptx from ppt {0}", pptPathIn);
presentation.SaveCopyAs(pptxPathOut, PowerPoint.PpSaveAsFileType.ppSaveAsOpenXMLPresentation, Microsoft.Office.Core.MsoTriState.msoFalse);
Debug.Print("Successfully created pptx {0} from ppt {1}", pptxPathOut, pptPathIn);
}
catch (Exception e)
{
Debug.Print("Error during creating pptx from ppt " + pptPathIn, e);
}
finally
{
presentationApp.Quit();
}
return pptxPathOut;
}
// Get a list of the titles of all the slides in the presentation.
public static IList<string> GetSlideTitles(string presentationFile)
{
// Open the presentation as read-only.
using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, false))
{
return GetSlideTitles(presentationDocument);
}
}
// Get a list of the titles of all the slides in the presentation.
public static IList<string> GetSlideTitles(PresentationDocument presentationDocument)
{
if (presentationDocument == null)
{
throw new ArgumentNullException("presentationDocument");
}
// Get a PresentationPart object from the PresentationDocument object.
PresentationPart presentationPart = presentationDocument.PresentationPart;
if (presentationPart != null &&
presentationPart.Presentation != null)
{
// Get a Presentation object from the PresentationPart object.
Presentation presentation = presentationPart.Presentation;
if (presentation.SlideIdList != null)
{
List<string> titlesList = new List<string>();
// Get the title of each slide in the slide order.
foreach (var slideId in presentation.SlideIdList.Elements<SlideId>())
{
SlidePart slidePart = presentationPart.GetPartById(slideId.RelationshipId) as SlidePart;
// Get the slide title.
string title = GetSlideTitle(slidePart);
// An empty title can also be added.
titlesList.Add(title);
}
return titlesList;
}
}
return null;
}
// Get the title string of the slide.
public static string GetSlideTitle(SlidePart slidePart)
{
if (slidePart == null)
{
throw new ArgumentNullException("slidePart");
}
// Declare a paragraph separator.
string paragraphSeparator = null;
if (slidePart.Slide != null)
{
// Find all the title shapes.
var shapes = from shape in slidePart.Slide.Descendants<Shape>()
where IsTitleShape(shape)
select shape;
StringBuilder paragraphText = new StringBuilder();
foreach (var shape in shapes)
{
// Get the text in each paragraph in this shape.
foreach (var paragraph in shape.TextBody.Descendants<D.Paragraph>())
{
// Add a line break.
paragraphText.Append(paragraphSeparator);
foreach (var text in paragraph.Descendants<D.Text>())
{
paragraphText.Append(text.Text);
}
paragraphSeparator = "\n";
}
}
return paragraphText.ToString();
}
return string.Empty;
}
// Determines whether the shape is a title shape.
private static bool IsTitleShape(Shape shape)
{
var placeholderShape = shape.NonVisualShapeProperties.ApplicationNonVisualDrawingProperties.GetFirstChild<PlaceholderShape>();
if (placeholderShape != null && placeholderShape.Type != null && placeholderShape.Type.HasValue)
{
switch ((PlaceholderValues)placeholderShape.Type)
{
// Any title shape.
case PlaceholderValues.Title:
// A centered title.
case PlaceholderValues.CenteredTitle:
return true;
default:
return false;
}
}
return false;
}
}
}
Finally I have found a way to get out powerpoint presentation titles from .ppt file without converting it to .pptx. Here is a solution:
using System;
using System.Collections.Generic;
using Microsoft.Office.Core;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
namespace Mintra.Publisher.DocumentConverter.Core.Utils
{
class InteropUtility
{
public static IList<string> GetPresentationTitles(string pptPath)
{
IList<string> result = new List<string>();
var presentationApp = new Microsoft.Office.Interop.PowerPoint.Application();
try
{
presentationApp.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
Microsoft.Office.Interop.PowerPoint.Presentations presentations = presentationApp.Presentations;
var readOnly = Microsoft.Office.Core.MsoTriState.msoTrue;
var untitled = Microsoft.Office.Core.MsoTriState.msoTrue;
var withWindow = Microsoft.Office.Core.MsoTriState.msoFalse;
Microsoft.Office.Interop.PowerPoint.Presentation presentation = presentations.Open(pptPath, readOnly, untitled, withWindow);
int i = 0;
foreach (PowerPoint.Slide slide in presentation.Slides)
{
string defaultTitle = String.Format("Slide {0}", i);
String shapeTitle = ExtractSlideTitlefromShape(slide, defaultTitle);
result.Add(shapeTitle);
}
}
finally
{
presentationApp.Quit();
}
return result;
}
private static string ExtractSlideTitlefromShape(PowerPoint.Slide slide, string defaultValue)
{
PowerPoint.HeadersFooters headersFooters = slide.HeadersFooters;
PowerPoint.Shapes mastershapes = slide.Master.Shapes;
for (int i = 1; i <= slide.Shapes.Count; i++)
{
PowerPoint.Shape shape = slide.Shapes[i];
bool hasTextFrame = shape.HasTextFrame == MsoTriState.msoTrue;
bool isTypePlaceholder = shape.Type.Equals(MsoShapeType.msoPlaceholder);
bool hasTextInTextFrame = shape.TextFrame.HasText == MsoTriState.msoTrue;
bool isTitleShape = shape.Name.ToLower().Contains("title");
if (isTypePlaceholder && hasTextFrame && hasTextInTextFrame && isTitleShape)
{
return shape.TextFrame.TextRange.Text;
}
}
return defaultValue;
}
}
}
Microsoft.Office.Interop.PowerPoint.Application pptApplication = new Microsoft.Office.Interop.PowerPoint.Application();
Microsoft.Office.Interop.PowerPoint.Slides slides;
Microsoft.Office.Interop.PowerPoint._Slide slide;
// Create the Presentation File
Presentation pptPresentation = pptApplication.Presentations.Add(MsoTriState.msoTrue);
for (int i = 0; i < 2; i++)
{
Microsoft.Office.Interop.PowerPoint.CustomLayout customLayout = pptPresentation.SlideMaster.CustomLayouts[Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutChartAndText];
// customLayout.t
// Create new Slide
slides = pptPresentation.Slides;
slide = slides.AddSlide(1, customLayout);
slide.Shapes.Title.Top = 0;
slide.Shapes.Title.TextFrame.TextRange.Text = "Welcome!";
All you need is change Welcome text.