/// <summary> /// 获取所有文本 /// </summary> /// <param name="pdoc">ppt对象</param> /// <returns></returns> private static List <string> GetSlideIdAndText(PresentationDocument pdoc) { IEnumerable <SlidePart> slideParts = pdoc.PresentationPart.SlideParts; List <string> result = new List <string>(); for (int i = 0; i < slideParts.Count(); i++) { PresentationPart part = pdoc.PresentationPart; OpenXmlElementList slideIds = part.Presentation.SlideIdList.ChildElements; string relId = (slideIds[i] as SlideId).RelationshipId; // 取得幻灯片的关系ID SlidePart slide = (SlidePart)part.GetPartById(relId); StringBuilder paragraphText = new StringBuilder(); // 得到幻灯片的文本内容 IEnumerable <D.Text> texts = slide.Slide.Descendants <D.Text>(); foreach (D.Text text in texts) { paragraphText.Append(text.Text + "\t"); } result.Add(paragraphText.ToString()); } return(result); }
/// <summary> /// ファイル名とスライド番号に対応するテキストをすべて取得して結合して返却する。 /// </summary> /// <param name="sldText">スライドに設定されたString</param> /// <param name="docName">ファイル名</param> /// <param name="index">スライド番号</param> public static void GetSlideIdAndText(out string sldText, string docName, int index) { using (PresentationDocument ppt = PresentationDocument.Open(docName, false)) { // Get the relationship ID of the first slide. PresentationPart part = ppt.PresentationPart; OpenXmlElementList slideIds = part.Presentation.SlideIdList.ChildElements; // スライド番号から、.NETで扱うためのスライドIDを取得する。 string relId = (slideIds[index] as SlideId).RelationshipId; // Get the slide part from the relationship ID. SlidePart slide = (SlidePart)part.GetPartById(relId); // Build a StringBuilder object. StringBuilder paragraphText = new StringBuilder(); // Get the inner text of the slide: // slide.Slide(current element's)がもつ DocumentFormat.OpenXml.Drawing.Text型のXML上の要素をすべて取得する。 IEnumerable <A.Text> texts = slide.Slide.Descendants <A.Text>(); foreach (A.Text text in texts) { paragraphText.Append(text.Text).Append(" "); Console.WriteLine("-------------------------------------"); Console.WriteLine("Parent:" + text.LocalName); Console.WriteLine("Parent:" + text.Parent.ToString()); } sldText = paragraphText.ToString(); } }
public int FindElementEndIndex(OpenXmlElementList source, int startIndex, List <string> styleBreakerList, int dashIndex) { int returnValue = -1; for (int i = startIndex; i <= dashIndex; i++) { styleBreakerList.ForEach(x => { if (this.Validator.IsCurrentSomething(source, i, x)) { returnValue = i - 1; return; } }); if (returnValue == -1 && this.Validator.IsCurrentSomething(source, i, CRTA)) { return(i - 1); } if (returnValue != -1) { return(returnValue); } } if (returnValue == -1) { throw new InvalidDataException("PARSER_FIND_ELEMENT_END_INDEX: Napaka formata dokumenta!"); } return(returnValue); }
/// <summary> /// Reading file raw data from file byte data. /// </summary> /// <param name="data">File resources as byte arrays.</param> /// <returns>An array of objects containing raw data.</returns> public TempData[] ReadFileRawDataFromByteArray(byte[] data) { try { using (PresentationDocument presentationDocument = PresentationDocument.Open(new MemoryStream(data), false)) { List <TempData> result = new List <TempData>(); PresentationPart presentationPart = presentationDocument.PresentationPart; OpenXmlElementList openXmlElementList = presentationPart.Presentation.SlideIdList.ChildElements; // Get all SlideParts. var slideParts = from item in openXmlElementList select(SlidePart) presentationPart.GetPartById((item as SlideId).RelationshipId); // Retrieve the text of each slidePart. var slideText = from item in slideParts select GetSlideText(item); result.AddRange(TempData.GetTempDataIEnumerable(StorageType.TextType, slideText)); // Find image and add to the result. // Insert code here! return(result.ToArray()); } } catch (Exception ex) { throw ex; } }
// Replace text in PPT slide private void ReplaceTextMatchingAltText(PresentationDocument presentationDocument, string relationshipId) { OpenXmlElementList slideIds = presentationDocument.PresentationPart.Presentation.SlideIdList.ChildElements; foreach (SlideId sID in slideIds) // loop thru the SlideIDList { string relId = sID.RelationshipId; // get first slide relationship if (relationshipId == relId) { SlidePart slide = (SlidePart)presentationDocument.PresentationPart.GetPartById(relId); // Get the slide part from the relationship ID. P.ShapeTree tree = slide.Slide.CommonSlideData.ShapeTree; foreach (P.Shape shape in tree.Elements <P.Shape>()) { // Run through all the paragraphs in the document foreach (A.Paragraph paragraph in shape.Descendants().OfType <A.Paragraph>()) { foreach (A.Run run in paragraph.Elements <A.Run>()) { if (run.Text.InnerText.Contains("Name")) { run.Text = new A.Text("Your new text"); } } } } } } }
/// <summary> /// Получает содержимое ячейки в зависимости от типа данных /// </summary> private static object GetCellValue(OpenXmlElementList cellFrm, SharedStringItem[] sharedItems, CellType cell) { if (cell.DataType == null) { return(GetCellValNoDataType(cellFrm, cell)); } // в зависимости от типа ячейки switch (cell.DataType.Value) { case CellValues.String: return(cell.CellValue?.Text?.Trim()); case CellValues.InlineString: return(cell.InlineString?.Text?.Text?.Trim()); case CellValues.SharedString: return(GetCellValSharedString(sharedItems, cell)); case CellValues.Boolean: case CellValues.Number: case CellValues.Date: case CellValues.Error: return(cell.InnerText?.Trim()); default: return(cell.InnerText?.Trim()); } }
/// <summary> /// если dataType не указан, возвращаем значение cell.innerText /// </summary> private static object GetCellValNoDataType(OpenXmlElementList cellFrm, CellType cell) { if (cell.CellValue == null) { return(cell.InnerText); } if (cell.StyleIndex == null) { return(cell.CellValue); } var cf = cellFrm[int.Parse(cell.StyleIndex.InnerText)] as CellFormat; if (cf != null) { if (cf.NumberFormatId == 177) //--- MM/YYYY { return(DateTime.FromOADate(Convert.ToDouble(cell.CellValue.Text))); } if (cf.NumberFormatId < 14 || cf.NumberFormatId > 22) { return(GetCellValue(cell.CellValue)); } } var date = DateTime.Parse("1900-01-01") .AddDays(double.Parse(cell.CellValue.Text.Replace(".", ",")) - 2); return((date.Day < 10 ? ("0" + date.Day) : date.Day.ToString()) + "." + (date.Month < 10 ? ("0" + date.Month) : date.Month.ToString()) + "." + date.Year); }
public static bool ReadFileCompateText(string path, string s) { using (PresentationDocument presentationDocument = PresentationDocument.Open(path, false)) { Regex r = new Regex(s, RegexOptions.IgnoreCase); // Get the relationship ID of the first slide. PresentationPart part = presentationDocument.PresentationPart; OpenXmlElementList slideIds = part.Presentation.SlideIdList.ChildElements; for (int i = 0; i < slideIds.Count; i++) { string relId = (slideIds[i] as SlideId).RelationshipId; // Get the slide part from the relationship ID. SlidePart slide = (SlidePart)part.GetPartById(relId); // Get the inner text of the slide: IEnumerable <A.Text> texts = slide.Slide.Descendants <A.Text>(); foreach (A.Text text in texts) { Match m = r.Match(text.InnerText); if (m.Success) { presentationDocument.Close(); return(true); } } } presentationDocument.Close(); } return(false); }
public Dictionary <int, string> FindMany(OpenXmlElementList source, string id, int dashIndex = -1) { if (dashIndex == -1) { dashIndex = source.Count; } var result = source .Select((x, i) => new { Value = x, index = i }) .Where(x => x.index < dashIndex) .Where(x => (x.Value is Paragraph)) .Where(x => (x.Value as Paragraph).ParagraphProperties != null) .Where(x => (x.Value as Paragraph).ParagraphProperties.ParagraphStyleId != null) .Where(x => (x.Value as Paragraph).ParagraphProperties?.ParagraphStyleId?.Val?.Value?.ToLower() == id.ToLower()) .ToList(); Dictionary <int, string> returnDictionary = new Dictionary <int, string>(); foreach (var item in result) { returnDictionary.Add(item.index, item.Value.InnerText); } return(returnDictionary); }
public bool IsCurrentSomethingOf(OpenXmlElementList source, int currentPositionOfI, List <string> something) { something = something.ConvertAll(x => x.ToLower()); try { if (currentPositionOfI >= source.Count) { throw new Exception("Index out of range"); } if (currentPositionOfI == -1) { throw new Exception("wtf is this"); } if (!IsXmlElementValidParagraphWithValidProperties(source[currentPositionOfI])) { return(false); } var tempParagraph = source[currentPositionOfI] as Paragraph; var id = tempParagraph.ParagraphProperties.ParagraphStyleId.Val.Value.ToLower(); if (something.Contains(id)) { return(true); } return(false); } catch (Exception e) { return(false); } }
public override string Parse() { if (!File.Exists(Context.Path)) { throw new FileNotFoundException("File " + Context.Path + " is not found"); } StringBuilder sb = new StringBuilder(); using (PresentationDocument ppt = PresentationDocument.Open(Context.Path, false)) { // Get the relationship ID of the first slide. PresentationPart part = ppt.PresentationPart; OpenXmlElementList slideIds = part.Presentation.SlideIdList.ChildElements; for (int index = 0; index < slideIds.Count; index++) { string relId = (slideIds[index] as SlideId).RelationshipId; relId = (slideIds[index] as SlideId).RelationshipId; // Get the slide part from the relationship ID. SlidePart slide = (SlidePart)part.GetPartById(relId); string[] texts = GetAllTextInSlide(slide); foreach (string text in texts) { sb.AppendLine(text); } } return(sb.ToString()); } }
public void ExtractTextFromPresentation(PresentationDocument document, StringBuilder sb) { PresentationPart pPart = document.PresentationPart; int slidesCount = 0; if (pPart != null) { slidesCount = pPart.SlideParts.Count(); } if (slidesCount < 1) { return; } OpenXmlElementList slideIds = pPart.Presentation.SlideIdList.ChildElements; for (var i = 0; i < slidesCount; i++) { string relId = (slideIds[i] as SlideId).RelationshipId; SlidePart slide = (SlidePart)pPart.GetPartById(relId); IEnumerable <A.Text> texts = slide.Slide.Descendants <A.Text>(); foreach (A.Text text in texts) { sb.Append(text.Text); sb.Append(" "); } } }
public static void GetSlideIdAndText(out string sldText, string docName, int index) { using (PresentationDocument ppt = PresentationDocument.Open(docName, false)) { // Get the relationship ID of the first slide. PresentationPart part = ppt.PresentationPart; OpenXmlElementList slideIds = part.Presentation.SlideIdList.ChildElements; string relId = (slideIds[index] as SlideId).RelationshipId; // Get the slide part from the relationship ID. SlidePart slide = (SlidePart)part.GetPartById(relId); // Build a StringBuilder object. StringBuilder paragraphText = new StringBuilder(); // Get the inner text of the slide: IEnumerable <A.Text> texts = slide.Slide.Descendants <A.Text>(); foreach (A.Text text in texts) { paragraphText.Append(text.Text); } sldText = paragraphText.ToString(); } }
private void DeleteSdtBlockAndKeepContent(MainDocumentPart mainDocumentPart, string sdtBlockTag) { List <SdtBlock> sdtList = mainDocumentPart.Document.Descendants <SdtBlock>().ToList(); SdtBlock sdtA = null; foreach (SdtBlock sdt in sdtList) { if (sdt.SdtProperties.GetFirstChild <Tag>().Val.Value == sdtBlockTag) { sdtA = sdt; break; } } OpenXmlElement sdtc = sdtA.GetFirstChild <SdtContentBlock>(); OpenXmlElement parent = sdtA.Parent; OpenXmlElementList elements = sdtc.ChildElements; var mySdtc = new SdtContentBlock(sdtc.OuterXml); foreach (OpenXmlElement elem in elements) { string text = parent.FirstChild.InnerText; parent.Append((OpenXmlElement)elem.Clone()); } sdtA.Remove(); }
public static void GetSlideIdAndText(out int foundCounter, string searchString, Stream docName, int index) { using (PresentationDocument ppt = PresentationDocument.Open(docName, false)) { //Reset Counter for founded String int stringCount = 0; // Get the relationship ID of the first slide. PresentationPart part = ppt.PresentationPart; OpenXmlElementList slideIds = part.Presentation.SlideIdList.ChildElements; string relId = (slideIds[index] as SlideId).RelationshipId; // Get the slide part from the relationship ID. SlidePart slide = (SlidePart)part.GetPartById(relId); // Build a StringBuilder object. StringBuilder paragraphText = new StringBuilder(); // Get the inner text of the slide: IEnumerable <A.Text> texts = slide.Slide.Descendants <A.Text>(); foreach (A.Text text in texts) { if (text.Text.Contains(searchString) && searchString != "") { stringCount = stringCount + 1; } } foundCounter = stringCount; } }
public static void changeSlideIdAndText(string docName, int index) { using (PresentationDocument ppt = PresentationDocument.Open(docName, true)) { // Get the relationship ID of the first slide. PresentationPart part = ppt.PresentationPart; OpenXmlElementList slideIds = part.Presentation.SlideIdList.ChildElements; // スライド番号から、.NETで扱うためのスライドIDを取得する。 string relId = (slideIds[index] as SlideId).RelationshipId; // Get the slide part from the relationship ID. // スライド番号からスライドのオブジェクトを取得 SlidePart slide = (SlidePart)part.GetPartById(relId); // Get the inner text of the slide: // slide.Slide(current element's)がもつ DocumentFormat.OpenXml.Drawing.Text型のXML上の要素をすべて取得する。 IEnumerable <A.Text> texts = slide.Slide.Descendants <A.Text>(); foreach (A.Text text in texts) { text.Text = text.Text + " Chage"; Console.WriteLine("-------------------------------------"); Console.WriteLine("Change後テキスト:" + text.Text); } } }
public Dictionary <int, string> FindManyBetween(OpenXmlElementList source, List <string> idList, int lowerLimit, int upperLimit, int dashIndex = -1) { if (dashIndex == -1) { dashIndex = source.Count; } idList = idList.ConvertAll(d => d.ToLower()); var result = source .Select((x, i) => new { Value = x, index = i }) .Where(x => x.index < dashIndex) .Where(x => (x.Value is Paragraph)) .Where(x => (x.Value as Paragraph).ParagraphProperties != null) .Where(x => (x.Value as Paragraph).ParagraphProperties.ParagraphStyleId != null) .Where(x => idList.Contains((x.Value as Paragraph).ParagraphProperties.ParagraphStyleId.Val.Value.ToLower())) .Where(x => x.index >= lowerLimit) .Where(x => x.index <= upperLimit) .ToList(); Dictionary <int, string> returnDictionary = new Dictionary <int, string>(); foreach (var item in result) { returnDictionary.Add(item.index, item.Value.InnerText); } return(returnDictionary); }
public static string GetSlideIdAndText(string docName, int index) { StringBuilder paragraphText = new StringBuilder(); using (PresentationDocument ppt = PresentationDocument.Open(docName, false)) { // Get the relationship ID of the first slide. PresentationPart part = ppt.PresentationPart; OpenXmlElementList slideIds = part.Presentation.SlideIdList.ChildElements; string relId = (slideIds[index] as SlideId).RelationshipId; // Get the slide part from the relationship ID. SlidePart slide = (SlidePart)part.GetPartById(relId); // Get the inner text of the slide IEnumerable <A.Text> texts = slide.Slide.Descendants <A.Text>(); foreach (A.Text text in texts) { paragraphText.Append(text.Text); } // Get any notes from the slide if (slide.NotesSlidePart != null) { paragraphText.Append(slide.NotesSlidePart.NotesSlide.InnerText); } } return(paragraphText.ToString()); }
public static OpenXmlElement GetElementSafe(this OpenXmlElementList collection, int index) { if (index >= collection.Count) { return(null); } return(collection[index]); }
public int CountSlide() { using (PresentationDocument ppt = PresentationDocument.Open(HttpContext.Current.Server.MapPath(folder), true)) { PresentationPart part = ppt.PresentationPart; OpenXmlElementList slideIds = part.Presentation.SlideIdList.ChildElements; ppt.Close(); return(slideIds.Count()); } }
private List <OpenXmlElement> GetChildShapesByPlaceholderpattern(OpenXmlElementList list) { List <OpenXmlElement> found = new List <OpenXmlElement>(); foreach (var element in list) { found.AddRange(FindShapesIncludingElement(element)); } return(found); }
public List <string> GetAllDocumentStyles(OpenXmlElementList source, int dashIndex) { List <string> styles = new List <string>(); for (int i = 0; i < dashIndex; i++) { string style = GetParagraphStyle(source, i); } return(styles); }
public string GetParagraphStyle(OpenXmlElementList source, int currentPositionOfI) { if (!Validator.IsXmlElementValidParagraphWithValidProperties(source[currentPositionOfI])) { return(""); } var tempParagraph = source[currentPositionOfI] as Paragraph; return(tempParagraph.ParagraphProperties.ParagraphStyleId.Val.Value.ToLower()); }
public int FindStartIndexOfNextSection(OpenXmlElementList source, int startIndex, int dashIndex) { for (int i = startIndex; i < dashIndex; i++) { if (this.Validator.IsCurrentSomething(source, i, CLEN_NASLOV) || this.Validator.IsCurrentSomething(source, i, ODSTAVEK_NASLOV) || this.Validator.IsCurrentSomething(source, i, ALINEJA_NASLOV) || this.Validator.IsCurrentSomething(source, i, CRTA)) { return(i); } } return(dashIndex); }
/// <summary> /// Gets a <see cref="SlidePart"/> instance by slide index. /// </summary> /// <param name="prePart"></param> /// <param name="sldIndex"></param> /// <returns></returns> public static SlidePart GetSlidePartByIndex(this PresentationPart prePart, int sldIndex) { // Get the collection of slide IDs OpenXmlElementList slideIds = prePart.Presentation.SlideIdList.ChildElements; string relId = ((SlideId)slideIds[sldIndex]).RelationshipId; // Get the specified slide part from the relationship ID SlidePart slidePart = (SlidePart)prePart.GetPartById(relId); return(slidePart); }
internal static string GetSlideText(PresentationDocument ppt, int idx) { // Get the relationship ID of the first slide. PresentationPart part = ppt.PresentationPart; OpenXmlElementList slideIds = part.Presentation.SlideIdList.ChildElements; string relId = (slideIds[idx] as SlideId).RelationshipId; // Get the slide part from the relationship ID. SlidePart slidePart = (SlidePart)part.GetPartById(relId); StringBuilder sb = new StringBuilder(); var paragraphs = slidePart.Slide.Descendants <Paragraph>(); foreach (Paragraph paragraph in paragraphs) { var elements = paragraph.Descendants(); foreach (OpenXmlElement element in elements) { if (element is Break) { sb.Append(Environment.NewLine); } else if (element is Text text) { sb.Append(text.Text); } } sb.Append(Environment.NewLine); } if (slidePart.NotesSlidePart != null) { sb.Append(Environment.NewLine); var texts = slidePart.NotesSlidePart.NotesSlide.Descendants <Text>(); foreach (Text text in texts) { if (text.Parent is Field field && field.Type.HasValue && field.Type.Value == "slidenum") { continue; } sb.Append(bar).Append(text.Text); sb.Append(Environment.NewLine); } } return(sb.ToString()); }
private static void InsertNameAndDate(string pptxPath, string insertName, string insertDate) { using (PresentationDocument ppt = PresentationDocument.Open(pptxPath, true)) { if (ppt == null) { throw new ArgumentNullException("presentationDocument"); } PresentationPart part = ppt.PresentationPart; OpenXmlElementList slideIds = part.Presentation.SlideIdList.ChildElements; for (int index = 0; index < slideIds.Count(); index++) { // スライドを取得する string relId = (slideIds[index] as SlideId).RelationshipId; SlidePart slide = (SlidePart)part.GetPartById(relId); if (slide != null) { ShapeTree tree = slide.Slide.CommonSlideData.ShapeTree; //1番目の<s:sp>を取得する Shape shape = tree.GetFirstChild <Shape>(); if (shape != null) { TextBody textBody = shape.TextBody; IEnumerable <Drawing2.Paragraph> paragraphs = textBody.Descendants <Drawing2.Paragraph>(); foreach (Drawing2.Paragraph paragraph in paragraphs) { foreach (var text in paragraph.Descendants <Drawing2.Text>()) { if (text.Text.Contains("様邸")) { text.Text = insertName + text.Text; } else if (text.Text.Contains("年月日")) { text.Text = text.Text.Replace("年月日", insertDate); } } } } slide.Slide.Save(); } } } return; }
public void ValidateResultCountBetween(OpenXmlElementList source, string style, bool isZeroCountValid, bool isMultipleCountValid, int lowerLimit, int upperLimit, int dashIndex, int styleCount) { //int styleCount = Finder.FindManyBetween(source, style.ToLower(), lowerLimit, upperLimit, dashIndex).Count; if (styleCount == 0 && !isZeroCountValid) { throw new InvalidDataException("PARSER_VALIDATE_RESULT_COUNT_BETWEEN: Greška formata dokumenta! Ne postoji stil: " + style); } if (styleCount > 1 && !isMultipleCountValid) { throw new InvalidDataException("PARSER_VALIDATE_RESULT_COUNT_BETWEEN: Greška formata dokumenta! Postoji više stilova: " + style); } }
private static void GetSlideIdAndText(out string sldText, PresentationDocument ppt, int index) { // Get the relationship ID of the first slide. PresentationPart part = ppt.PresentationPart; OpenXmlElementList slideIds = part.Presentation.SlideIdList.ChildElements; string relId = (slideIds[index] as SlideId).RelationshipId; // Get the slide part from the relationship ID. SlidePart slide = (SlidePart)part.GetPartById(relId); sldText = slide.Slide.InnerText; }
private ICssProperty[] BuildMultiple(OpenXmlElementList childElements) { var result = new List <ICssProperty>(childElements.Count); foreach (var child in childElements) { var prop = BuildSingle(child); if (prop != null) { result.Add(prop); } } return(result.ToArray()); }