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); }
private string convert(String path, List <String> imgList, Size size) { String filePath = String.Empty; while (String.IsNullOrEmpty(filePath) || System.IO.File.Exists(filePath)) { string guid = Guid.NewGuid().ToString(); filePath = System.IO.Path.Combine(path, guid + ".pptx"); } try { using (PresentationDocument presentationDocument = PresentationDocument.Create(filePath, PresentationDocumentType.Presentation)) { PresentationPart presentationPart = presentationDocument.AddPresentationPart(); presentationPart.Presentation = new Presentation(); insert(presentationPart, imgList); presentationDocument.Close(); } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); throw new Exception("fail to convert image to pptx"); } return(filePath); }
public void Scan() { try { using PresentationDocument document = PresentationDocument.Open(this.powerpoint.FilePath, true); SlidePart slidePart; var presentation = document.PresentationPart.Presentation; //Console.WriteLine("Loaded"); foreach (SlideId slideId in presentation.SlideIdList) { slidePart = document.PresentationPart.GetPartById(slideId.RelationshipId) as SlidePart; if (slidePart == null || slidePart.Slide == null) { continue; } string currentSlideRelID = slideId.RelationshipId.Value; SlideModel slidemodel = CreateNewSlide(currentSlideRelID); Slide slide = slidePart.Slide; CheckIssues(slide, currentSlideRelID, slidePart, document); } document.Close(); } catch (FileNotFoundException) { Console.WriteLine("Opps, we could not find the presentation you were referencing. Try again...."); } }
public void Finish() { PreCGWDoc.Close(); PreSampleDoc.Close(); PreCGWDocInMemoryExpandable.Close(); PreSampleDocInMemoryExpandable.Close(); }
public static void SearchAndReplace(string document, string targetURI, string oldValue, string newValue) { //The string that will store the read excel stream string excelText = ""; using (PresentationDocument pptPres = PresentationDocument.Open(document, true)) { PackagePart pckgPart = pptPres.Package.GetPart(new Uri(targetURI, UriKind.Relative)); using (StreamReader sr = new StreamReader(pckgPart.GetStream())) { excelText = sr.ReadToEnd(); sr.Close(); } Regex regexText = new Regex(oldValue); excelText = regexText.Replace(excelText, newValue); using (StreamWriter sw = new StreamWriter(pckgPart.GetStream(FileMode.Create))) { sw.Write(excelText); sw.Flush(); sw.Close(); } pptPres.Close(); } }
public List <PPTSlide> GetPPTSlides(string pathToPresentation) { string fileFromPath = Path.GetFileName(pathToPresentation); var inf = new FileInfo(fileFromPath); string fileName = Path.GetFileNameWithoutExtension(inf.Name); string dir = Path.GetDirectoryName(Path.GetDirectoryName(Environment.CurrentDirectory)); string destDir = Path.Combine(dir, Globals.STORAGE_DIR); PresentationDocument presentationDocument = null; try { presentationDocument = PresentationDocument.Open(pathToPresentation, false); //get the slide sizes. Presentation presentation = presentationDocument.PresentationPart.Presentation; SlideSizes = presentation.SlideSize; } catch (Exception ex) { throw new FileNotFoundException( "PPTPresenationController.Ctor Unable to open Power Point Presentation.Path - " + pathToPresentation, ex.InnerException); } if (presentationDocument == null) { throw new ArgumentNullException("Presentation Document missing"); } IEnumerable <SlidePart> slideParts = GetPresentationSlideParts(presentationDocument); preserveWhitespaces(slideParts);//bug fix; whitespaces in separate runs are not preserved List <PPTSlide> pptSlides = GetPPTSlidesFromParts(slideParts, presentationDocument.PresentationPart.Presentation.DefaultTextStyle, fileName); presentationDocument.Close(); List <PPTImage> pictures = new List <PPTImage>(); foreach (PPTSlide slide in pptSlides) { foreach (PPTShapeBase baseShape in slide.ContainerShape.Elements) { if (typeof(PPTImage).Equals(baseShape.GetType())) { pictures.Add((PPTImage)baseShape); } } } var pptInteropt = new PPTBackgroundBuilderInterop(pathToPresentation, pictures); pptInteropt.ExportPresentationImages(destDir); pptInteropt = null; GC.Collect(); return(pptSlides); }
public void Close() { DeleteTemplateSlide(_detailSlideTemplate, DetailTemplateSlideId); DeleteTemplateSlide(_imageSlideTemplate, ImageTemplateSlideId); DeleteTemplateSlide(_forcesSlideTemplate, ForcesTemplateSlideId); DeleteTemplateSlide(_topicSlideTemplate, TopicTemplateSlideId); _doc.PresentationPart.Presentation.Save(); _doc.Close(); }
public int GetTotalSlidesCount(string presentationFile) { using (PresentationDocument prstDoc = PresentationDocument.Open(presentationFile, false)) { int slideCount = prstDoc.PresentationPart.Presentation.SlideIdList.Count(); prstDoc.Close(); return(slideCount); } }
/// <summary> /// <inheritdoc cref="IPresentation.Close"/> /// </summary> public void Close() { if (_disposed) { return; } _sdkPre.Close(); _disposed = true; }
/// <summary> /// 创建ppt /// </summary> /// <param name="filepath">保存地址</param> public static void CreatePresentation(string filepath) { PresentationDocument presentationDoc = PresentationDocument.Create(filepath, PresentationDocumentType.Presentation); PresentationPart presentationPart = presentationDoc.AddPresentationPart(); presentationPart.Presentation = new Presentation(); CreatePresentationParts(presentationPart); presentationDoc.Close(); }
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()); } }
public static void CreatePresentation(string filepath) { // Create a presentation at a specified file path. The presentation document type is pptx, by default. PresentationDocument presentationDoc = PresentationDocument.Create(filepath, PresentationDocumentType.Presentation); PresentationPart presentationPart = presentationDoc.AddPresentationPart(); presentationPart.Presentation = new Presentation(); CreatePresentationParts(presentationPart); // Close the presentation handle presentationDoc.Close(); }
static void Main(string[] args) { WordprocessingDocument doc = WordprocessingDocument.Create(@"C:\tmp\testOpenXmlLib.docx", OpenXmlPackage.DocumentType.Document); MainDocumentPart part = doc.MainDocumentPart; const string docXml = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <w:document xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main""> <w:body><w:p><w:r><w:t>Hello world!</w:t></w:r></w:p></w:body> </w:document>"; Stream stream = part.GetStream(); byte[] buf = (new UTF8Encoding()).GetBytes(docXml); stream.Write(buf, 0, buf.Length); doc.Close(); PresentationDocument presentation = PresentationDocument.Create(@"C:\tmp\testOpenXmlLib.pptx", OpenXmlPackage.DocumentType.Document); PresentationPart presentationPart = presentation.PresentationPart; SlidePart slide = presentationPart.AddSlidePart(); string presentationXml = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <p:presentation xmlns:a=""http://schemas.openxmlformats.org/drawingml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"" xmlns:p=""http://schemas.openxmlformats.org/presentationml/2006/main"" saveSubsetFonts=""1""> <p:sldIdLst> <p:sldId id=""256"" r:id=""" + slide.RelIdToString + @"""/> </p:sldIdLst> </p:presentation>"; stream = presentationPart.GetStream(); buf = (new UTF8Encoding()).GetBytes(presentationXml); stream.Write(buf, 0, buf.Length); string slideXml = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <p:sld xmlns:a=""http://schemas.openxmlformats.org/drawingml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"" xmlns:p=""http://schemas.openxmlformats.org/presentationml/2006/main""> </p:sld>"; stream = slide.GetStream(); buf = (new UTF8Encoding()).GetBytes(slideXml); stream.Write(buf, 0, buf.Length); presentation.Close(); }
public static void CreatePresentation() { string filepath = $@"{Constants.Locations.DesktopPath}\{Constants.FTP.PptFile}"; // Create a presentation at a specified file path. The presentation document type is pptx, by default. PresentationDocument presentationDoc = PresentationDocument.Create(filepath, PresentationDocumentType.Presentation); PresentationPart presentationPart = presentationDoc.AddPresentationPart(); presentationPart.Presentation = new P.Presentation(); CreatePresentationParts(presentationPart); //Close the presentation handle presentationDoc.Close(); }
public void CreatePresentation(string filepath) { // Create a presentation at a specified file path. The presentation document type is pptx, by default. PresentationDocument presentationDoc = PresentationDocument.Create(filepath, PresentationDocumentType.Presentation); PresentationPart presentationPart = presentationDoc.AddPresentationPart(); presentationPart.Presentation = new Presentation(); CreatePresentationParts(presentationPart); //Close the presentation handle //presentationDoc.SaveAs(@"C:\\Users\\Public\\Music\\info.pptx"); // presentationDoc.Save(); presentationDoc.Close(); //InsertNewSlide(presentationDoc, 1, "Hello, my name is Sumit"); }
public void SavePresentationAsSlideshow(string presentationFile) { using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, true)) { try { presentationDocument.ChangeDocumentType(PresentationDocumentType.Slideshow); presentationDocument.Close(); File.Copy(Server.MapPath("~/upload/default.pptx"), Server.MapPath("~/ppsx/default.ppsx")); // File.Copy(Server.MapPath("~/upload")"c:\\_websites\\cisfslebbmanagement\\upload\\default.pptx", @"c:\\_websites\\cisfslebbmanagement\\ppsx\\default.ppsx"); } catch (Exception ey) { lblError.Text = "Save Presentation As Slideshow Error: " + ey.Message; } } }
public void getPptDocumentAsMathML() { /*这里打开后会自动保存兼容性配置,不支持的会自动转为图片*/ //OpenSettings settings = new OpenSettings(); //settings.AutoSave = true; //MarkupCompatibilityProcessSettings markupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessAllParts, FileFormatVersions.Office2019); //settings.MarkupCompatibilityProcessSettings = markupCompatibilityProcessSettings; /*打开PPT*/ //using (PresentationDocument presentationDocument = PresentationDocument.Open(@"C:\Users\admin\Downloads\666.pptx", true, settings)) using (PresentationDocument presentationDocument = PresentationDocument.Open(@"C:\Users\admin\Downloads\666.pptx", false)) { /*获取演示部分*/ PresentationPart presentationPart = presentationDocument.PresentationPart; /*PPT页数*/ int slidesCount = presentationPart.SlideParts.Count(); OpenXmlElementList slideIds = presentationPart.Presentation.SlideIdList.ChildElements; for (int index = 0; index < slidesCount; index++) { /*PPT每页的ID*/ string relId = (slideIds[index] as SlideId).RelationshipId; SlidePart slide = (SlidePart)presentationPart.GetPartById(relId); List <string> mathOuterXmlList = new List <string>(); /*找到数学公式的xml列表*/ mathOuterXmlList = findMathParagraph(slide.Slide.ChildElements, mathOuterXmlList); foreach (string pptXml in mathOuterXmlList) { string mmlXml = xslTransform(pptXml, XSLMODE.OMML2MML); if (mmlXml != "") { string lexXml = xslTransform(mmlXml, XSLMODE.MML2TEX); //Console.Out.WriteLine(lexXml); } } } /*关闭PPT*/ presentationDocument.Close(); } }
/// <summary> /// Closes presentation. /// </summary> public void Close() { if (_closed) { return; } _sdkPre.Close(); if (_preSettings != null) { foreach (var xlsxDoc in _preSettings.XlsxDocuments.Values) { xlsxDoc.Close(); } } _closed = true; }
/// <summary> /// create pptx /// using OpenSDK /// </summary> /// <param name="svgDocs"></param> /// <param name="stream"></param> public static void CreatePowerPointXStreamBySvgs(List <SvgDocument> svgDocs, Stream stream) { using (MemoryStream ms = new MemoryStream()) { using (PresentationDocument presentationDoc = PresentationDocument.Create(ms, PresentationDocumentType.Presentation, true)) { PresentationPart presentationPart = presentationDoc.AddPresentationPart(); presentationPart.Presentation = new Presentation(); CreatePresentationTempalte(presentationPart); CreateImageSlideParts(presentationPart, svgDocs); DeleteSlide(presentationPart, 0); presentationDoc.Close(); ms.Seek(0, SeekOrigin.Begin); ms.WriteTo(stream); } } }
public void ExportToPPT(string folderPath, string themeFilePath) { string pptFilePath = folderPath + @"\Report.pptx"; if (CopyPresentation(themeFilePath, pptFilePath)) { using (PresentationDocument presentationDocument = PresentationDocument.Open(pptFilePath, true)) { //string xml = (new StreamReader(presentationDocument.PresentationPart.GetStream())).ReadToEnd(); DirectoryInfo imagesDirectory = new DirectoryInfo(folderPath); var presentationPart = presentationDocument.PresentationPart; //MMS:2 var templatePart = GetSlidePartsInOrder(presentationPart).ElementAt(4); foreach (FileInfo file in imagesDirectory.GetFiles("*.png")) { var newSlidePart = CloneSlide(templatePart); AppendSlide(presentationPart, newSlidePart); Slide slide = newSlidePart.Slide; //MMS:1 Picture pic = newSlidePart.Slide.Descendants <Picture>().First(); AddImagePart(slide, pic.BlipFill.Blip.Embed.Value, file.FullName); //using (FileStream imgStream = File.Open(file.FullName, FileMode.Open)) //{ // ip.FeedData(imgStream); //} //string xml = (new StreamReader(newSlidePart.GetStream())).ReadToEnd(); //Shape shape = slide.CommonSlideData.ShapeTree.Elements<Shape>().FirstOrDefault( //sh => sh.NonVisualShapeProperties.NonVisualDrawingProperties.Name.Value.ToLower().Equals("Picture Placeholder 5".ToLower())); //Picture pic = AddPicture(slide, shape, file.FullName); //slide.CommonSlideData.ShapeTree.RemoveChild<Shape>(shape); slide.Save(); //string xml2 = (new StreamReader(newSlidePart.GetStream())).ReadToEnd(); } //presentationDocument.PresentationPart.DeletePart(templatePart); string xml = (new StreamReader(presentationDocument.PresentationPart.GetStream())).ReadToEnd(); presentationDocument.PresentationPart.Presentation.Save(); presentationDocument.Close(); } } }
public static OpenXmlMemoryStreamDocument CreatePresentationDocument() { MemoryStream stream = new MemoryStream(); using (PresentationDocument doc = PresentationDocument.Create(stream, DocumentFormat.OpenXml.PresentationDocumentType.Presentation)) { doc.AddPresentationPart(); XNamespace ns = "http://schemas.openxmlformats.org/presentationml/2006/main"; XNamespace relationshipsns = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; XNamespace drawingns = "http://schemas.openxmlformats.org/drawingml/2006/main"; doc.PresentationPart.PutXDocument(new XDocument( new XElement(ns + "presentation", new XAttribute(XNamespace.Xmlns + "a", drawingns), new XAttribute(XNamespace.Xmlns + "r", relationshipsns), new XAttribute(XNamespace.Xmlns + "p", ns), new XElement(ns + "sldMasterIdLst"), new XElement(ns + "sldIdLst"), new XElement(ns + "notesSz", new XAttribute("cx", "6858000"), new XAttribute("cy", "9144000"))))); doc.Close(); return(new OpenXmlMemoryStreamDocument(stream)); } }
//public void ExportToPPT(string folderPath, string themeFilePath) //{ // string pptFilePath = folderPath + @"\Report.pptx"; // if (DocumentFormat.OpenXml.Packaging.Extensions.PowerpointExtensions.CopyPresentation(themeFilePath, pptFilePath)) // { // using (PresentationDocument presentationDocument = PresentationDocument.Open(pptFilePath, true)) // { // DirectoryInfo imagesDirectory = new DirectoryInfo(folderPath); // foreach (FileInfo file in imagesDirectory.GetFiles("*.png")) // { // Slide slide = presentationDocument.PresentationPart.InsertSlide("Title Only"); // Shape shape = slide.CommonSlideData.ShapeTree.Elements<Shape>().FirstOrDefault( // sh => sh.NonVisualShapeProperties.NonVisualDrawingProperties.Name.Value.ToLower().Equals("Content Placeholder 2".ToLower())); // Picture pic = slide.AddPicture(shape, file.FullName); // slide.CommonSlideData.ShapeTree.RemoveChild<Shape>(shape); // slide.Save(); // } // presentationDocument.PresentationPart.Presentation.Save(); // presentationDocument.Close(); // } // } //} public void ExportToPPT(string folderPath, string themeFilePath) { string pptFilePath = folderPath + @"\Report.pptx"; if (CopyPresentation(themeFilePath, pptFilePath)) { using (PresentationDocument presentationDocument = PresentationDocument.Open(pptFilePath, true)) { DirectoryInfo imagesDirectory = new DirectoryInfo(folderPath); int position = 7; foreach (FileInfo file in imagesDirectory.GetFiles("*.png")) { Slide slide = InsertNewSlide(presentationDocument, position, file.Name); Shape shape = slide.CommonSlideData.ShapeTree.Elements <Shape>().FirstOrDefault( sh => sh.NonVisualShapeProperties.NonVisualDrawingProperties.Name.Value.ToLower().Equals("Content Placeholder 2".ToLower())); Picture pic = slide.AddPicture(shape, file.FullName); slide.CommonSlideData.ShapeTree.RemoveChild <Shape>(shape); slide.Save(); } presentationDocument.PresentationPart.Presentation.Save(); presentationDocument.Close(); } } }
internal void MakeInvCopy(string templateAssemblyPath, string targetDirectory, OccurrenceList occurrenceList, UniqueModuleEvaluator uniqueModuleEvaluator) { // TODO Test for the existance of folders and assemblies. TemplateAssemblyPath = templateAssemblyPath; UniqueModules = uniqueModuleEvaluator; //Get the folder name that will be used to store the files associated with this Module. string folderName = GetModuleFolderPath(); //Need to get number of the parent occ, top level name as foldername ModulePath = System.IO.Path.Combine(targetDirectory, folderName); string topFileFullName = occurrenceList.TargetAssembly.FullDocumentName; string topFileNameOnly = System.IO.Path.GetFileName(topFileFullName); ModuleAssemblyPath = System.IO.Path.Combine(ModulePath, topFileNameOnly); //If this file already exists in the current location, for now we are //going to just skip the file creation, and assume it was previously done //correctly. Probably need to give the user the option to redo and //overwrite files if they want to. if (!System.IO.File.Exists(ModuleAssemblyPath)) { FilePathPair = new TupleList <string, string>(); for (int i = 0; i < occurrenceList.Items.Count; i++) { string targetOccPath = occurrenceList.Items[i].ReferencedFileDescriptor.FullFileName; string newCopyName = System.IO.Path.GetFileName(targetOccPath); string newFullCopyName = System.IO.Path.Combine(ModulePath, newCopyName); FilePathPair.Add(targetOccPath, newFullCopyName); } //Check if an earlier module already made the folder, if not, create it. if (!System.IO.Directory.Exists(ModulePath)) { //This property is needed later when placing occurrences of the assembly this Module instance //refers to. If FirstTime is false, we will want to have a slightly different strategry for constraint //placement. If FirstTime is true, all constraints are important and we need not relax them. If //FirstTime is false, then we need tolerance in the constraints because of double precision. When //FirstTime is false, we really just want to position the occurrence correctly, not drive its //geometry. if (FirstTime == null) { FirstTime = true; } System.IO.Directory.CreateDirectory(ModulePath); ReplaceReferences(occurrenceList.TargetAssembly, FilePathPair, ModulePath); AssemblyDocument oAssDoc = (AssemblyDocument)PersistenceManager.InventorApplication.Documents.Open(TemplateAssemblyPath, false); oAssDoc.SaveAs(ModuleAssemblyPath, true); oAssDoc.Close(true); //Need to copy presentation files if there are any. For now this is only going to work with the top assembly. string templateDirectory = System.IO.Path.GetDirectoryName(TemplateAssemblyPath); string[] presentationFiles = System.IO.Directory.GetFiles(templateDirectory, "*.ipn"); //If we want the ability to have subassemblies with .ipn files or multiple ones, this will have to be changed //to iterate over all the .ipn files. if (presentationFiles.Length != 0) { string newCopyPresName = System.IO.Path.GetFileName(presentationFiles[0]); string newFullCopyPresName = System.IO.Path.Combine(ModulePath, newCopyPresName); PresentationDocument presentationDocument = (PresentationDocument)PersistenceManager.InventorApplication.Documents.Open(presentationFiles[0], false); DocumentDescriptorsEnumerator presFileDescriptors = presentationDocument.ReferencedDocumentDescriptors; foreach (DocumentDescriptor refPresDocDescriptor in presFileDescriptors) { if (refPresDocDescriptor.FullDocumentName == TemplateAssemblyPath) { refPresDocDescriptor.ReferencedFileDescriptor.ReplaceReference(ModuleAssemblyPath); presentationDocument.SaveAs(newFullCopyPresName, true); presentationDocument.Close(true); } } } } else { FirstTime = false; } } }
/// <summary> /// プロパティを読み込みます /// </summary> /// <param name="filePath"></param> /// <param name="propertiesTable"></param> /// <returns>取得したプロパティ一覧</returns> public Dictionary <string, string> ReadProperties(ClsFilePropertyList list, string fileType, string str_exception) // 20171011 修正(ファイル読込時のエラー理由を保存) { Dictionary <string, string> retTable = new Dictionary <string, string>(); System.IO.FileInfo fi = new System.IO.FileInfo(list.filePath); if (fi.Length == 0) { // ファイルサイズがゼロの場合プロパティが存在しないのでエラー // 20171011 追加 (読取専用、ファイ存在しない以外のエラー) //error_reason = ListForm.LIST_VIEW_NA; return(retTable); } SpreadsheetDocument excel = null; WordprocessingDocument word = null; PresentationDocument ppt = null; CoreFilePropertiesPart coreFileProperties; // 20171011 修正(xlsxとdocxのみファイルを開いている状態でファイルアクセスするとエラーになる為の回避対応) try { // ファイルのプロパティ領域を開く switch (fileType) { case "Excel": // エクセルの場合 excel = SpreadsheetDocument.Open(list.filePath, false); coreFileProperties = excel.CoreFilePropertiesPart; break; case "Word": // ワードの場合 word = WordprocessingDocument.Open(list.filePath, false); coreFileProperties = word.CoreFilePropertiesPart; break; case "PowerPoint": // パワポの場合 ppt = PresentationDocument.Open(list.filePath, false); coreFileProperties = ppt.CoreFilePropertiesPart; break; default: // 異常なファイル // 20171228 追加(エラー理由保存) //error_reason = ListForm.LIST_VIEW_NA; return(retTable); } NameTable nt = new NameTable(); XmlNamespaceManager nsManager = new XmlNamespaceManager(nt); nsManager.AddNamespace(PropertiesKeyList.STR_TAG_CP, PropertiesSchemaList.CorePropertiesSchema); nsManager.AddNamespace(PropertiesKeyList.STR_TAG_DC, PropertiesSchemaList.DcPropertiesSchema); nsManager.AddNamespace(PropertiesKeyList.STR_TAG_DCTRMS, PropertiesSchemaList.DctermsPropertiesSchema); nsManager.AddNamespace(PropertiesKeyList.STR_TAG_DCMITYPE, PropertiesSchemaList.DcmitypePropertiesSchema); nsManager.AddNamespace(PropertiesKeyList.STR_TAG_XSI, PropertiesSchemaList.XsiPropertiesSchema); XmlDocument xdoc = new XmlDocument(); xdoc.Load(coreFileProperties.GetStream()); // プロパティのキーリストを作成 List <string> propertieslist = PropertiesKeyList.getPropertiesKeyList(); // 全キーリストを見て存在するデータを取得 foreach (string key in propertieslist) { // 書き込み先のキーワードを指定 string searchString = string.Format(PropertiesKeyList.STR_CORE_PROPERTIES + "{0}", key); // 書き込み先を検索 XmlNode xNode = xdoc.SelectSingleNode(searchString, nsManager); if (xNode != null) { // 読み込む retTable.Add(key, xNode.InnerText); } } // ファイルのプロパティ領域を閉じる if (excel != null) { excel.Close(); } if (word != null) { word.Close(); } if (ppt != null) { ppt.Close(); } // プロパティ取得 string[] propertyData = null; if (retTable.ContainsKey(PropertiesKeyList.STR_KEYWORDS) != false) { propertyData = retTable[PropertiesKeyList.STR_KEYWORDS].Split(';'); } if (propertyData != null) { list.fileSecrecy = propertyData[0].TrimEnd(); // 機密区分が登録されているか判定 if (!string.IsNullOrEmpty(list.fileSecrecy)) { // 登録あり if (propertyData.Count() >= 1) { list.fileClassification = propertyData[1].TrimEnd(); } if (propertyData.Count() >= 2) { list.fileOfficeCode = propertyData[2].TrimEnd(); } // 他事務所ファイル判定 if (Globals.ThisAddIn.clsCommonSettings.strOfficeCode != list.fileOfficeCode.Trim()) { // 他事務所ファイルの場合、登録なし扱にする list.fileSecrecy = ""; } } } else { list.fileSecrecy = "Notting"; } } #if false #region HyperLink修復 // ■ ADD TSE Kitada // HyperLinkが破損している場合に、そのリンクを書き直して正常にOPEN出来るようにする。 // 但し、ドキュメントの中身を直接書き換える処理のため、見送る。 catch (OpenXmlPackageException ope) { if (ope.ToString().Contains("Invalid Hyperlink")) { // HyperLinkの破損が原因なので、内部のリンクを修正する using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { UriFixer.FixInvalidUri(fs, brokenUri => FixUri(brokenUri)); } if (count >= 1) { // 2回実行してダメだったので終了 error_reason = ListForm.LIST_VIEW_NA; } else { // もう一度トライ retTable = ReadProperties(filePath, filetype, ref error_reason, ref str_exception, 1); } } if (excel != null) { excel.Close(); } if (word != null) { word.Close(); } if (ppt != null) { ppt.Close(); } } #endregion #endif catch (Exception e) { str_exception += "file : " + list.filePath + "\r\n\r\n"; str_exception += "error : " + e.ToString(); // xlsxとdocxのみファイルを開いている状態でファイルアクセスした場合 // ファイルが開かれている場合のエラー //error_reason = ListForm.LIST_VIEW_NA; if (excel != null) { excel.Close(); } if (word != null) { word.Close(); } if (ppt != null) { ppt.Close(); } return(retTable); } return(retTable); }
public void ClosePresentation() { OpenPresentationDocument.Close(); }
public void Finish() { PreCGWDoc.Close(); PreSampleDoc.Close(); }
/// <summary> /// プロパティを読み込みます /// </summary> /// <param name="filePath"></param> /// <param name="propertiesTable"></param> /// <returns></returns> public Dictionary <string, string> ReadProperties(string filePath, int filetype, ref string error_reason, ref string str_exception) // 20171011 修正(ファイル読込時のエラー理由を保存) { Dictionary <string, string> retTable = new Dictionary <string, string>(); System.IO.FileInfo fi = new System.IO.FileInfo(filePath); if (fi.Length == 0) { // ファイルサイズがゼロの場合プロパティが存在しないのでエラー // 20171011 追加 (読取専用、ファイ存在しない以外のエラー) error_reason = ListForm.LIST_VIEW_NA; return(retTable); } SpreadsheetDocument excel = null; WordprocessingDocument word = null; PresentationDocument ppt = null; CoreFilePropertiesPart coreFileProperties; // 20171011 修正(xlsxとdocxのみファイルを開いている状態でファイルアクセスするとエラーになる為の回避対応) try { // ファイルのプロパティ領域を開く switch (filetype) { case ListForm.EXTENSION_EXCEL: excel = SpreadsheetDocument.Open(filePath, false); coreFileProperties = excel.CoreFilePropertiesPart; break; case ListForm.EXTENSION_WORD: word = WordprocessingDocument.Open(filePath, false); coreFileProperties = word.CoreFilePropertiesPart; break; case ListForm.EXTENSION_POWERPOINT: ppt = PresentationDocument.Open(filePath, false); coreFileProperties = ppt.CoreFilePropertiesPart; break; default: // 異常なファイル // 20171228 追加(エラー理由保存) error_reason = ListForm.LIST_VIEW_NA; return(retTable); } NameTable nt = new NameTable(); XmlNamespaceManager nsManager = new XmlNamespaceManager(nt); nsManager.AddNamespace(PropertiesKeyList.STR_TAG_CP, PropertiesSchemaList.CorePropertiesSchema); nsManager.AddNamespace(PropertiesKeyList.STR_TAG_DC, PropertiesSchemaList.DcPropertiesSchema); nsManager.AddNamespace(PropertiesKeyList.STR_TAG_DCTRMS, PropertiesSchemaList.DctermsPropertiesSchema); nsManager.AddNamespace(PropertiesKeyList.STR_TAG_DCMITYPE, PropertiesSchemaList.DcmitypePropertiesSchema); nsManager.AddNamespace(PropertiesKeyList.STR_TAG_XSI, PropertiesSchemaList.XsiPropertiesSchema); XmlDocument xdoc = new XmlDocument(); xdoc.Load(coreFileProperties.GetStream()); // プロパティのキーリストを作成 List <string> propertieslist = PropertiesKeyList.getPropertiesKeyList(); // 全キーリストを見て存在するデータを取得 foreach (string key in propertieslist) { // 書き込み先のキーワードを指定 string searchString = string.Format(PropertiesKeyList.STR_CORE_PROPERTIES + "{0}", key); // 書き込み先を検索 XmlNode xNode = xdoc.SelectSingleNode(searchString, nsManager); if (xNode != null) { // 読み込む retTable.Add(key, xNode.InnerText); } } // ファイルのプロパティ領域を閉じる if (excel != null) { excel.Close(); } if (word != null) { word.Close(); } if (ppt != null) { ppt.Close(); } } #if false #region HyperLink修復 // ■ ADD TSE Kitada // HyperLinkが破損している場合に、そのリンクを書き直して正常にOPEN出来るようにする。 // 但し、ドキュメントの中身を直接書き換える処理のため、見送る。 catch (OpenXmlPackageException ope) { if (ope.ToString().Contains("Invalid Hyperlink")) { // HyperLinkの破損が原因なので、内部のリンクを修正する using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { UriFixer.FixInvalidUri(fs, brokenUri => FixUri(brokenUri)); } if (count >= 1) { // 2回実行してダメだったので終了 error_reason = ListForm.LIST_VIEW_NA; } else { // もう一度トライ retTable = ReadProperties(filePath, filetype, ref error_reason, ref str_exception, 1); } } if (excel != null) { excel.Close(); } if (word != null) { word.Close(); } if (ppt != null) { ppt.Close(); } } #endregion #endif catch (Exception e) { str_exception += "file : " + filePath + "\r\n\r\n"; str_exception += "error : " + e.ToString(); // xlsxとdocxのみファイルを開いている状態でファイルアクセスした場合 // ファイルが開かれている場合のエラー error_reason = ListForm.LIST_VIEW_NA; if (excel != null) { excel.Close(); } if (word != null) { word.Close(); } if (ppt != null) { ppt.Close(); } return(retTable); } return(retTable); }
/// <summary> /// プロパティを書き込みます /// </summary> /// <param name="filePath"></param> /// <param name="propertiesTable"></param> /// <returns></returns> public bool WriteProperties(string filePath, string keyword, int filetype, bool bFileInfoUpdate, List <string> lstFinal, ref DateTime LastWriteTime, ref string error_reason) // 20171011 修正(ファイル書込み時のエラー理由を保存) // step2 iwasa { bool bRet = true; // 20171010 修正(try-catch追加(対象ファイルが存在しない場合に発生するエラー対応)) // (検索ボタン押下後、ファイルを移動/削除した場合など) try { System.IO.FileInfo fi = new System.IO.FileInfo(filePath); if (fi.Length == 0) { // ファイルサイズがゼロの場合プロパティが存在しないのでエラー // 20171228 追加(エラー理由保存) error_reason = ListForm.LIST_VIEW_NA; return(false); } // 最終版 } catch { // 対象ファイルが存在しない場合にここに来る // ファイルが存在しない場合のエラー error_reason = ListForm.LIST_VIEW_NA; return(false); } // ファイルのプロパティ領域を開く SpreadsheetDocument excel = null; WordprocessingDocument word = null; PresentationDocument ppt = null; CoreFilePropertiesPart coreFileProperties; // 20171010 修正(try-catch追加(開いているファイルを開こうとして発生するエラー対応)) try { switch (filetype) { case ListForm.EXTENSION_EXCEL: excel = SpreadsheetDocument.Open(filePath, true); coreFileProperties = excel.CoreFilePropertiesPart; break; case ListForm.EXTENSION_WORD: word = WordprocessingDocument.Open(filePath, true); coreFileProperties = word.CoreFilePropertiesPart; break; case ListForm.EXTENSION_POWERPOINT: ppt = PresentationDocument.Open(filePath, true); coreFileProperties = ppt.CoreFilePropertiesPart; break; default: // 異常なファイル // 20171228 追加(エラー理由保存) error_reason = ListForm.LIST_VIEW_NA; return(false); } } catch { // 開いているファイルを開いた場合にここに来る // ファイルが開かれている場合のエラー // または読み取り専用のファイル error_reason = ListForm.LIST_VIEW_NA; return(false); } LastWriteTime = new DateTime(); NameTable nt = new NameTable(); XmlNamespaceManager nsManager = new XmlNamespaceManager(nt); nsManager.AddNamespace(PropertiesKeyList.STR_TAG_CP, PropertiesSchemaList.CorePropertiesSchema); nsManager.AddNamespace(PropertiesKeyList.STR_TAG_DC, PropertiesSchemaList.DcPropertiesSchema); nsManager.AddNamespace(PropertiesKeyList.STR_TAG_DCTRMS, PropertiesSchemaList.DctermsPropertiesSchema); nsManager.AddNamespace(PropertiesKeyList.STR_TAG_DCMITYPE, PropertiesSchemaList.DcmitypePropertiesSchema); nsManager.AddNamespace(PropertiesKeyList.STR_TAG_XSI, PropertiesSchemaList.XsiPropertiesSchema); XmlDocument xdoc = new XmlDocument(); try { xdoc.Load(coreFileProperties.GetStream()); // 最終版のチェック string searchString = string.Format(PropertiesKeyList.STR_CORE_PROPERTIES + "{0}", PropertiesKeyList.STR_CONTENT_STATUS); // 書き込み先を検索 XmlNode xNode = xdoc.SelectSingleNode(searchString, nsManager); //if (xNode != null && xNode.InnerText == PropertiesKeyList.STR_FINAL_CONTENT) if (xNode != null && lstFinal.Contains(xNode.InnerText)) // step2 iwasa { // 最終版のファイルへの書き込みはできないのでエラーを返す // 20171228追加(エラーの理由を保存) error_reason = ListForm.LIST_VIEW_NA; return(false); } // 更新日時を読み込む // 書き込み先のキーワードを指定 searchString = string.Format(PropertiesKeyList.STR_CORE_PROPERTIES + "{0}", PropertiesKeyList.STR_MODIFIED); // 書き込み先を検索 xNode = xdoc.SelectSingleNode(searchString, nsManager); if (xNode != null) { LastWriteTime = DateTime.Parse(xNode.InnerText); } else { // なかったら今日の日付 LastWriteTime = DateTime.Now; } // キーワードの書込 // 書き込み先のキーワードを指定 searchString = string.Format(PropertiesKeyList.STR_CORE_PROPERTIES + "{0}", PropertiesKeyList.STR_KEYWORDS); // 書き込み先を検索 xNode = xdoc.SelectSingleNode(searchString, nsManager); if (xNode != null) { // 書き込む xNode.InnerText = keyword; } else { // keywordsタグが存在していないので作成する XmlNode node = xdoc.DocumentElement; // TSE kitada Comment. // .NETのバグ(?)により、"cp:keywords"を出力すると「:」より前をprefix扱いして勝手に削除してしまうため // Excelのフォーマットとして破損した形で出力されてしまう。 // "cp:"の部分は名前空間を指定することで勝手に付与されるので、qualifiedNameにはcp:をつけなくてよい。 XmlElement el = xdoc.CreateElement(PropertiesKeyList.STR_KEYWORDS, PropertiesSchemaList.CorePropertiesSchema); el.InnerText = keyword; node.AppendChild(el); } // カテゴリのリセット // 書き込み先のキーワードを指定 searchString = string.Format(PropertiesKeyList.STR_CORE_PROPERTIES + "{0}", PropertiesKeyList.STR_CATEGORY); // 書き込み先を検索 xNode = xdoc.SelectSingleNode(searchString, nsManager); if (xNode != null) { // 書き込む xNode.InnerText = ""; // 保存 //xdoc.Save(coreFileProperties.GetStream()); } // 20190705 TSE matsuo ファイルのプロパティ領域を再作成する if (excel != null) { excel.DeletePart(excel.CoreFilePropertiesPart); excel.AddCoreFilePropertiesPart(); coreFileProperties = excel.CoreFilePropertiesPart; } if (word != null) { word.DeletePart(word.CoreFilePropertiesPart); word.AddCoreFilePropertiesPart(); coreFileProperties = word.CoreFilePropertiesPart; } if (ppt != null) { ppt.DeletePart(ppt.CoreFilePropertiesPart); ppt.AddCoreFilePropertiesPart(); coreFileProperties = ppt.CoreFilePropertiesPart; } // 20180109 TSE kitada 保存は最後に一回だけ // 保存 xdoc.Save(coreFileProperties.GetStream()); } catch (Exception e) { bRet = false; // 20171011 追加 (読取専用、ファイ存在しない以外のエラー) error_reason = ListForm.LIST_VIEW_NA; } finally { // ファイルのプロパティ領域を閉じる if (excel != null) { excel.Close(); } if (word != null) { word.Close(); } if (ppt != null) { ppt.Close(); } } try { // 更新日は更新しない場合は元の更新日を上書きする if (!bFileInfoUpdate) { System.IO.File.SetLastWriteTime(filePath, LastWriteTime); } } catch (Exception e) { // 対象ファイルがロックされている場合はスルーする } return(bRet); }
public void SetPPTShapeText(string[] arrayParameters, int numSlide) { using (PresentationDocument ppt = PresentationDocument.Open(HttpContext.Current.Server.MapPath(folder), true)) { numSlide--; IEnumerable <Shape> elementSlide; PresentationPart part = ppt.PresentationPart; OpenXmlElementList slideIds = part.Presentation.SlideIdList.ChildElements; string relId = (slideIds[numSlide] as SlideId).RelationshipId; SlidePart slide = (SlidePart)part.GetPartById(relId); if (slide != null) { ShapeTree tree = slide.Slide.CommonSlideData.ShapeTree; elementSlide = tree.Elements <Shape>(); foreach (Shape shape1 in elementSlide) { string valueStr = shape1.NonVisualShapeProperties.NonVisualDrawingProperties.Name.Value; switch (valueStr) { case "Заголовок 1": Drawing.Paragraph paragraph1 = shape1.TextBody.ChildElements.OfType <Drawing.Paragraph>().ElementAt(0); Drawing.Run run1 = paragraph1.ChildElements.OfType <Drawing.Run>().ElementAt(0); run1.Text.Text = arrayParameters[0]; slide.Slide.Save(); break; case "Прямоугольник 4": paragraph1 = shape1.TextBody.ChildElements.OfType <Drawing.Paragraph>().ElementAt(0); run1 = paragraph1.ChildElements.OfType <Drawing.Run>().ElementAt(0); run1.Text.Text = arrayParameters[1]; slide.Slide.Save(); break; case "Прямоугольник 6": paragraph1 = shape1.TextBody.ChildElements.OfType <Drawing.Paragraph>().ElementAt(0); run1 = paragraph1.ChildElements.OfType <Drawing.Run>().ElementAt(0); run1.Text.Text = arrayParameters[2]; slide.Slide.Save(); break; case "Прямоугольник 9": paragraph1 = shape1.TextBody.ChildElements.OfType <Drawing.Paragraph>().ElementAt(0); run1 = paragraph1.ChildElements.OfType <Drawing.Run>().ElementAt(0); run1.Text.Text = arrayParameters[3]; slide.Slide.Save(); break; case "Прямоугольник 11": paragraph1 = shape1.TextBody.ChildElements.OfType <Drawing.Paragraph>().ElementAt(0); run1 = paragraph1.ChildElements.OfType <Drawing.Run>().ElementAt(0); run1.Text.Text = arrayParameters[4]; slide.Slide.Save(); break; case "Прямоугольник 13": paragraph1 = shape1.TextBody.ChildElements.OfType <Drawing.Paragraph>().ElementAt(0); run1 = paragraph1.ChildElements.OfType <Drawing.Run>().ElementAt(0); run1.Text.Text = arrayParameters[5]; slide.Slide.Save(); break; case "Прямоугольник 18": paragraph1 = shape1.TextBody.ChildElements.OfType <Drawing.Paragraph>().ElementAt(0); run1 = paragraph1.ChildElements.OfType <Drawing.Run>().ElementAt(0); run1.Text.Text = arrayParameters[6]; slide.Slide.Save(); break; case "Прямоугольник 20": paragraph1 = shape1.TextBody.ChildElements.OfType <Drawing.Paragraph>().ElementAt(0); run1 = paragraph1.ChildElements.OfType <Drawing.Run>().ElementAt(0); run1.Text.Text = arrayParameters[7]; slide.Slide.Save(); break; } } } ppt.Close(); } }
private void SaveAndCloseDocument() { document.Save(); document.Close(); }