public override void Convert(String inputFile, String outputFile)
        {
            try
            {
                if (!File.Exists(inputFile))
                {
                    throw new ConvertException("File not Exists");
                }

                if (IsPasswordProtected(inputFile))
                {
                    throw new ConvertException("Password Exist");
                }

                app = new PowerPoint.Application();
                presentations = app.Presentations;
                presentation = presentations.Open(inputFile, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
                presentation.ExportAsFixedFormat(outputFile, PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF);
                // presentation.ExportAsFixedFormat(outputFile, PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF, PowerPoint.PpFixedFormatIntent.ppFixedFormatIntentScreen, MsoTriState.msoFalse, PowerPoint.PpPrintHandoutOrder.ppPrintHandoutVerticalFirst, PowerPoint.PpPrintOutputType.ppPrintOutputSlides, MsoTriState.msoFalse, null, PowerPoint.PpPrintRangeType.ppPrintAll, "", false, false, false, false, false, null);
            }
            catch (Exception e)
            {
                release();
                throw new ConvertException(e.Message);
            }
            release();
        }
Пример #2
0
 public DirectoryInfo Convert(FileInfo ppt)
 {
     DirectoryInfo dir = new DirectoryInfo(ppt.Directory.FullName + "/" + Path.GetFileNameWithoutExtension(ppt.Name));
     dir.Create();
     PowerPoint.Application pptApp = null;
     PowerPoint.Presentation pptDoc = null;
     try
     {
         pptApp = new PowerPoint.Application();
         pptDoc = pptApp.Presentations.Open(ppt.FullName, OfficeCore.MsoTriState.msoFalse, OfficeCore.MsoTriState.msoFalse, OfficeCore.MsoTriState.msoFalse);
         if (pptDoc.CreateVideoStatus != PowerPoint.PpMediaTaskStatus.ppMediaTaskStatusInProgress
             && pptDoc.Slides.Count > 0)
         {
             pptDoc.Export(dir.FullName, "png");
         }
     }
     catch (Exception e)
     {
         log.Error("Convert PPT error", e);
     }
     finally
     {
         if (pptDoc != null)
             pptDoc.Close();
         if(pptApp != null)
             pptApp.Quit();
     }
     return dir;
 }
        /// <summary>
        /// Open PPT App and opens dialog to select presentation
        /// </summary>
        /// <returns></returns>
        public bool OpenPowerPoint()
        {
            try
            {
                //Create an instance of PowerPoint.
                oPPT = new Application();
                // Show PowerPoint to the user.
                oPPT.Visible = MsoTriState.msoTrue;
                objPresSet = oPPT.Presentations;
                OpenFileDialog Opendlg = new OpenFileDialog();

                Opendlg.Filter = "Powerpoint|*.ppt;*.pptx|All files|*.*";

                // Open file when user  click "Open" button
                if (Opendlg.ShowDialog() == true)
                {
                    string pptFilePath = Opendlg.FileName;
                    //open the presentation
                    objPres = objPresSet.Open(pptFilePath, MsoTriState.msoFalse,
                    MsoTriState.msoTrue, MsoTriState.msoTrue);

                    objPres.SlideShowSettings.ShowPresenterView = MsoTriState.msoFalse;
                    objPres.SlideShowSettings.Run();
                    
                    oSlideShowView = objPres.SlideShowWindow.View;
                    return true;
                }
                return false;
            }
            catch (Exception)
            {
                MessageBox.Show("Unable to open Power Point, please make sure you have the program installed correctly");
                return false;
            }
        }
Пример #4
0
 public void Generate()
 {
     indensionStack.Clear();
     indensionStack.Push(-1);
     if (app == null) app = new Application();
     thisPresentation = app.Presentations.Add(MsoTriState.msoFalse);
     var cl = new DocumentClosure(null, thisPresentation, app);
     CurrentClosure = cl;
     ChangeTheme();
     cl.Initialize();
     cl.WorkPath = DefaultWorkPath;
     var module = thisPresentation.VBProject.VBComponents.Add(vbext_ComponentType.vbext_ct_StdModule);
     module.CodeModule.AddFromString(Resources.VBAModule);
     while (true)
     {
         var thisLine = ScriptReader.ReadLine();
         if (thisLine == null) break;
         Console.WriteLine(thisLine);
         if (!string.IsNullOrWhiteSpace(thisLine) && thisLine.TrimStart()[0] != '#')
             ParseLine(thisLine);
     }
     while (CurrentClosure != null) ExitClosure();
     app.Run("PAG_PostProcess", thisPresentation);
     var wnd = thisPresentation.NewWindow();
     thisPresentation.VBProject.VBComponents.Remove(module);
     wnd.Activate();
     //thisPresentation.Close();
 }
Пример #5
0
 private void Button_Split_Click(object sender, EventArgs e)
 {
     if (DialogResult.OK == ChooseFolder.ShowDialog())
     {
         Cursor = Cursors.WaitCursor;
         Microsoft.Office.Interop.PowerPoint.Application A = new Microsoft.Office.Interop.PowerPoint.Application();
         foreach (string file in MyFiles)
         {
             FileInfo F = new FileInfo(file);
             string Name = F.Name;
             Presentation P = A.Presentations.Open(file, MsoTriState.msoTrue,
                 MsoTriState.msoFalse, MsoTriState.msoFalse);
             for (int i = 1; i <= P.Slides.Count; i++)
             {
                 P.Slides[i].Copy();
                 Presentation P1 = A.Presentations.Add(MsoTriState.msoFalse);
                 P1.Slides.Paste(1);
                 P1.Slides[1].FollowMasterBackground = MsoTriState.msoFalse;
                 P1.SaveAs(ChooseFolder.SelectedPath + "\\" + i.ToString() + "_" + Name,
                     PpSaveAsFileType.ppSaveAsDefault, MsoTriState.msoFalse);
                 P1.Close();
             }
             P.Close();
         }
         Cursor = Cursors.Default;
     }
 }
 public void Initialised(object context)
 {
     presentation = (PowerPoint.Presentation) context;
     if (presentation == null) return;
     application = presentation.Application;
     application.PresentationNewSlide += ApplicationOnPresentationNewSlide;
 }
Пример #7
0
        public int loadFile(String filename)
        {
            //Create app and open file
            app = new PPT.Application();
            pres = app.Presentations.Open(filename, Core.MsoTriState.msoFalse,
                Core.MsoTriState.msoFalse, Core.MsoTriState.msoFalse);

            if (pres == null)
            {
                sss = null;
                ssw = null;
                ssv = null;

                loaded = false;
                visible = false;
                return -1;
            }

            app.Visible = Core.MsoTriState.msoFalse;

            sss = pres.SlideShowSettings;
            sss.ShowType = PPT.PpSlideShowType.ppShowTypeKiosk;
            ssw = sss.Run();
            ssv = ssw.View;

            loaded = true;
            visible = true;
            return pres.Slides.Count;
        }
Пример #8
0
        public Presenter(Application app, SlideShowWindow win)
        {
            app_ = app;
            win_ = win;

            try
            {
                provider_ = new Nui.Provider();
            }
            catch (InvalidOperationException)
            {
                provider_ = null;

                if (MessageBox.Show(
                    "Kinect is not detected. Check the connection and device.\nWould you like to disable Kinect for the presentation?",
                    "Kynapsee", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.Yes)
                {
                    win_.Presentation.SetKinectEnable(false);
                    return;
                }
                win_.View.Exit();
                return;
            }

            gestures_ = win.Presentation.GetNuiModel();

            provider_.GestureDone += GestureDone;
            app.SlideShowNextSlide += SlideShowNextSlide;

            LoadSlideGestures();
        }
Пример #9
0
        public virtual void Show(IJointShow jointShow, bool launchShow)
        {
            List<IShow> shows = jointShow.ShowOrderShows;
            if (shows.Count == 0) return;

            PowerPoint.Application application = new PowerPoint.Application();
            PowerPoint.Presentations applicationPresentations = application.Presentations;

            PowerPoint.Presentation joinedPresentation = applicationPresentations.Add();

            for (int i = 0; i < shows.Count; i++)
            {
                PowerPoint.Presentation sourcePresentation
                    = applicationPresentations.Open(shows[i].Path, MsoTriState.msoFalse, MsoTriState.msoTrue, MsoTriState.msoFalse);
                CopySlides(sourcePresentation, joinedPresentation);

                sourcePresentation.Close();
                Marshal.ReleaseComObject(sourcePresentation);
            }

            if (launchShow)
            {
                PowerPoint.SlideShowSettings slideShowSettings = joinedPresentation.SlideShowSettings;
                slideShowSettings.Run();

                GC.Collect();
                GC.WaitForPendingFinalizers();
                Marshal.ReleaseComObject(slideShowSettings);
            }

            Marshal.ReleaseComObject(joinedPresentation);
            Marshal.ReleaseComObject(applicationPresentations);
            Marshal.ReleaseComObject(application);
        }
Пример #10
0
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                server = new TcpListener(System.Net.IPAddress.Any, LOCAL_PORT);
                server.Start();
                SetText("Server listening on port " + LOCAL_PORT);
                NextClient();

                Debug.WriteLine("Form loaded");

                //Create an instance of PowerPoint.
                oPPT = new PowerPoint.Application();

                oPPT.PresentationOpen += new Microsoft.Office.Interop.PowerPoint.EApplication_PresentationOpenEventHandler(oPPT_PresentationOpen);
                oPPT.SlideShowNextClick += new Microsoft.Office.Interop.PowerPoint.EApplication_SlideShowNextClickEventHandler(oPPT_SlideShowNextClick);
                oPPT.SlideShowNextSlide += new Microsoft.Office.Interop.PowerPoint.EApplication_SlideShowNextSlideEventHandler(oPPT_SlideShowNextSlide);
                //oPPT.SlideShowOnNext += new Microsoft.Office.Interop.PowerPoint.EApplication_SlideShowOnNextEventHandler(oPPT_SlideShowOnNext);

                // Show PowerPoint to the user.
                oPPT.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message, "Application error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
                Application.Exit();
            }
        }
 public PptEventHandlers(PPT.Application pptApp)
 {
     _app = pptApp;
     
     _app.SlideShowBegin += new PPT.EApplication_SlideShowBeginEventHandler(_app_SlideShowBegin);
     _app.SlideShowEnd += new PPT.EApplication_SlideShowEndEventHandler(_app_SlideShowEnd);
     _app.SlideShowNextSlide += new PPT.EApplication_SlideShowNextSlideEventHandler(_app_SlideShowNextSlide);            
 }
Пример #12
0
 public SlideshowManager(string presentationFile)
 {
     this.PresentationFile = presentationFile;
     this.PowerPointApp = new PowerPoint.Application();
     this.PowerPointApp.Activate();
     Presentation = this.PowerPointApp.Presentations.Open(presentationFile);
     Presentation.SlideShowSettings.Run();
 }
Пример #13
0
        private void LaunchApplication()
        {
            if (g_PPT_Application == null)
                g_PPT_Application = new PowerPoint.Application();

            //g_PPT_Application.Visible = MsoTriState.msoTrue;
            //g_PPT_Application.SlideShowBegin += g_PPT_Application_SlideShowBegin;
        }
Пример #14
0
 //
 //**********************************************************************************************
 //
 // Class TPPT
 //   Part of  : TDRFree
 //   Function : Interacts with Microsoft Powerpoint to make a presentation
 //   Author   : Jan G. Wesseling
 //   Date     : April 9th, 2013
 //
 //**********************************************************************************************
 //
 public TPPT()
 {
     MyApp = new PowerPoint.Application();
       MyApp.Visible = MsoTriState.msoTrue;
       MyApp.WindowState = PowerPoint.PpWindowState.ppWindowMinimized;
     MyPresentations = MyApp.Presentations;
       MyPresentation = MyPresentations.Add(MsoTriState.msoFalse);
       MySlides = MyPresentation.Slides;
 }
Пример #15
0
 public void Setup()
 {
     CultureUtil.SetDefaultCulture(CultureInfo.GetCultureInfo("en-US"));
     App = new PowerPoint.Application();
     Pres = App.Presentations.Open(
         PathUtil.GetDocTestPath() + GetTestingSlideName(),
         WithWindow: MsoTriState.msoFalse);
     PpOperations = new UnitTestPpOperations(Pres, App);
 }
Пример #16
0
        static void Main(string []args)
        {
            String path = System.IO.Directory.GetCurrentDirectory();
            String rpath=path+"\\copy\\";
            String path1 = path + "\\copy\\pptimg";
            
            string[] filePaths = Directory.GetFiles(path1, "*.jpg");
            foreach (string filePath in filePaths)
            {
                //if (filePath.Contains(".bmp"))
                File.Delete(filePath);
            }
            
            Microsoft.Office.Interop.PowerPoint.Application app = new Microsoft.Office.Interop.PowerPoint.Application();

            Console.WriteLine("Specify the complete path of the Powerpoint file...");

            String spath = Console.ReadLine();

            Presentation pres = app.Presentations.Open(spath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
           
            pres.SaveAs(path1, PpSaveAsFileType.ppSaveAsJPG, MsoTriState.msoFalse);

            pres.Close();

            string folder = path1;
            string[] files = Directory.GetFiles(folder);
            NumericComparer ns = new NumericComparer();
            Array.Sort(files, ns);
            int count1 = 0;
            foreach (string file in files)
            {
                count1++;
            }

            TextReader tr = new StreamReader("begin.html");
            TextWriter tw = new StreamWriter(path+"\\copy\\op.html");
            tw.WriteLine(tr.ReadToEnd());
            String int_str;
            for (int i = 0; i < count1; i++)
            {
                int_str=files[i].Replace(rpath, "");
                tw.WriteLine("<div class=\"slide\" id=\"landing-slide" + i + "\"> <style>#landing-slide p {font-size: 35px;}#landing-slide li{font-size: 25px;}</style><section class=\"middle\"><img id=\"imgBamburgh" + i + "\" alt=\"\"src=\"" + int_str + "\"pbshowcaption=\"true\"pbcaption=\""+int_str+"\"style=\"width: 750px; height: 550px;\"class=\"PopBoxImageSmall\" title=\"Click to magnify/shrink\" onclick=\"Pop(this,50,'PopBoxImageLarge');\" /></section> </div> ");
                tw.WriteLine();
            }
                tr.Close();
            tw.Close();

            string fname=path + "\\copy\\op.html";
            TextReader tr2 = new StreamReader("end.html");
   FileInfo file1=new FileInfo(fname);
   StreamWriter sw = File.AppendText(fname);
   sw.WriteLine(tr2.ReadToEnd());
   tr2.Close();
   sw.Close(); 
        }
Пример #17
0
 public void KillApplications()
 {
     //Kill All the processes
     var pptProcesses = Process.GetProcessesByName("powerpnt");
     foreach (var p in pptProcesses)
         p.Kill();
     g_ApplicationStarted = false;
     g_PPT_Application = null;
     g_PPT_PresentationToBeProjected = null;
 }
Пример #18
0
 private void createPresentationBtn_Click(object sender, EventArgs e)
 {
     //create the powerpoint interop object
     powerPointApplication = new Microsoft.Office.Interop.PowerPoint.Application();
     //set to visible to show powerpoint during this process
     powerPointApplication.Visible = MsoTriState.msoTrue;
     //Get the list of presentations in the application
     Presentations presentations=powerPointApplication.Presentations;
     //add a presentation and add to the list above
     currentPresentation = presentations.Add(MsoTriState.msoCTrue);
 }
Пример #19
0
 private void CreatePowerPoint() {
     lock(this) {
        if (mspowerpoint == null) {
             mspowerpoint = new PowerPoint.Application();
             mspowerpoint.Visible = MsoTriState.msoTrue;
             mspowerpoint.DisplayAlerts = PowerPoint.PpAlertLevel.ppAlertsNone;
             mspowerpoint.AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityForceDisable;
             
             //No way to do this in powerpoint, it seems
             //mspowerpoint.?Path? = Directory.GetCurrentDirectory();
         }
     }
 }
Пример #20
0
 public static void TweetSlideChange_SlideShowNextSlide(Application powerpointApplication, SlideShowWindow slideShowWindow)
 {
     try
     {
         string subject = ConfigManager.CurrentUserSpecific.PresentationSubject;
         string notesFirstLine = GetNotesFirstLine(slideShowWindow);
         if (String.IsNullOrEmpty(notesFirstLine))
             return;
         string tweet = String.Format("{0} {1}", subject, notesFirstLine).Trim();
         TwitterFeedSupport.Tweet(tweet);
     }
     catch
     {
     }
 }
Пример #21
0
        private static void AutomatePowerPointImpl()
        {
            try
            {
            // 创建一个Microsoft PowerPoint实例并使其不可见。

                PowerPoint.Application oPowerPoint = new PowerPoint.Application();
            // 默认情况下PowerPoint不可见,直道你使它可见。
                //oPowerPoint.Visible = Office.MsoTriState.msoFalse;

            // 创建一个新的演示文稿。

                PowerPoint.Presentation oPre = oPowerPoint.Presentations.Add(
                    Microsoft.Office.Core.MsoTriState.msoTrue);
                Console.WriteLine("一个新的演示文稿被建立");

            // 插入一个幻灯片,并为幻灯片加入一些文本。

                Console.WriteLine("插入一个幻灯片");
                PowerPoint.Slide oSlide = oPre.Slides.Add(1,
                    PowerPoint.PpSlideLayout.ppLayoutText);

                Console.WriteLine("添加一些文本");
                oSlide.Shapes[1].TextFrame.TextRange.Text =
                    "一站式代码框架";

            // 保存此演示文稿为pptx文件并将其关闭。

                Console.WriteLine("保存并退出演示文稿");

                string fileName = Path.GetDirectoryName(
                    Assembly.GetExecutingAssembly().Location) + "\\Sample2.pptx";
                oPre.SaveAs(fileName,
                    PowerPoint.PpSaveAsFileType.ppSaveAsOpenXMLPresentation,
                    Office.MsoTriState.msoTriStateMixed);
                oPre.Close();

            // 退出PowerPoint应用程序

                Console.WriteLine("退出PowerPoint应用程序");
                oPowerPoint.Quit();
            }
            catch (Exception ex)
            {
                Console.WriteLine("解决方案2.AutomatePowerPoint抛出的错误: {0}",
                    ex.Message);
            }
        }
Пример #22
0
        public static void convert(int coursewareId, int userId, String inputFileName)
        {
            //输入文件的所在文件夹路径(ppt所在文件夹)
            string inputFilePath = System.Configuration.ConfigurationManager.AppSettings["FILE_SERVER_PATH"] + "input\\" + coursewareId + "\\";
            string inputFilePathName = inputFilePath + inputFileName;

            //输出图片文件夹路径
            string outputFilePath = System.Configuration.ConfigurationManager.AppSettings["FILE_SERVER_PATH"] + "output\\" + coursewareId + "\\pic\\";
            //输出图片的宽度
            int outputPicWidth = int.Parse(System.Configuration.ConfigurationManager.AppSettings["PPT_OUTPUT_PIC_WIDTH"]);
            //输出图片的高度
            int outputPicHeight = int.Parse(System.Configuration.ConfigurationManager.AppSettings["PPT_OUTPUT_PIC_HEIGHT"]);

            if (!Directory.Exists(outputFilePath))
            {
                Directory.CreateDirectory(outputFilePath);
            }

            PowerPoint.Application pptApplication = new PowerPoint.Application();
            //记录日志(目前暂记录到系统日志中,可考虑写到数据库)
            EventLog.WriteEntry("ppt-start", "try convert " + inputFilePathName);

            PowerPoint.Presentation ppt = pptApplication.Presentations.Open(inputFilePathName,

                                    Microsoft.Office.Core.MsoTriState.msoTrue,

                                    Microsoft.Office.Core.MsoTriState.msoFalse,

                                    Microsoft.Office.Core.MsoTriState.msoFalse);

            PowerPoint.Presentation pptPresentation = pptApplication.Presentations.Open(inputFilePathName, MsoTriState.msoFalse,
            MsoTriState.msoFalse, MsoTriState.msoFalse);

            string fileNameTmp = coursewareId + "_{0}.jpg";
            for (int i = 1; i <= ppt.Slides.Count; i++)
            {//循环保存每帧图片
                string fileName = string.Format(fileNameTmp, i);
                //输出到文件
                ppt.Slides[i].Export(outputFilePath + fileName, "jpg", outputPicWidth, outputPicHeight);
                //保存到数据库
                PptDao.savePptImage(userId, coursewareId, i, "/res/data/coursewarePkg/output/" + coursewareId + "/pic/" + fileName);
            }
            EventLog.WriteEntry("ppt-complete", "convert complete " + inputFilePathName);

            ppt.Close();

            pptApplication.Quit();
        }
Пример #23
0
        public void Clean()
        {
            if (this.presentation != null && this.powerpoint != null)
            {
                //this.presentation.Close();
                //Marshal.ReleaseComObject(this.presentation);

                //this.powerpoint.Quit();
                //Marshal.ReleaseComObject(this.powerpoint);

                this.powerpoint = null;
                this.presentation = null;

                this.KillPowerPoint();
            }
        }
Пример #24
0
        static void Main(string[] args)
        {
            string out_format = "PDF";
            bool   optimize_for_screen = false;
            List<string> files = (new OptionSet{
                { "xps"   , v => { if (v != null) out_format = "XPS";         } },
                { "pdf"   , v => { if (v != null) out_format = "PDF";         } },
                { "screen", v => { if (v != null) optimize_for_screen = true; } }
            }).Parse(args);

            var rx_ppt = new Regex(@"\.(pptx|ppt|pptm|ppsx|pps|ppsm|potx|pot|potm|odp)$", RegexOptions.IgnoreCase);
            var rx_doc = new Regex(@"\.(docx|docm|dotx|dotm|doc|dot|htm|html|rtf|mht|mhtml|xml|odt)$", RegexOptions.IgnoreCase);

            PowerPoint.Application ppt = null;
            Word.Application       wrd = null;
            foreach (var i in files)
            {
                try
                {
                    var file = Path.GetFullPath(i);
                    if (rx_ppt.IsMatch(file))
                    {
                        if (ppt == null) ppt = new PowerPoint.Application();
                        PowerPoint.Presentation p = ppt.Presentations.Open(file, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
                        string dst = getAvailableFileName(out_format == "PDF" ? getPDFName(file) : getXPSName(file));
                        p.SaveCopyAs(dst, out_format == "PDF" ? PowerPoint.PpSaveAsFileType.ppSaveAsPDF : PowerPoint.PpSaveAsFileType.ppSaveAsXPS, MsoTriState.msoTrue);
                        p.Close();
                    }
                    else if (rx_doc.IsMatch(file))
                    {
                        if (wrd == null) wrd = new Word.Application();
                        Word.Document d = wrd.Documents.Open(file, false, true);
                        string dst = getAvailableFileName(out_format == "PDF" ? getPDFName(file) : getXPSName(file));
                        d.ExportAsFixedFormat(dst, out_format == "PDF" ? Word.WdExportFormat.wdExportFormatPDF : Word.WdExportFormat.wdExportFormatXPS, false, optimize_for_screen ? Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen : Word.WdExportOptimizeFor.wdExportOptimizeForPrint);
                        d.Close(false);
                    }
                    else
                    {
                        Console.Error.WriteLine("Unknown file type: " + i);
                    }
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine(e.Message);
                }
            }
        }
Пример #25
0
 public void Setup()
 {
     CultureUtil.SetDefaultCulture(CultureInfo.GetCultureInfo("en-US"));
     try
     {
         App = new PowerPoint.Application();
     }
     catch (COMException)
     {
         // in case a warm-up is needed
         App = new PowerPoint.Application();
     }
     Pres = App.Presentations.Open(
         PathUtil.GetDocTestPath() + GetTestingSlideName(),
         WithWindow: MsoTriState.msoFalse);
     PpOperations = new UnitTestPpOperations(Pres, App);
 }
Пример #26
0
 public static new Boolean Convert(String inputFile, String outputFile) {
     Microsoft.Office.Interop.PowerPoint.Application app;
     try {
         app = new Microsoft.Office.Interop.PowerPoint.Application();
         app.Visible = MSCore.MsoTriState.msoTrue;
         app.Presentations.Open(inputFile, MSCore.MsoTriState.msoFalse, MSCore.MsoTriState.msoTrue, MSCore.MsoTriState.msoTrue);
         app.ActivePresentation.SaveAs(outputFile, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPDF, MSCore.MsoTriState.msoCTrue);
         app.ActivePresentation.Close();
         app.Quit();
         return true;
     } catch (Exception e) {
         Console.WriteLine(e.Message);
         return false;
     } finally {
         app = null;
     }
 }
        public string ExportSlides(string fileName, BackgroundWorker bckgWorker)
        {
            string retVal = "";
            Presentation pptfile = null;
            try
            {
                var app = new Microsoft.Office.Interop.PowerPoint.Application();
                var pres = app.Presentations;
                pptfile = pres.Open(fileName, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse);
                //Exporting slides to the folder where the PPTX file is, in the subfolder named as the presentation

                ////Exporting all in one take, no progress bar feedback, aprox 2% faster
                //string savePath = Path.GetDirectoryName(fileName) + "\\" + Path.GetFileNameWithoutExtension(fileName) + ".png";
                //pptfile.SaveCopyAs(savePath, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPNG, Microsoft.Office.Core.MsoTriState.msoTrue);

                //Exporting slide by slide, able to provide progress bar feedback
                string savePath = Path.GetDirectoryName(fileName) + "\\" + Path.GetFileNameWithoutExtension(fileName);
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }
                string picFileName = null;
                int numOfSlides = pptfile.Slides.Count;
                for (int i = 1; i <= numOfSlides; i++)
                {
                    picFileName = savePath + "\\" + "Slide" + i.ToString() + ".png";
                    pptfile.Slides[i].Export(picFileName, "PNG");
                    float progress = (((float)i / numOfSlides)) * 30;
                    bckgWorker.ReportProgress((int)progress);

                }

                retVal = "OK";
            }
            catch (Exception ex)
            {
                AddToLog("Problem with exporting slide pictures. " + ex.Message);
                MessageBox.Show("Problem with exporting slide pictures. Try closing Microsoft Office programs if you have multiple open. " + ex.Message);
                retVal = ex.Message;
            }
            finally
            {
                pptfile.Close();
            }
            return retVal;
        }
Пример #28
0
        public void Parse(object src, object dest)
        {
            if (src == null || string.IsNullOrEmpty(src.ToString()))
            {
                throw new ArgumentNullException("源文件不能为空");
            }
            if (dest == null || string.IsNullOrEmpty(dest.ToString()))
            {
                throw new ArgumentNullException("目标路径不能为空");
            }
            try
            {
                presentation = pptApp.Presentations.Open(src.ToString(), Microsoft.Office.Core.MsoTriState.msoTrue
                , Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);

                presentation.ExportAsFixedFormat(dest.ToString(), PpFixedFormatType.ppFixedFormatTypePDF, PpFixedFormatIntent.ppFixedFormatIntentScreen
                    , Microsoft.Office.Core.MsoTriState.msoFalse, PpPrintHandoutOrder.ppPrintHandoutHorizontalFirst, PpPrintOutputType.ppPrintOutputSlides
                    , Microsoft.Office.Core.MsoTriState.msoFalse, null, PpPrintRangeType.ppPrintAll, string.Empty, false
                    , false, false, true, true, missing);
            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {
                if (presentation != null)
                {
                    presentation.Close();
                    presentation = null;
                }

                if (pptApp != null)
                {
                    pptApp.Quit();
                    pptApp = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
		public void TestGetVersionNumber()
		{
			TestClassForOfficeApplicationVersion test = new TestClassForOfficeApplicationVersion();

			Word.Application myWord = new Word.Application();
			Assert.AreEqual(test.GetVersionFromAppType(testenum.AppWord, myWord), test.GetInstalledWordVersion(), "Versions are different for Word");
			myWord.Quit();
			Marshal.ReleaseComObject(myWord);

			PowerPoint.Application myPPT = new PowerPoint.Application();
			Assert.AreEqual(test.GetVersionFromAppType(testenum.AppPowerPoint, myPPT), test.GetInstalledPowerPointVersion(), "Versions are different for PowerPoint");
			Marshal.ReleaseComObject(myPPT);

			Excel.Application myExcel = new Excel.Application();
			Assert.AreEqual(test.GetVersionFromAppType(testenum.AppExcel, myExcel), test.GetInstalledExcelVersion(), "Versions are different for Excel");
			Marshal.ReleaseComObject(myExcel);

			GC.Collect();
		}
Пример #30
0
        public override string Read()
        {
            try
            {
                powerPointApp = new PowerPoint.Application();
                powerPointApp.Visible = MsoTriState.msoFalse;
                multiPresentations = powerPointApp.Presentations;

                MsoTriState trueState = MsoTriState.msoTrue;
                MsoTriState falseState = MsoTriState.msoFalse;
                string filePath = (string)FilePath;

                presentation = multiPresentations.Open(filePath,
                                                       trueState,
                                                       falseState,
                                                       falseState);

                string result = string.Empty;

                for (int i = 0; i < presentation.Slides.Count; i++)
                {
                    foreach (var item in presentation.Slides[i + 1].Shapes)
                    {
                        var shape = (PowerPoint.Shape)item;
                        if (shape.HasTextFrame == MsoTriState.msoTrue && shape.TextFrame.HasText == MsoTriState.msoTrue)
                        {
                            var textRange = shape.TextFrame.TextRange;
                            result += textRange.Text;
                        }
                    }
                }

                powerPointApp.Quit();

                return result;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Пример #31
0
        static private void RasterizeDirectory(string pptxRoot, string outputDir)
        {
            var           pptApp           = new PPT.Application();
            string        directory        = pptxRoot;
            var           pptxFiles        = Directory.EnumerateFiles(directory, "*.pptx", SearchOption.TopDirectoryOnly);
            List <string> failedFiles      = new List <string>();
            List <string> successFiles     = new List <string>();
            List <string> failedFinalFiles = new List <string>();
            StreamWriter  catalogWriter    = File.CreateText(outputDir + "Failed.txt");

            const int batchSize    = 5;
            int       indexInBatch = 0;

            foreach (string currentFile in pptxFiles)
            {
                bool fSaved = false;
                try
                {
                    RasterizeOne(pptApp, currentFile, directory, outputDir);
                    successFiles.Add(currentFile);
                    fSaved = true;
                    indexInBatch++;
                    if (indexInBatch == batchSize)
                    {
                        indexInBatch = 0;
                        pptApp.Quit();
                        pptApp = null;
                        pptApp = new PPT.Application();
                    }
                }
                catch (Exception e)
                {
                    if (!fSaved)
                    {
                        failedFiles.Add(currentFile);
                    }
                    Console.WriteLine(e.Message);
                    if ((uint)e.HResult == 0x0800706ba)
                    {
                        pptApp       = new PPT.Application();
                        indexInBatch = 0;
                    }
                }
            }

            indexInBatch = 0;
            foreach (string currentFile in failedFiles)
            {
                try
                {
                    RasterizeOne(pptApp, currentFile, directory, outputDir);
                    successFiles.Add(currentFile);
                    indexInBatch++;
                    if (indexInBatch == batchSize)
                    {
                        indexInBatch = 0;
                        pptApp.Quit();
                        Thread.Sleep(1000);
                        pptApp = new PPT.Application();
                    }
                }
                catch (Exception e)
                {
                    failedFinalFiles.Add(currentFile);
                    catalogWriter.WriteLine(currentFile);
                    catalogWriter.WriteLine(e.Message);
                }
            }
            catalogWriter.Flush();
        }
Пример #32
0
        public static bool convertToNewOfficeDocument(string fileName, out string newFileName, out string newExt)
        {
            string ext = Path.GetExtension(fileName);

            newExt = ext;


            newFileName = fileName;


            if (!destinationDictionary.ContainsKey(ext))
            {
                return(false);
            }

            officeDestination dest = destinationDictionary[ext];

            newExt = dest.Extension;

            newFileName = fileName.Replace(ext, dest.Extension);

            object obj;

            bool result = true;

            switch (dest.Application)
            {
            case officeApplication.Word:
                Word._Application wordApp = new Word.Application();
                Word._Document    wordDoc = null;

                try
                {
                    wordDoc = wordApp.Documents.Open(fileName);
                    wordDoc.Convert();
                    wordDoc.SaveAs(newFileName, dest.FileFormat);
                }
                catch (Exception e)
                {
                    displayError(fileName, e);
                    newFileName = fileName;
                    result      = false;
                }
                finally
                {
                    wordDoc.Close();
                    wordApp.Quit();
                    obj = (object)wordDoc;
                    disposeInteropObject(ref obj);
                    obj = (object)wordApp;
                    disposeInteropObject(ref obj);
                }
                break;

            case officeApplication.Excel:
                Excel._Application excelApp = new Excel.Application();
                Excel._Workbook    excelDoc = null;
                try
                {
                    excelDoc = excelApp.Workbooks.Open(fileName);
                    excelDoc.SaveAs(newFileName, dest.FileFormat);
                }
                catch (Exception e)
                {
                    displayError(fileName, e);
                    newFileName = fileName;
                    result      = false;
                }
                finally
                {
                    excelDoc.Close();
                    excelApp.Quit();
                    obj = (object)excelDoc;
                    disposeInteropObject(ref obj);
                    obj = (object)excelApp;
                    disposeInteropObject(ref obj);
                }
                break;

            case officeApplication.PowerPoint:
                PowerPoint._Application  powerpointApp = new PowerPoint.Application();
                PowerPoint._Presentation powerpointDoc = null;
                try
                {
                    powerpointDoc = powerpointApp.Presentations.Open(fileName, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse);
                    powerpointDoc.SaveAs(newFileName, (PowerPoint.PpSaveAsFileType)dest.FileFormat);
                }
                catch (Exception e)
                {
                    displayError(fileName, e);
                    newFileName = fileName;
                    result      = false;
                }
                finally
                {
                    powerpointDoc.Close();
                    powerpointApp.Quit();
                    obj = (object)powerpointDoc;
                    disposeInteropObject(ref obj);
                    obj = (object)powerpointApp;
                    disposeInteropObject(ref obj);
                }
                break;
            }

            GC.Collect();
            return(result);
        }
Пример #33
0
 public PowerPoint2003OfficeDocument(PowerPoint.Presentation presentation)
 {
     this.presentation = presentation;
     this.application  = this.presentation.Application;
 }
Пример #34
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < 8; i++)
            {
                pptApplication = PPT.TryGetApplication();
                if (pptApplication != null)
                {
                    break;
                }
                System.Threading.Thread.Sleep(2000);
            }
            if (pptApplication == null)
            {
                WdMessageBox.Display("错误", "即将关闭,请打开PPT再打开本软件");
                App.Current.Shutdown();
            }

            //获得演示文稿对象
            presentation = pptApplication.ActivePresentation;
            // 获得幻灯片对象集合
            slides = presentation.Slides;
            // 获得幻灯片的数量
            slidesCount = slides.Count;

            inks = new InkCanvas[slidesCount + 1];//slideIndex从1开始
            for (int i = 0; i < inks.Length; i++)
            {
                inks[i] = new InkCanvas
                {
                    Background = new SolidColorBrush(Color.FromArgb(1, 0, 0, 0)),
                };
                inks[i].SetValue(Grid.RowSpanProperty, 2);
                GMain.Children.Add(inks[i]);
            }
            Canvas.SetZIndex(GBottom, 1);
            DispatcherTimer dispatcherTimer = new DispatcherTimer()
            {
                Interval = TimeSpan.FromSeconds(1), IsEnabled = true
            };

            dispatcherTimer.Tick += (sder, arg) =>
            {
                if (!IsPPtOpened())
                {
                    PPtClosed();
                    return;
                }
                UpdateSlideIndex();

                if (!IsPPtOpened())
                {
                    PPtClosed();
                    return;
                }
                try
                {
                    TbInfo.Text = $"name={presentation.Name}{Environment.NewLine}" +
                                  $"slideIndex={slideIndex}";
                    string s = slideIndex.ToString() + "/" + slidesCount.ToString();
                    LbLeft.Content  = s;
                    LbRight.Content = s;
                }
                catch (Exception ex)
                {
                    TLib.Software.Logger.WriteException(ex);
                }
            };
            Color[] colors = new Color[] { Colors.Black, Colors.DarkGray, Colors.Gray, Colors.LightGray, Colors.White,
                                           Colors.Red, Colors.OrangeRed, Colors.Orange, Colors.Gold, Colors.Yellow,
                                           Colors.LawnGreen, Colors.Green, Colors.SeaGreen, Colors.DeepSkyBlue, Colors.Blue,
                                           Colors.Tomato, Colors.Violet, Colors.LightYellow, Colors.LightGreen, Colors.LightBlue,
                                           Colors.Pink, Colors.RosyBrown, Colors.Chocolate, Colors.Brown, Colors.Purple, };
            for (int i = 0; i < btnsColor.Length; i++)
            {
                btnsColor[i] = new Button
                {
                    Background = new SolidColorBrush(colors[i]),
                    Name       = "BtnColor" + i
                };
                btnsColor[i].Click += (s, arg) =>
                {
                    Button b     = (Button)s;
                    int    index = int.Parse(b.Name.Substring(8));
                    for (int t = 0; t < btnsColor.Length; t++)
                    {
                        if (index == t)
                        {
                            btnsColor[t].BorderThickness = new Thickness(2);
                        }
                        else
                        {
                            btnsColor[t].BorderThickness = new Thickness(0);
                        }
                    }
                    foreach (var item in inks)
                    {
                        item.DefaultDrawingAttributes.Color = colors[index];
                    }
                };
                UGColor.Children.Add(btnsColor[i]);
                //Grid.SetColumn(btns[i],0);
                //Grid.SetRow(btns[i], 0);
            }
            SelectedIndex = 0;//默认选择鼠标模式
        }
Пример #35
0
 public void OpenPPT(string filename)
 {
     pptApplication = new PowerPoint.Application();
     multi_p        = pptApplication.Presentations;
     presentation   = multi_p.Open(filename);
 }
Пример #36
0
 public static void WarnForTweeter_PresentationOpen(Application powerpointApplication, Presentation presentation)
 {
     warnForTwitter();
 }
Пример #37
0
        public static void RemoveMenu(object objApp, string appName, Office.CommandBar cbar, string menuName, string Name)
        {
            Office.CommandBars cbars = null;

            try
            {
                switch (appName)
                {
                case "Microsoft Excel":
                    MsoExcel.Application appExcel = (MsoExcel.Application)objApp;
                    cbars = appExcel.CommandBars;
                    break;

                case "Microsoft PowerPoint":
                    MsoPowerPoint.Application appPowerPoint = (MsoPowerPoint.Application)objApp;
                    cbars = appPowerPoint.CommandBars;
                    break;

                case "Microsoft Project":
                    MsoProject.Application appProject = (MsoProject.Application)objApp;
                    cbars = appProject.CommandBars;
                    break;

                case "Microsoft Visio":
                    MsoVisio.Application appVisio = (MsoVisio.Application)objApp;
                    cbars = (Office.CommandBars)appVisio.CommandBars;
                    break;

                case "Microsoft Word":
                    MsoWord.Application appWord = (MsoWord.Application)objApp;
                    cbars = appWord.CommandBars;
                    break;

                // TODO: There is no ActiveExplorer when we exit app.  How to handle?
                //case "Outlook":
                //    Outlook.Application appOutlook = (Outlook.Application)objApp;
                //    Outlook.Explorer explorer = appOutlook.ActiveExplorer();
                //    cbars = explorer.CommandBars;
                //    break;

                default:
                    MessageBox.Show("RemoveMenu:Unknown appName->" + appName + "<");
                    return;
                }

                cbar = cbars[menuName];

                foreach (Office.CommandBarControl cbc in cbar.Controls)
                {
                    if (cbc.Caption == Name)
                    {
                        cbc.Delete(Missing.Value);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                throw;
            }
        }
Пример #38
0
        public static void AutomatePowerPoint()
        {
            PowerPoint.Application   oPowerPoint = null;
            PowerPoint.Presentations oPres       = null;
            PowerPoint.Presentation  oPre        = null;
            PowerPoint.Slides        oSlides     = null;
            PowerPoint.Slide         oSlide      = null;
            PowerPoint.Shapes        oShapes     = null;
            PowerPoint.Shape         oShape      = null;
            PowerPoint.TextFrame     oTxtFrame   = null;
            PowerPoint.TextRange     oTxtRange   = null;

            try
            {
                // 创建一个Microsoft PowerPoint实例并使其不可见。

                oPowerPoint = new PowerPoint.Application();

                // 默认情况下PowerPoint不可见,直道你使它可见。
                //oPowerPoint.Visible = Office.MsoTriState.msoFalse;

                // 创建一个新的演示文稿。

                oPres = oPowerPoint.Presentations;
                oPre  = oPres.Add(Office.MsoTriState.msoTrue);
                Console.WriteLine("一个新的演示文稿被建立");

                // 插入一个幻灯片,并为幻灯片加入一些文本。

                Console.WriteLine("插入一个幻灯片");
                oSlides = oPre.Slides;
                oSlide  = oSlides.Add(1, PowerPoint.PpSlideLayout.ppLayoutText);

                Console.WriteLine("添加一些文本");
                oShapes        = oSlide.Shapes;
                oShape         = oShapes[1];
                oTxtFrame      = oShape.TextFrame;
                oTxtRange      = oTxtFrame.TextRange;
                oTxtRange.Text = "一站式代码框架";

                // 保存此演示文稿为pptx文件并将其关闭。

                Console.WriteLine("保存并退出演示文稿");

                string fileName = Path.GetDirectoryName(
                    Assembly.GetExecutingAssembly().Location) + "\\Sample1.pptx";
                oPre.SaveAs(fileName,
                            PowerPoint.PpSaveAsFileType.ppSaveAsOpenXMLPresentation,
                            Office.MsoTriState.msoTriStateMixed);
                oPre.Close();

                // 退出PowerPoint应用程序

                Console.WriteLine("退出PowerPoint应用程序");
                oPowerPoint.Quit();
            }
            catch (Exception ex)
            {
                Console.WriteLine("解决方案1.AutomatePowerPoint抛出的错误: {0}",
                                  ex.Message);
            }
            finally
            {
                // 显式地调用Marshal.FinalReleaseComObject访问所有的存取器对象清除
                // 非托管的COM资源。
                // 参见http://support.microsoft.com/kb/317109

                if (oTxtRange != null)
                {
                    Marshal.FinalReleaseComObject(oTxtRange);
                    oTxtRange = null;
                }
                if (oTxtFrame != null)
                {
                    Marshal.FinalReleaseComObject(oTxtFrame);
                    oTxtFrame = null;
                }
                if (oShape != null)
                {
                    Marshal.FinalReleaseComObject(oShape);
                    oShape = null;
                }
                if (oShapes != null)
                {
                    Marshal.FinalReleaseComObject(oShapes);
                    oShapes = null;
                }
                if (oSlide != null)
                {
                    Marshal.FinalReleaseComObject(oSlide);
                    oSlide = null;
                }
                if (oSlides != null)
                {
                    Marshal.FinalReleaseComObject(oSlides);
                    oSlides = null;
                }
                if (oPre != null)
                {
                    Marshal.FinalReleaseComObject(oPre);
                    oPre = null;
                }
                if (oPres != null)
                {
                    Marshal.FinalReleaseComObject(oPres);
                    oPres = null;
                }
                if (oPowerPoint != null)
                {
                    Marshal.FinalReleaseComObject(oPowerPoint);
                    oPowerPoint = null;
                }
            }
        }
Пример #39
0
    // Insert logic for processing found files here.
    public static void ProcessFile(string path, string tipo, string dpto, bool actualizar)
    {
        bool indexatexto = false, indexaaudio = false, indexaimagen = false, indexahipertexto = false, indexavideo = false;

        Random rnd = new Random();


        switch (tipo)
        {
        case "texto":
            indexatexto = true;
            break;

        case "hipertexto":
            indexahipertexto = true;
            break;

        case "video":
            indexavideo = true;
            break;

        case "imagen":
            indexaimagen = true;
            break;

        case "audio":
            indexaaudio = true;
            break;

        case "":
            indexatexto      = true;
            indexahipertexto = true;
            indexavideo      = true;
            indexaimagen     = true;
            indexaaudio      = true;
            break;
        }


        if (Herramientas.EsHiperTexto(path) && indexatexto && path.Contains(dpto))
        {
            Regex           trimmer = new Regex(@"\s\s+");
            ScrapingBrowser Browser = new ScrapingBrowser();
            Browser.AllowAutoRedirect = true; // Browser has settings you can access in setup
            Browser.AllowMetaRedirect = true;
            HtmlNode html = GetNodes(new Uri(path));

            var titulo = html.CssSelect("title").FirstOrDefault().InnerText;
            var body   = html.CssSelect("body").FirstOrDefault().InnerText;

            body = Regex.Replace(body, "<.*?>", string.Empty);
            body = Regex.Replace(body, @"(?:(?:\r?\n)+ +){2,}", @"\n");

            var f = new FileInfo(path);
            var fileLengthInKB = f.Length / 1024.0;

            Hipertexto h = new Hipertexto();
            h.nombreArchivo  = titulo;
            h.textoContenido = body;
            h.tamanoArchivo  = fileLengthInKB;

            Uri    u        = new Uri(path);
            string ext      = System.IO.Path.GetExtension(path);
            string auxiliar = "http://localhost/servidores/";
            h.urlRuta = u.AbsoluteUri;
            var    puerto = u.Port;
            int    pos    = h.urlRuta.IndexOf("servidores/") + 11;
            string aux2   = h.urlRuta.Substring(pos);
            int    pos2   = aux2.IndexOf("/");
            h.urlRuta = auxiliar + aux2;
            string servidor = aux2.Substring(0, pos2);
            int    pos3     = aux2.IndexOf(servidor + "/") + servidor.Length + 1;

            string depart = aux2.Substring(pos3);
            int    pos4   = depart.IndexOf("/");
            depart = depart.Substring(0, pos4);
            depart = depart.Replace("%20", " ");

            h.departamento             = depart;
            h.urlRuta                  = auxiliar + aux2;
            h.tamanoArchivo            = fileLengthInKB;
            h.formato                  = ext;
            h.idServidor               = servidor;
            h.nombreArchivo            = System.IO.Path.GetFileName(path);
            h.fechaCreacionArchivo     = (DateTime)File.GetCreationTime(path);
            h.fechaModificacionArchivo = (DateTime)File.GetLastWriteTime(path);
            h.fechaUltimaLectura       = (DateTime)File.GetLastAccessTime(path);
            h.fechaUltimaActualizacion = DateTime.Now;
            h.hits = rnd.Next(1, 55);

            if (File.Exists(path))
            {
                h.estadoActividad = 1;
            }

            Hipertexto existente = OperacionesElasticSearch.ExisteHipertexto(h);
            if (existente == null)
            {
                OperacionesElasticSearch.InsertarHiperTexto(h);
            }
            else
            {
                OperacionesElasticSearch.actualizarHipertexto(existente, h);
            }
        }
        else if (path.EndsWith(".txt") && indexatexto && path.Contains(dpto))
        {
            var    f = new FileInfo(path);
            var    fileLengthInKB = f.Length / 1024.0;
            Uri    u        = new Uri(path);
            Texto  t        = new Texto();
            string ext      = System.IO.Path.GetExtension(path);
            string auxiliar = "http://localhost/servidores/";
            t.urlRuta = u.AbsoluteUri;
            var    puerto = u.Port;
            int    pos    = t.urlRuta.IndexOf("servidores/") + 11;
            string aux2   = t.urlRuta.Substring(pos);
            t.urlRuta = auxiliar + aux2;
            int    pos2     = aux2.IndexOf("/");
            string servidor = aux2.Substring(0, pos2);
            int    pos3     = aux2.IndexOf(servidor + "/") + servidor.Length + 1;

            string depart = aux2.Substring(pos3);
            int    pos4   = depart.IndexOf("/");
            depart = depart.Substring(0, pos4);
            depart = depart.Replace("%20", " ");

            string textoContenido = System.IO.File.ReadAllText(path);
            string user           = System.IO.File.GetAccessControl(path).GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();
            t.estadoActividad          = 1;
            t.departamento             = depart;
            t.urlRuta                  = auxiliar + aux2;
            t.tamanoArchivo            = fileLengthInKB;
            t.idServidor               = servidor;
            t.textoContenido           = textoContenido;
            t.titulo                   = t.nombreArchivo;
            t.formato                  = ext;
            t.nombreArchivo            = System.IO.Path.GetFileName(path);
            t.fechaCreacionArchivo     = (DateTime)File.GetCreationTime(path);
            t.fechaModificacionArchivo = (DateTime)File.GetLastWriteTime(path);
            t.fechaUltimaLectura       = (DateTime)File.GetLastAccessTime(path);
            t.fechaUltimaActualizacion = DateTime.Now;
            t.hits         = rnd.Next(1, 55);
            t.autorArchivo = user;


            Texto existente = OperacionesElasticSearch.ExisteTexto(t);
            if (existente == null)
            {
                OperacionesElasticSearch.InsertarTexto(t);
            }
            else
            {
                OperacionesElasticSearch.actualizarTexto(existente, t);
            }
        }
        else if (Herramientas.EsWord(path) && indexatexto && path.Contains(dpto))
        {
            var f = new FileInfo(path);
            var fileLengthInKB = f.Length / 1024.0;

            var applicationWord = new Microsoft.Office.Interop.Word.Application();
            applicationWord.Visible = false;
            Word.Document w = applicationWord.Documents.Open(@path, ReadOnly: true);
            Word.Range    ContentTypeProperties = w.Content;

            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            object miss = System.Reflection.Missing.Value;

            object readOnly = true;
            Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);


            //Get Author Name
            object wordProperties = docs.BuiltInDocumentProperties;

            Type   typeDocBuiltInProps = wordProperties.GetType();
            Object Authorprop          = typeDocBuiltInProps.InvokeMember("Item", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.GetProperty, null, wordProperties, new object[] { "Author" });//query for author properties
            Type   typeAuthorprop      = Authorprop.GetType();
            //string strAuthor = typeAuthorprop.InvokeMember("Value", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.GetProperty, null, Authorprop, new object[] { }).ToString();//get author name

            string textoContenido = "";
            for (int i = 0; i < docs.Paragraphs.Count; i++)
            {
                textoContenido += " \r\n " + docs.Paragraphs[i + 1].Range.Text.ToString();
            }
            Uri    u   = new Uri(path);
            Texto  t   = new Texto();
            string ext = System.IO.Path.GetExtension(path);

            string auxiliar = "http://localhost/servidores/";
            t.urlRuta = u.AbsoluteUri;
            var    puerto = u.Port;
            int    pos    = t.urlRuta.IndexOf("servidores/") + 11;
            string aux2   = t.urlRuta.Substring(pos);
            t.urlRuta = auxiliar + aux2;
            int    pos2     = aux2.IndexOf("/");
            string servidor = aux2.Substring(0, pos2);
            int    pos3     = aux2.IndexOf(servidor + "/") + servidor.Length + 1;

            string depart = aux2.Substring(pos3);
            int    pos4   = depart.IndexOf("/");
            depart = depart.Substring(0, pos4);
            depart = depart.Replace("%20", " ");


            t.departamento             = depart;
            t.urlRuta                  = auxiliar + aux2;
            t.tamanoArchivo            = fileLengthInKB;
            t.idServidor               = servidor;
            t.textoContenido           = textoContenido;
            t.titulo                   = t.nombreArchivo;
            t.formato                  = ext;
            t.nombreArchivo            = System.IO.Path.GetFileName(path);
            t.fechaCreacionArchivo     = (DateTime)File.GetCreationTime(path);
            t.fechaModificacionArchivo = (DateTime)File.GetLastWriteTime(path);
            t.fechaUltimaLectura       = (DateTime)File.GetLastAccessTime(path);
            t.fechaUltimaActualizacion = DateTime.Now;
            t.hits = rnd.Next(1, 55);

            if (File.Exists(path))
            {
                t.estadoActividad = 1;
            }

            w.Close();


            Texto existente = OperacionesElasticSearch.ExisteTexto(t);
            if (existente == null)
            {
                OperacionesElasticSearch.InsertarTexto(t);
            }
            else
            {
                OperacionesElasticSearch.actualizarTexto(existente, t);
            }
        }
        else if (Herramientas.EsExcel(path) && indexatexto && path.Contains(dpto))
        {
            /*Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
             * Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Open(@path, ReadOnly: true);
             *
             * var f = new FileInfo(path);
             * var fileLengthInKB = f.Length / 1024.0;
             *
             * //Create COM Objects. Create a COM object for everything that is referenced
             * Excel.Application xlApp = new Excel.Application();
             * Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(path);
             * Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[0];
             * Excel.Range xlRange = xlWorksheet.UsedRange;
             * int rowCount = xlRange.Rows.Count;
             * int colCount = xlRange.Columns.Count;
             * //iterate over the rows and columns and print to the console as it appears in the file
             * //excel is not zero based!!
             * //Get Author Name
             * String autor = wb.Author;
             *
             * String textoContenido = "";
             * for (int i = 1; i <= rowCount; i++)
             * {
             *  for (int j = 1; j <= colCount; j++)
             *  {
             *      //new line
             *      if (j == 1)
             *          Console.Write("\r\n");
             *
             *      //write the value to the console
             *      if ((Excel.Range)xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null)
             *          textoContenido += xlRange.Cells[i, j].Value2.ToString() + " ";
             *
             *      //add useful things here!
             *  }
             * }
             *
             * xlWorkbook.Close();
             * Uri u = new Uri(path);
             *
             * Texto t = new Texto();
             * t.urlRuta = u.AbsoluteUri;
             * string ext = System.IO.Path.GetExtension(path);
             *
             * string auxiliar = "http://localhost/servidorIntranet/";
             * h.urlRuta = u.AbsoluteUri;
             * var puerto = u.Port;
             * int pos = h.urlRuta.IndexOf("servidores/") + 11 ;
             * string aux2 = h.urlRuta.Substring(pos);
             * t.urlRuta = auxiliar + aux2;
             * int pos2 = aux2.IndexOf("/");
             * string servidor = aux2.Substring(0, pos2);
             * int pos3 = aux2.IndexOf(servidor + "/") + servidor.Length + 1;
             *
             * string depart = aux2.Substring(pos3);
             * int pos4 = depart.IndexOf("/");
             * depart = depart.Substring(0, pos4);
             * depart = depart.Replace("%20", " ");
             *
             * string depart = aux2.Substring(pos3);
             * int pos4 = depart.IndexOf("/");
             * depart = depart.Substring(0, pos4);
             * depart = depart.Replace("%20", " ");
             * t.departamento = depart;
             *
             * t.idServidor = servidor;
             * t.urlRuta = u.AbsoluteUri;
             * t.tamanoArchivo = fileLengthInKB;
             * t.textoContenido = textoContenido;
             * t.titulo = t.nombreArchivo;
             * t.formato = ext;
             * t.nombreArchivo = System.IO.Path.GetFileName(path);
             * t.fechaCreacionArchivo = (DateTime)File.GetCreationTime(path);
             * t.fechaModificacionArchivo = (DateTime)File.GetLastWriteTime(path);
             * t.fechaUltimaLectura = (DateTime)File.GetLastAccessTime(path);
             * t.fechaUltimaActualizacion = DateTime.Now;
             * t.hits = 0;
             *
             * if (File.Exists(path))
             *  t.estadoActividad = 1;
             *
             * Texto existente = OperacionesElasticSearch.ExisteTexto(t);
             * if (existente == null)
             *  OperacionesElasticSearch.InsertarTexto(t);
             * else
             *  OperacionesElasticSearch.actualizarTexto(existente, t);
             *
             */
        }
        else if (Herramientas.EsPDF(path) && indexatexto && path.Contains(dpto))
        {
            var text = new TextExtractor().Extract(path).Text;
            text = Regex.Replace(text, @"\s+", " ");
            text = text.Replace("\r", "");
            text = text.Replace("\n", "");

            PDFParser pdfParser = new PDFParser();

            var f = new FileInfo(path);
            var fileLengthInKB = f.Length / 1024.0;

            // extract the text
            String resultado = "";
            pdfParser.ExtractText(path, "C:\\Users\\cesar\\Desktop\\DocumentosIndeaxar\\salida.txt");
            resultado = pdfParser.ToString();

            String autor          = "";
            String textoContenido = "";
            String titulo         = "";


            using (PdfReader reader = new PdfReader(path)){
                //titulo = reader.Info["Title"];
                //String ayt = reader.Info["Author"];
                titulo = "";

                StringBuilder text2 = new StringBuilder();

                for (int i = 1; i <= reader.NumberOfPages; i++)
                {
                    text2.Append(PdfTextExtractor.GetTextFromPage(reader, i));
                }

                textoContenido = text.ToString();
            }

            Texto t = new Texto();
            Uri   u = new Uri(path);

            t.urlRuta = u.AbsoluteUri;
            string auxiliar = "http://localhost/servidores/";
            t.urlRuta = u.AbsoluteUri;
            var puerto = u.Port;
            int pos    = t.urlRuta.IndexOf("servidores/") + 11;

            string aux2 = t.urlRuta.Substring(pos);
            t.urlRuta = auxiliar + aux2;
            int    pos2     = aux2.IndexOf("/");
            string servidor = aux2.Substring(0, pos2);
            int    pos3     = aux2.IndexOf(servidor + "/") + servidor.Length + 1;

            string depart = aux2.Substring(pos3);
            int    pos4   = depart.IndexOf("/");
            depart = depart.Substring(0, pos4);
            depart = depart.Replace("%20", " ");

            t.idServidor     = servidor;
            t.departamento   = depart;
            t.textoContenido = textoContenido;
            t.nombreArchivo  = path.Substring(0, path.IndexOf(".pdf"));
            t.titulo         = titulo;
            t.tamanoArchivo  = fileLengthInKB;

            string ext = System.IO.Path.GetExtension(path);
            t.formato                  = ext;
            t.nombreArchivo            = path.Substring(0, path.IndexOf(ext));
            t.nombreArchivo            = System.IO.Path.GetFileName(path);
            t.fechaCreacionArchivo     = (DateTime)File.GetCreationTime(path);
            t.fechaModificacionArchivo = (DateTime)File.GetLastWriteTime(path);
            t.fechaUltimaLectura       = (DateTime)File.GetLastAccessTime(path);
            t.fechaUltimaActualizacion = DateTime.Now;
            t.hits = rnd.Next(1, 55);

            if (File.Exists(path))
            {
                t.estadoActividad = 1;
            }

            Texto existente = OperacionesElasticSearch.ExisteTexto(t);
            if (existente == null)
            {
                OperacionesElasticSearch.InsertarTexto(t);
            }
            else
            {
                OperacionesElasticSearch.actualizarTexto(existente, t);
            }
        }
        else if (Herramientas.EsPowerPoint(path) && indexatexto && path.Contains(dpto))
        {
            Microsoft.Office.Interop.PowerPoint.Application   PowerPoint_App      = new Microsoft.Office.Interop.PowerPoint.Application();
            Microsoft.Office.Interop.PowerPoint.Presentations multi_presentations = PowerPoint_App.Presentations;
            Microsoft.Office.Interop.PowerPoint.Presentation  presentation        = multi_presentations.Open(path);

            var f = new FileInfo(path);
            var fileLengthInKB = f.Length / 1024.0;

            string textoContenido = "";
            for (int i = 0; i < presentation.Slides.Count; i++)
            {
                foreach (var item in presentation.Slides[i + 1].Shapes)
                {
                    var shape = (Powerpoint.Shape)item;
                    if (shape.HasTextFrame == MsoTriState.msoTrue)
                    {
                        if (shape.TextFrame.HasText == MsoTriState.msoTrue)
                        {
                            var textRange = shape.TextFrame.TextRange;
                            var text      = textRange.Text;
                            textoContenido += text + " ";
                        }
                    }
                }
            }
            //Get Author Name
            object wordProperties      = presentation.BuiltInDocumentProperties;
            Type   typeDocBuiltInProps = wordProperties.GetType();
            Object Authorprop          = typeDocBuiltInProps.InvokeMember("Item", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.GetProperty, null, wordProperties, new object[] { "Author" }); //query for author properties
            Type   typeAuthorprop      = Authorprop.GetType();
            string autor = typeAuthorprop.InvokeMember("Value", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.GetProperty, null, Authorprop, new object[] { }).ToString();                     //get author name

            Texto t = new Texto();
            t.textoContenido = textoContenido;
            Uri u = new Uri(path);
            t.urlRuta = u.AbsoluteUri;
            string ext = System.IO.Path.GetExtension(path);
            t.formato       = ext;
            t.nombreArchivo = path.Substring(0, path.IndexOf(ext));
            string auxiliar = "http://localhost/servidores/";
            t.urlRuta = u.AbsoluteUri;
            var puerto = u.Port;
            int pos    = t.urlRuta.IndexOf("servidores/") + 11;

            string aux2 = t.urlRuta.Substring(pos);
            t.urlRuta = auxiliar + aux2;
            int    pos2     = aux2.IndexOf("/");
            string servidor = aux2.Substring(0, pos2);
            int    pos3     = aux2.IndexOf(servidor + "/") + servidor.Length + 1;

            string depart = aux2.Substring(pos3);
            int    pos4   = depart.IndexOf("/");
            depart         = depart.Substring(0, pos4);
            depart         = depart.Replace("%20", " ");
            t.departamento = depart;
            t.hits         = rnd.Next(1, 55);


            PowerPoint_App.Quit();
            presentation.Close();

            t.idServidor               = servidor;
            textoContenido             = textoContenido.Trim();
            t.nombreArchivo            = System.IO.Path.GetFileName(path);
            t.fechaCreacionArchivo     = (DateTime)File.GetCreationTime(path);
            t.fechaModificacionArchivo = (DateTime)File.GetLastWriteTime(path);
            t.fechaUltimaLectura       = (DateTime)File.GetLastAccessTime(path);
            t.fechaUltimaActualizacion = DateTime.Now;

            if (File.Exists(path))
            {
                t.estadoActividad = 1;
            }

            Texto existente = OperacionesElasticSearch.ExisteTexto(t);
            if (existente == null)
            {
                OperacionesElasticSearch.InsertarTexto(t);
            }
            else
            {
                OperacionesElasticSearch.actualizarTexto(existente, t);
            }
        }
        else if (Herramientas.EsImagen(path) && indexaimagen && path.Contains(dpto))
        {
            var           f = new FileInfo(path);
            var           fileLengthInKB = f.Length / 1024.0;
            string        ext            = System.IO.Path.GetExtension(path);
            List <string> eti            = new List <string>();
            eti.Add("imagen");
            eti.Add("foto");

            String   titulo  = path.Substring(0, path.IndexOf(ext));
            FileInfo file    = new FileInfo(path);
            int      tamanio = (int)file.Length;

            Bitmap img = new Bitmap(path);

            int altura  = img.Height;
            int anchura = img.Width;

            Imagen im = new Imagen();
            im.pixelesAltura  = altura;
            im.pixelesAnchura = anchura;

            Uri u = new Uri(path);
            im.urlRuta = u.AbsoluteUri;


            string auxiliar = "http://localhost/servidores/";
            im.urlRuta = u.AbsoluteUri;
            var puerto = u.Port;
            int pos    = im.urlRuta.IndexOf("servidores/") + 11;

            string aux2 = im.urlRuta.Substring(pos);
            im.urlRuta = auxiliar + aux2;
            int    pos2     = aux2.IndexOf("/");
            string servidor = aux2.Substring(0, pos2);
            int    pos3     = aux2.IndexOf(servidor + "/") + servidor.Length + 1;

            string depart = aux2.Substring(pos3);
            int    pos4   = depart.IndexOf("/");
            depart          = depart.Substring(0, pos4);
            depart          = depart.Replace("%20", " ");
            im.departamento = depart;

            im.idServidor               = servidor;
            ext                         = System.IO.Path.GetExtension(path);
            im.formato                  = ext;
            im.nombreArchivo            = System.IO.Path.GetFileName(path);
            im.fechaCreacionArchivo     = (DateTime)File.GetCreationTime(path);
            im.fechaModificacionArchivo = (DateTime)File.GetLastWriteTime(path);
            im.fechaUltimaLectura       = (DateTime)File.GetLastAccessTime(path);
            im.fechaUltimaActualizacion = DateTime.Now;
            im.etiquetas                = eti;
            im.hits                     = rnd.Next(1, 55);


            if (File.Exists(path))
            {
                im.estadoActividad = 1;
            }

            Imagen existente = OperacionesElasticSearch.ExisteImagen(im);
            if (existente == null)
            {
                OperacionesElasticSearch.InsertarImagen(im);
            }
            else
            {
                OperacionesElasticSearch.actualizarImagen(existente, im);
            }
        }
        else if (Herramientas.EsAudio(path) && indexaaudio)
        {
            var fi             = new FileInfo(path);
            var fileLengthInKB = fi.Length / 1024.0;

            string ext    = System.IO.Path.GetExtension(path);
            string titulo = path.Substring(0, path.IndexOf(ext));

            TagLib.File f        = TagLib.File.Create(path, TagLib.ReadStyle.Average);
            var         duracion = (int)f.Properties.Duration.TotalSeconds;

            List <string> eti = new List <string>();
            eti.Add("audio");
            eti.Add("sonido");

            Audio au = new Audio();
            Uri   u  = new Uri(path);
            au.urlRuta = u.AbsoluteUri;
            string auxiliar = "http://localhost/servidores/";
            au.urlRuta = u.AbsoluteUri;
            var puerto = u.Port;
            int pos    = au.urlRuta.IndexOf("servidores/") + 11;

            string aux2 = au.urlRuta.Substring(pos);
            au.urlRuta = auxiliar + aux2;
            int    pos2     = aux2.IndexOf("/");
            string servidor = aux2.Substring(0, pos2);
            int    pos3     = aux2.IndexOf(servidor + "/") + servidor.Length + 1;

            string depart = aux2.Substring(pos3);
            int    pos4   = depart.IndexOf("/");
            depart                      = depart.Substring(0, pos4);
            depart                      = depart.Replace("%20", " ");
            au.departamento             = depart;
            au.duracion                 = duracion;
            au.etiquetas                = eti;
            au.formato                  = ext;
            au.nombreArchivo            = System.IO.Path.GetFileName(path);
            au.fechaCreacionArchivo     = (DateTime)File.GetCreationTime(path);
            au.fechaModificacionArchivo = (DateTime)File.GetLastWriteTime(path);
            au.fechaUltimaLectura       = (DateTime)File.GetLastAccessTime(path);
            au.fechaUltimaActualizacion = DateTime.Now;
            au.hits                     = rnd.Next(1, 55);
            au.idServidor               = servidor;

            if (File.Exists(path))
            {
                au.estadoActividad = 1;
            }

            Audio existente = OperacionesElasticSearch.ExisteAudio(au);
            if (existente == null)
            {
                OperacionesElasticSearch.InsertarAudio(au);
            }
            else
            {
                OperacionesElasticSearch.actualizarAudio(existente, au);
            }
        }
        else if (Herramientas.EsVideo(path) && indexavideo)
        {
            string        ext    = System.IO.Path.GetExtension(path);
            string        titulo = path.Substring(0, path.IndexOf(ext));
            List <string> eti    = new List <string>();
            eti.Add("video");
            var    fi             = new FileInfo(path);
            int    duracion       = 0;
            string calidad        = "";
            var    fileLengthInKB = fi.Length / 1024.0;
            if (ext == ".mp4")
            {
                TagLib.File f = TagLib.File.Create(path, TagLib.ReadStyle.Average);
                duracion = (int)f.Properties.Duration.TotalSeconds;

                if (f.Properties.VideoHeight != 0 && f.Properties.VideoWidth != 0)
                {
                    int height = (int)f.Properties.VideoHeight;
                    int width  = (int)f.Properties.VideoWidth;
                    calidad = height + "x" + width;
                }
            }

            Uri u = new Uri(path);

            Video v = new Video();
            v.urlRuta = u.AbsoluteUri;
            string auxiliar = "http://localhost/servidores/";
            v.urlRuta = u.AbsoluteUri;
            var puerto = u.Port;
            int pos    = v.urlRuta.IndexOf("servidores/") + 11;

            string aux2 = v.urlRuta.Substring(pos);
            v.urlRuta = auxiliar + aux2;
            int    pos2     = aux2.IndexOf("/");
            string servidor = aux2.Substring(0, pos2);
            int    pos3     = aux2.IndexOf(servidor + "/") + servidor.Length + 1;

            string depart = aux2.Substring(pos3);
            int    pos4   = depart.IndexOf("/");
            depart                     = depart.Substring(0, pos4);
            depart                     = depart.Replace("%20", " ");
            depart                     = depart.Replace("%20", " ");
            v.departamento             = depart;
            v.duracion                 = duracion;
            v.etiquetas                = eti;
            v.calidad                  = calidad;
            v.idServidor               = servidor;
            v.nombreArchivo            = System.IO.Path.GetFileName(path);
            v.fechaCreacionArchivo     = (DateTime)File.GetCreationTime(path);
            v.fechaModificacionArchivo = (DateTime)File.GetLastWriteTime(path);
            v.fechaUltimaLectura       = (DateTime)File.GetLastAccessTime(path);
            v.fechaUltimaActualizacion = DateTime.Now;
            v.formato                  = ext;
            v.hits                     = rnd.Next(1, 55);

            if (File.Exists(path))
            {
                v.estadoActividad = 1;
            }

            Video existente = OperacionesElasticSearch.ExisteVideo(v);
            if (existente == null)
            {
                OperacionesElasticSearch.InsertarVideo(v);
            }
            else
            {
                OperacionesElasticSearch.actualizarVideo(existente, v);
            }
        }
    }
Пример #40
0
 /// <summary>
 /// Initialise les "handlers" (comment on dit ça en français?) pour le traitement du
 /// changement de sélection et la fermeture de document.
 /// </summary>
 /// <param name="app">L'application Word dans laquelle ceci est exécuté. Ne peut pas
 /// être <c>null</c></param>
 public void InitHandlers(Microsoft.Office.Interop.PowerPoint.Application app)
 {
     app.PresentationClose     += new EApplication_PresentationCloseEventHandler(PresentationClosed);
     app.WindowSelectionChange += new EApplication_WindowSelectionChangeEventHandler(SelChanged_Event);
 }
Пример #41
0
        private void ConvertToPdfIfNeeded(string tmpReportFile)
        {
            // convert docx or pptx to pdf
            if (ReportFileName.Contains(".pdf"))
            {
                if (tmpReportFile.Contains(".docx"))
                {
                    try
                    {
                        Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
                        Document wordDocument = appWord.Documents.Open(tmpReportFile);
                        wordDocument.ExportAsFixedFormat(ReportFileName, WdExportFormat.wdExportFormatPDF);
                        wordDocument.Close();
                        appWord.Quit();
                    }
                    catch (Exception)
                    {
                        // Error if office not installed, then do not save as pdf
                        ReportFileName = ReportFileName.Replace(".pdf", SelectedTemplateFile.Extension);
                        File.Copy(tmpReportFile, ReportFileName, true);
                    }
                }
                else if (tmpReportFile.Contains(".pptx"))
                {
                    try
                    {
                        Microsoft.Office.Interop.PowerPoint.Application appPowerpoint = new Microsoft.Office.Interop.PowerPoint.Application();
                        Presentation appPres = appPowerpoint.Presentations.Open(tmpReportFile);
                        appPres.ExportAsFixedFormat(ReportFileName, PpFixedFormatType.ppFixedFormatTypePDF);
                        appPres.Close();
                        appPowerpoint.Quit();
                    }
                    catch (Exception)
                    {
                        // Error if office not installed, then do not save as pdf
                        ReportFileName = ReportFileName.Replace(".pdf", SelectedTemplateFile.Extension);
                        File.Copy(tmpReportFile, ReportFileName, true);
                    }
                }

                /* Reports too ugly and unusable when converted from excel to pdf
                 * else if (tmpReportFile.Contains(".xlsx"))
                 *  {
                 *      Microsoft.Office.Interop.Excel.Application appExcel = new Microsoft.Office.Interop.Excel.Application();
                 *      Workbook excelDoc = appExcel.Workbooks.Open(tmpReportFile);
                 *      excelDoc.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, ReportFileName);
                 *      excelDoc.Close();
                 *      appExcel.Quit();
                 *  }
                 */
                else
                {
                    string report = ReportFileName.Replace(".pdf", SelectedTemplateFile.Extension);
                    File.Copy(tmpReportFile, report, true);
                }
            }
            else
            {
                //Copy report file to the selected destination
                File.Copy(tmpReportFile, ReportFileName, true);
            }
        }
Пример #42
0
 public Application()
 {
     this.app = new InteropPowerPoint.Application();
 }
Пример #43
0
        /// <summary>
        /// If an instance of the PowerPoint application exits this method will export the text of the active presentation to the selected file.
        /// </summary>
        public override void Perform()
        {
            if (File.Exists(fileName))
            {
                streamWriter = null;

                try
                {
                    FileStream stream = File.Open(fileName, FileMode.Create);
                    streamWriter = new StreamWriter(stream);
                }
                catch (Exception ex)
                {
                    ErrorLog.AddError(ErrorType.Failure, Strings.General_CantOpenFile);
                    Logger.WriteLine(ex);

                    return;
                }
            }
            else
            {
                ErrorLog.AddError(ErrorType.Failure, Strings.General_FileNotFound);
                return;
            }

            try
            {
                app = (OPowerPoint.Application)Marshal.GetActiveObject("PowerPoint.Application");
            }
            catch (Exception ex)
            {
                ErrorLog.AddError(ErrorType.Failure, Strings.PowerPoint_ApplicationNotFound);
                Logger.Write(ex);

                try
                {
                    if (streamWriter != null)
                    {
                        streamWriter.Close();
                    }
                }
                catch (IOException e)
                {
                    ErrorLog.AddError(ErrorType.Failure, Strings.CantCloseFileStream);
                    Logger.WriteLine(e);
                }

                return;
            }

            try
            {
                OPowerPoint.Presentation activePresentation = app.ActivePresentation;

                if (activePresentation == null)
                {
                    ErrorLog.AddError(ErrorType.Failure, Strings.PowerPoint_NoActivePresentation);
                }
                else
                {
                    foreach (OPowerPoint.Slide slide in activePresentation.Slides)
                    {
                        foreach (OPowerPoint.Shape shape in slide.Shapes)
                        {
                            if (shape.HasTextFrame == Microsoft.Office.Core.MsoTriState.msoTrue)
                            {
                                if (shape.TextFrame.HasText == Microsoft.Office.Core.MsoTriState.msoTrue)
                                {
                                    streamWriter.WriteLine(shape.TextFrame.TextRange.Text);
                                }
                            }
                        }
                    }
                }

                streamWriter.Close();
            }
            catch (Exception ex)
            {
                ErrorLog.AddError(ErrorType.Failure, Strings.PowerPoint_CantExportText);
                Logger.Write(ex);

                try
                {
                    if (streamWriter != null)
                    {
                        streamWriter.Close();
                    }
                }
                catch (IOException e)
                {
                    ErrorLog.AddError(ErrorType.Failure, Strings.CantCloseFileStream);
                    Logger.WriteLine(e);
                }
            }
            finally
            {
                app = null;
            }
        }
Пример #44
0
        public PowerPointConverter()
        {
            _app = new PowerPoint.Application();

            _ppts = _app.Presentations;
        }
Пример #45
0
 public PowerPointApi(PowerPoint.Application application)
 {
     _officeApplication = application;
 }
Пример #46
0
        public void CreatePowerPoint()
        {
            String strTemplate, strPic;

            strTemplate = Directory.GetCurrentDirectory() + "\\Resources\\blends.pot";
            strPic      = Directory.GetCurrentDirectory() + "\\Resources\\Add record.png";

            Power.Application   objApp;
            Power.Presentations objPresSet;
            Power._Presentation objPres;
            Power.Slides        objSlides;
            Power._Slide        objSlide;
            Power.TextRange     objTextRng;
            //Power.Shapes objShapes;
            //Power.Shape objShape;

            //Power.SlideShowWindows objSSWs;
            //Power.SlideShowTransition objSST;
            //Power.SlideShowSettings objSSS;
            //Power.SlideRange objSldRng;
            //Graph.Chart objChart;

            //Create a new presentation based on a template.
            objApp         = new Power.Application();
            objApp.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
            objPresSet     = objApp.Presentations;
            objPres        = objPresSet.Open(strTemplate,
                                             Microsoft.Office.Core.MsoTriState.msoFalse,
                                             Microsoft.Office.Core.MsoTriState.msoTrue,
                                             Microsoft.Office.Core.MsoTriState.msoTrue);
            objSlides = objPres.Slides;

            //Build Slide #1:
            //Add text to the slide, change the font and insert/position a
            //picture on the first slide.
            //objSlide = objSlides.Add(1, Power.PpSlideLayout.ppLayoutTitleOnly);
            //objTextRng = objSlide.Shapes[1].TextFrame.TextRange;
            //objTextRng.Text = "IBM IT Consultation";
            //objTextRng.Font.Name = "Comic Sans MS";
            //objTextRng.Font.Size = 48;
            //objSlide.Shapes.AddPicture(strPic, Microsoft.Office.Core.MsoTriState.msoFalse,
            //    Microsoft.Office.Core.MsoTriState.msoTrue,
            //    150, 150, 500, 350);

            //Build Slide #2:
            //Add text to the slide title, format the text. Also add a chart to the
            //slide and change the chart type to a 3D pie chart.
            //objSlide = objSlides.Add(2, Power.PpSlideLayout.ppLayoutTitleOnly);
            //objTextRng = objSlide.Shapes[1].TextFrame.TextRange;
            //objTextRng.Text = "My Chart";
            //objTextRng.Font.Name = "Comic Sans MS";
            //objTextRng.Font.Size = 48;
            //objChart = (Graph.Chart)objSlide.Shapes.AddOLEObject(150, 150, 480, 320,
            //    "MSGraph.Chart.8", "", Microsoft.Office.Core.MsoTriState.msoFalse,
            //    "", 0, "",
            //    Microsoft.Office.Core.MsoTriState.msoFalse).OLEFormat.Object;
            //objChart.ChartType = Graph.XlChartType.xl3DPie;
            //objChart.Legend.Position = Graph.XlLegendPosition.xlLegendPositionBottom;
            //objChart.HasTitle = true;
            //objChart.ChartTitle.Text = "Here it is...";

            //Build Slide #3:
            //Change the background color of this slide only. Add a text effect to the slide
            //and apply various color schemes and shadows to the text effect.
            //objSlide = objSlides.Add(3, Power.PpSlideLayout.ppLayoutBlank);
            //objSlide.FollowMasterBackground = Microsoft.Office.Core.MsoTriState.msoFalse;
            //objShapes = objSlide.Shapes;
            //objShape = objShapes.AddTextEffect(Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect27,
            //  "The End", "Impact", 96, Microsoft.Office.Core.MsoTriState.msoFalse,
            //  Microsoft.Office.Core.MsoTriState.msoFalse, 230, 200);


            var FD = new System.Windows.Forms.FolderBrowserDialog();

            if (FD.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }

            var files = Directory.EnumerateFiles(FD.SelectedPath);

            foreach (var file in files)
            {
                if (file.Contains("~$") || !file.Contains(".jpg"))
                {
                    continue;
                }

                objSlide             = objSlides.Add(1, Power.PpSlideLayout.ppLayoutTitleOnly);
                objTextRng           = objSlide.Shapes[1].TextFrame.TextRange;
                objTextRng.Text      = Path.GetFileNameWithoutExtension(file);
                objTextRng.Font.Name = "Comic Sans MS";
                objTextRng.Font.Size = 48;
                objSlide.Shapes.AddPicture(file, Microsoft.Office.Core.MsoTriState.msoFalse,
                                           Microsoft.Office.Core.MsoTriState.msoTrue,
                                           150, 150, 500, 350);
            }
        }
Пример #47
0
        static void Main(string[] args)
        {
            string        out_format          = "PDF";
            bool          optimize_for_screen = false;
            List <string> files = (new OptionSet {
                { "xps", v => { if (v != null)
                                {
                                    out_format = "XPS";
                                }
                  } },
                { "pdf", v => { if (v != null)
                                {
                                    out_format = "PDF";
                                }
                  } },
                { "screen", v => { if (v != null)
                                   {
                                       optimize_for_screen = true;
                                   }
                  } }
            }).Parse(args);

            var rx_ppt = new Regex(@"\.(pptx|ppt|pptm|ppsx|pps|ppsm|potx|pot|potm|odp)$", RegexOptions.IgnoreCase);
            var rx_doc = new Regex(@"\.(docx|docm|dotx|dotm|doc|dot|htm|html|rtf|mht|mhtml|xml|odt)$", RegexOptions.IgnoreCase);

            PowerPoint.Application ppt = null;
            Word.Application       wrd = null;
            foreach (var i in files)
            {
                try
                {
                    var file = Path.GetFullPath(i);
                    if (rx_ppt.IsMatch(file))
                    {
                        if (ppt == null)
                        {
                            ppt = new PowerPoint.Application();
                        }
                        PowerPoint.Presentation p = ppt.Presentations.Open(file, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
                        string dst = getAvailableFileName(out_format == "PDF" ? getPDFName(file) : getXPSName(file));
                        p.SaveCopyAs(dst, out_format == "PDF" ? PowerPoint.PpSaveAsFileType.ppSaveAsPDF : PowerPoint.PpSaveAsFileType.ppSaveAsXPS, MsoTriState.msoTrue);
                        p.Close();
                    }
                    else if (rx_doc.IsMatch(file))
                    {
                        if (wrd == null)
                        {
                            wrd = new Word.Application();
                        }
                        Word.Document d   = wrd.Documents.Open(file, false, true);
                        string        dst = getAvailableFileName(out_format == "PDF" ? getPDFName(file) : getXPSName(file));
                        d.ExportAsFixedFormat(dst, out_format == "PDF" ? Word.WdExportFormat.wdExportFormatPDF : Word.WdExportFormat.wdExportFormatXPS, false, optimize_for_screen ? Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen : Word.WdExportOptimizeFor.wdExportOptimizeForPrint);
                        d.Close(false);
                    }
                    else
                    {
                        Console.Error.WriteLine("Unknown file type: " + i);
                    }
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine(e.Message);
                }
            }
            ppt?.Quit();
            wrd?.Quit();
        }
Пример #48
0
        public void Output(ShiftingReport report, string filename)
        {
            ppt         = new PowerPoint.Application();
            ppt.Visible = Office.MsoTriState.msoTrue;
            PowerPoint.Presentation targetPres = ppt.Presentations.Add();
            targetPres.SaveAs(filename);
            targetPres.PageSetup.SlideSize = (PowerPoint.PpSlideSizeType.ppSlideSizeOnScreen);

            int index = 0;

            foreach (string region in report.Regions)
            {
                List <ReportTable> tables = (from r in report.ReportTables
                                             where r.region == region
                                             select r).ToList();
                List <string> hint = new List <string>()
                {
                    "光明畅优", "光明健能", "光明E+", "蒙牛", "伊利",
                };
                tables.Sort(new Comparison <ReportTable>((x, y) =>
                {
                    int xidx = hint.FindIndex(s => s.Equals(x.vendor));
                    int yidx = hint.FindIndex(s => s.Equals(y.vendor));
                    if (xidx < 0)
                    {
                        xidx = hint.Count;
                        hint.Add(x.vendor);
                    }
                    if (yidx < 0)
                    {
                        yidx = hint.Count;
                        hint.Add(y.vendor);
                    }
                    return(xidx > yidx ? 1 : -1);
                }));
                foreach (ReportTable table in tables)
                {
                    targetPres.Slides.InsertFromFile(tmplPPTFilename, index * 2, 1, 2);

                    PowerPoint.Slide slideText  = targetPres.Slides[index * 2 + 1];
                    PowerPoint.Slide slideChart = targetPres.Slides[index * 2 + 2];

                    ReplaceTextInSlide(slideText, "{region}", table.region);
                    ReplaceTextInSlide(slideText, "{vendor}", table.vendor);
                    ReplaceTextInSlide(slideChart, "{region}", table.region);
                    ReplaceTextInSlide(slideChart, "{vendor}", table.vendor);

                    BuildChart(table, slideChart.SlideNumber, 2, row =>
                    {
                        Dictionary <string, string> dict = new Dictionary <string, string>()
                        {
                            { "shiftingtotal", "品牌转换" },
                            { "retainedbuyers", "原有消费者购买增加/减少" },
                            { "new/lostbuyers", "购买清单中增加/删除品牌" },
                            { "nonbuyers", "新增/流失品类消费者" },
                        };
                        string key   = row[0].Trim().Replace(" ", "").ToLower();
                        string value = null;
                        if (dict.TryGetValue(key, out value))
                        {
                            string[] newrow = new string[row.Length];
                            Array.Copy(row, newrow, row.Length);
                            newrow[0] = value;
                            return(newrow);
                        }
                        return(null);
                    });

                    BuildChart(table, slideChart.SlideNumber, 4, row =>
                    {
                        string key = row[0].Trim().Replace(" ", "");
                        Regex cn   = new Regex("[\u4e00-\u9fa5]+");
                        if (cn.IsMatch(key))
                        {
                            string[] newrow = new string[row.Length];
                            Array.Copy(row, newrow, row.Length);
                            newrow[0] = key;
                            return(newrow);
                        }
                        return(null);
                    });
                    targetPres.Save();
                    index += 1;
                }
            }
        }
Пример #49
0
        public static void generate(GenInfo genInfo)
        {
            Powerpoint.Application powerApp = new Powerpoint.Application();

            Powerpoint.Presentation awardsPresentation = powerApp.Presentations.Open(genInfo.awardPowerpointTemplateFile, MsoTriState.msoFalse, MsoTriState.msoTrue, MsoTriState.msoFalse);

            int startingNumberOfSlides = awardsPresentation.Slides.Count;

            Excel.Application excelApp        = new Excel.Application();
            Excel.Workbook    awardsWorkbook  = excelApp.Workbooks.Open(genInfo.awardExcelFile, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "/t", false, false, 0, true, 1, 0);
            Excel.Worksheet   awardsWorksheet = awardsWorkbook.Worksheets[1];

            int lastUsedRow = awardsWorksheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing).Row;

            for (int rowIndex = genInfo.startingRow; rowIndex <= lastUsedRow; rowIndex++)
            {
                if (getValueOfCell(ref awardsWorksheet, genInfo.studentCodeColumn, rowIndex) == "")
                {
                    continue;
                }

                Powerpoint.Slide currentSlide = awardsPresentation.Slides.AddSlide(awardsPresentation.Slides.Count + 1, awardsPresentation.SlideMaster.CustomLayouts[genInfo.awardLayoutIndex]);

                Powerpoint.Shapes slideShapes = currentSlide.Shapes;

                Powerpoint.Placeholders placeholders = slideShapes.Placeholders;

                int placeholderIndex = 1;
                foreach (Powerpoint.Shape shape in placeholders)
                {
                    // Set Student Name
                    if (placeholderIndex == genInfo.awardStudentNamePlaceholderIndex)
                    {
                        shape.TextFrame.TextRange.Text = getValueOfCell(ref awardsWorksheet, genInfo.studentNameColumn, rowIndex);
                    }

                    // Set Student Form
                    if (placeholderIndex == genInfo.awardStudentFormPlaceholderIndex)
                    {
                        Powerpoint.TextFrame frame = shape.TextFrame;

                        Powerpoint.TextRange range = frame.TextRange;
                        range.Text = getValueOfCell(ref awardsWorksheet, genInfo.studentFormColumn, rowIndex);
                    }

                    // Set award
                    if (placeholderIndex == genInfo.awardAwardTitlePlaceholderIndex)
                    {
                        shape.TextFrame.TextRange.Text = getValueOfCell(ref awardsWorksheet, genInfo.studentAwardColumn, rowIndex);
                    }

                    // Set picture
                    if (placeholderIndex == genInfo.awardStudentPicturePlaceholderIndex)
                    {
                        string studentCode = getValueOfCell(ref awardsWorksheet, genInfo.studentCodeColumn, rowIndex);
                        string pictureFile = findFileInFolder(genInfo.picturesFolder, studentCode + genInfo.pictureFileExtension);
                        if (pictureFile != "")
                        {
                            shape.Fill.UserPicture(pictureFile);
                        }
                        else
                        {
                            Console.Out.WriteLine("Picture for " + studentCode + " not found");
                        }
                    }
                    placeholderIndex++;
                }
            }

            for (int i = 0; i < startingNumberOfSlides; i++)
            {
                awardsPresentation.Slides[1].Delete();
            }



            awardsPresentation.SaveAs(Path.GetDirectoryName(genInfo.awardPowerpointTemplateFile) + "/Output.pptx");
        }
Пример #50
0
 private void RegisterPowerPointAppClosedEvent(PowerPoint.Application app)
 {
     app.PresentationBeforeClose += (PowerPoint.Presentation pres, ref bool cancel) => AppClosedEvent?.Invoke(this, new AppClosedEventArgs(pres.FullName, OfficeAppType.PowerPoint));
 }
Пример #51
0
        private void ShowPresentation()
        {
            String strTemplate, strPic;

            strTemplate =
                //"C:\\Program Files\\Microsoft Office\\Templates\\Presentation Designs\\Blends.pot";
                @"C:\Users\ssor\Desktop\MyPPT.ppt";
            //strPic = "C:\\Windows\\Blue Lace 16.bmp";
            strPic = @"C:\Users\ssor\Desktop\460.jpg";
            bool bAssistantOn;

            PowerPoint.Application         objApp;
            PowerPoint.Presentations       objPresSet;
            PowerPoint._Presentation       objPres;
            PowerPoint.Slides              objSlides;
            PowerPoint._Slide              objSlide;
            PowerPoint.TextRange           objTextRng;
            PowerPoint.Shapes              objShapes;
            PowerPoint.Shape               objShape;
            PowerPoint.SlideShowWindows    objSSWs;
            PowerPoint.SlideShowTransition objSST;
            PowerPoint.SlideShowSettings   objSSS;
            PowerPoint.SlideRange          objSldRng;
            Graph.Chart objChart;

            //Create a new presentation based on a template.
            objApp         = new PowerPoint.Application();
            objApp.Visible = MsoTriState.msoTrue;
            objPresSet     = objApp.Presentations;
            objPres        = objPresSet.Open(strTemplate,
                                             MsoTriState.msoFalse, MsoTriState.msoTrue, MsoTriState.msoTrue);
            objSlides = objPres.Slides;

            //Build Slide #1:
            //Add text to the slide, change the font and insert/position a
            //picture on the first slide.
            objSlide             = objSlides.Add(1, PowerPoint.PpSlideLayout.ppLayoutTitleOnly);
            objTextRng           = objSlide.Shapes[1].TextFrame.TextRange;
            objTextRng.Text      = "My Sample Presentation";
            objTextRng.Font.Name = "Comic Sans MS";
            objTextRng.Font.Size = 48;
            objSlide.Shapes.AddPicture(strPic, MsoTriState.msoFalse, MsoTriState.msoTrue,
                                       150, 150, 500, 350);

            //Build Slide #2:
            //Add text to the slide title, format the text. Also add a chart to the
            //slide and change the chart type to a 3D pie chart.
            objSlide             = objSlides.Add(2, PowerPoint.PpSlideLayout.ppLayoutTitleOnly);
            objTextRng           = objSlide.Shapes[1].TextFrame.TextRange;
            objTextRng.Text      = "My Chart";
            objTextRng.Font.Name = "Comic Sans MS";
            objTextRng.Font.Size = 48;
            objChart             = (Graph.Chart)objSlide.Shapes.AddOLEObject(150, 150, 480, 320,
                                                                             "MSGraph.Chart.8", "", MsoTriState.msoFalse, "", 0, "",
                                                                             MsoTriState.msoFalse).OLEFormat.Object;
            objChart.ChartType       = Graph.XlChartType.xl3DPie;
            objChart.Legend.Position = Graph.XlLegendPosition.xlLegendPositionBottom;
            objChart.HasTitle        = true;
            objChart.ChartTitle.Text = "Here it is...";

            //Build Slide #3:
            //Change the background color of this slide only. Add a text effect to the slide
            //and apply various color schemes and shadows to the text effect.
            objSlide = objSlides.Add(3, PowerPoint.PpSlideLayout.ppLayoutBlank);
            objSlide.FollowMasterBackground = MsoTriState.msoFalse;
            objShapes = objSlide.Shapes;
            objShape  = objShapes.AddTextEffect(MsoPresetTextEffect.msoTextEffect27,
                                                "The End", "Impact", 96, MsoTriState.msoFalse, MsoTriState.msoFalse, 230, 200);


            // 自动播放的代码(閞始)
            //Modify the slide show transition settings for all 3 slides in
            //the presentation.
            int[] SlideIdx = new int[3];
            for (int i = 0; i < 3; i++)
            {
                SlideIdx[i] = i + 1;
            }
            objSldRng            = objSlides.Range(SlideIdx);
            objSST               = objSldRng.SlideShowTransition;
            objSST.AdvanceOnTime = MsoTriState.msoTrue;
            objSST.AdvanceTime   = 3;
            objSST.EntryEffect   = PowerPoint.PpEntryEffect.ppEffectBoxOut;

            //Prevent Office Assistant from displaying alert messages:
            bAssistantOn        = objApp.Assistant.On;
            objApp.Assistant.On = false;

            //Run the Slide show from slides 1 thru 3.
            objSSS = objPres.SlideShowSettings;
            objSSS.StartingSlide = 1;
            objSSS.EndingSlide   = 3;
            objSSS.Run();

            //Wait for the slide show to end.
            objSSWs = objApp.SlideShowWindows;
            while (objSSWs.Count >= 1)
            {
                System.Threading.Thread.Sleep(100);
            }

            //Reenable Office Assisant, if it was on:
            if (bAssistantOn)
            {
                objApp.Assistant.On      = true;
                objApp.Assistant.Visible = false;
            }
            // 自动播放的代码(结束)

            //Close the presentation without saving changes and quit PowerPoint.
            objPres.Close();
            objApp.Quit();
        }
Пример #52
0
        /// <summary>
        /// Read the file of PPT and output to List of string
        /// </summary>
        /// <param name="file">full path of ppt</param>
        /// <returns>list of string</returns>
        public static List <string> PPT2txt(string file)
        {
            PPT.Application  app   = null;
            PPT.Presentation pptx  = null;
            List <string>    notes = new List <string>();

            try
            {
                // PPTのインスタンス作成
                app = new PPT.Application();

                // ファイルオープン
                pptx = app.Presentations.Open(
                    file,
                    Office.MsoTriState.msoTrue,    // 読み取り専用
                    Office.MsoTriState.msoTrue,
                    Office.MsoTriState.msoFalse
                    );

                foreach (PPT.Slide sld in pptx.Slides)
                {
                    foreach (PPT.Shape shp in sld.Shapes)
                    {
                        if (shp.HasTextFrame == Office.MsoTriState.msoTrue)
                        {
                            if (shp.TextFrame.HasText == Office.MsoTriState.msoTrue)
                            {
                                notes.Add(shp.TextFrame.TextRange.Text);
                            }
                        }

                        else if (shp.HasTable == Office.MsoTriState.msoTrue)
                        {
                            foreach (PPT.Row rw in shp.Table.Rows)
                            {
                                string strRW = "";
                                foreach (PPT.Cell cl in rw.Cells)
                                {
                                    strRW = strRW + cl.Shape.TextFrame.TextRange.Text == "" ? "△" : cl.Shape.TextFrame.TextRange.Text;
                                }
                                notes.Add(strRW);
                            }
                        }

                        else if (shp.HasChart == Office.MsoTriState.msoTrue)
                        {
                            if (shp.Chart.HasTitle)
                            {
                                notes.Add(shp.Chart.Title);
                            }
                        }

                        else if (shp.HasSmartArt == Office.MsoTriState.msoTrue)
                        {
                            foreach (Office.SmartArtNode art in shp.SmartArt.Nodes)
                            {
                                notes.Add(art.TextFrame2.TextRange.Text);
                            }
                        }
                    }
                }
            }
            finally
            {
                // ファイルを閉じる
                if (pptx != null)
                {
                    pptx.Close();
                    pptx = null;
                }

                // PPTを閉じる
                if (app != null)
                {
                    app.Quit();
                    app = null;
                }
            }

            return(notes);
        }
Пример #53
0
        public void ReplaceTemplatePowerpoint()
        {
            String strTemplate, strPic;

            strTemplate = Directory.GetCurrentDirectory() + "\\Resources\\ITPlanningTemplate.ppt";
            String strBubblePic           = Directory.GetCurrentDirectory() + "\\Charts\\BubbleChart.jpg";
            String strITCUPECurr          = Directory.GetCurrentDirectory() + "\\Charts\\IT Current CUPE Responses.jpg";
            String strITCUPEFut           = Directory.GetCurrentDirectory() + "\\Charts\\IT Future CUPE Responses.jpg";
            String strBUSCUPECurr         = Directory.GetCurrentDirectory() + "\\Charts\\Business Current CUPE Responses.jpg";
            String strBUSCUPEFut          = Directory.GetCurrentDirectory() + "\\Charts\\Business Future CUPE Responses.jpg";
            String strITComparisonBar     = Directory.GetCurrentDirectory() + "\\Charts\\IT StakeHolders CurrentFuture Comparison.jpg";
            String strBUSIComparisonBar   = Directory.GetCurrentDirectory() + "\\Charts\\Business Leaders CurrentFuture Comparison.jpg";
            String ITProviderRelationship = Directory.GetCurrentDirectory() + "\\Charts\\IT Provider Relationship.jpg";
            String strHeatMap             = Directory.GetCurrentDirectory() + "\\Charts\\HeatMap.jpg";

            strPic = Directory.GetCurrentDirectory() + "\\Resources\\Add record.png";

            Power.Slides objSlides;
            Power._Slide objSlide;


            //Create a new presentation based on a template.
            Power.Application ppApp = new Power.Application();
            ppApp.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
            Power.Presentations ppPresens = ppApp.Presentations;
            Power.Presentation  objPres   = ppPresens.Open(strTemplate,
                                                           Microsoft.Office.Core.MsoTriState.msoFalse,
                                                           Microsoft.Office.Core.MsoTriState.msoTrue,
                                                           Microsoft.Office.Core.MsoTriState.msoTrue);
            objSlides = objPres.Slides;

            Power.Shape objShape   = null;
            String      tempString = string.Empty;

            try
            {
                //Slide 10
                //Replace the bullets on Slide 10
                //
                objSlide = objSlides[10];

                objShape   = objSlide.Shapes[4];
                tempString = string.Empty;
                //TODO: change this to objectives
                foreach (string BomCat in ClientDataControl.db.GetObjectivesFromCurrentClientBOM())
                {
                    tempString += BomCat + "\r";
                }
                objShape.TextFrame.TextRange.Text = tempString;
                ///
            }
            catch
            {
            }

            try
            {
                //Slide 12
                //Replace the bubblechart picture on slide 12
                //
                objSlide = objSlides[12];

                objSlide.Shapes[2].Delete();


                objSlide.Shapes.AddPicture(strBubblePic, Microsoft.Office.Core.MsoTriState.msoFalse,
                                           Microsoft.Office.Core.MsoTriState.msoTrue, 100, 100, 490, 275);
                //Change the text on slide 12

                objShape = objSlide.Shapes[3];

                tempString = string.Empty + "Business Imperatives:\v\v ";

                //TODO: Replace with imperatives
                foreach (String s in ClientDataControl.db.GetImperativesFromCurrentClientBOM())
                {
                    tempString += s + "\t\t";
                }
                objShape.TextFrame.TextRange.Text = tempString;
                ///
            }
            catch
            {
            }


            try
            {
                ///Slide 18
                ///
                objSlide = objSlides[18];
                objShape = objSlide.Shapes[2];
                objShape.Delete();
                objShape = objSlide.Shapes[2];
                objShape.Delete();


                objSlide.Shapes.AddPicture(ITProviderRelationship, Microsoft.Office.Core.MsoTriState.msoFalse,
                                           Microsoft.Office.Core.MsoTriState.msoTrue, 30, 100, 670, 400);
            }
            catch
            {
            }

            try
            {
                ///Slide 19
                ///
                objSlide = objSlides[19];
                objShape = objSlide.Shapes[3];
                objShape.Delete();
                objShape = objSlide.Shapes[3];
                objShape.Delete();
                objShape = objSlide.Shapes[3];
                objShape.Delete();
                objShape = objSlide.Shapes[3];
                objShape.Delete();
                objShape = objSlide.Shapes[4];
                objShape.Delete();
                objShape = objSlide.Shapes[4];
                objShape.Delete();

                objSlide.Shapes.AddPicture(strBUSCUPECurr, Microsoft.Office.Core.MsoTriState.msoFalse,
                                           Microsoft.Office.Core.MsoTriState.msoTrue, 80, 120, 300, 200);
                objSlide.Shapes.AddPicture(strBUSCUPEFut, Microsoft.Office.Core.MsoTriState.msoFalse,
                                           Microsoft.Office.Core.MsoTriState.msoTrue, 80, 320, 300, 200);
                objSlide.Shapes.AddPicture(strITCUPECurr, Microsoft.Office.Core.MsoTriState.msoFalse,
                                           Microsoft.Office.Core.MsoTriState.msoTrue, 360, 120, 300, 200);
                objSlide.Shapes.AddPicture(strITCUPEFut, Microsoft.Office.Core.MsoTriState.msoFalse,
                                           Microsoft.Office.Core.MsoTriState.msoTrue, 360, 320, 300, 200);
            }
            catch
            {
            }
            try
            {
                ///Slide 20
                ///
                objSlide = objSlides[20];
                objShape = objSlide.Shapes[5];
                objShape.Delete();
                objShape = objSlide.Shapes[5];
                objShape.Delete();
                objShape = objSlide.Shapes[5];
                objShape.Delete();
                objShape = objSlide.Shapes[5];
                objShape.Delete();
                objShape = objSlide.Shapes[5];
                objShape.Delete();
                objShape = objSlide.Shapes[2];
                objShape.Delete();
                objShape = objSlide.Shapes[2];
                objShape.Delete();


                objSlide.Shapes.AddPicture(strBUSIComparisonBar, Microsoft.Office.Core.MsoTriState.msoFalse,
                                           Microsoft.Office.Core.MsoTriState.msoTrue, 0, 100, 350, 380);
                objSlide.Shapes.AddPicture(strITComparisonBar, Microsoft.Office.Core.MsoTriState.msoFalse,
                                           Microsoft.Office.Core.MsoTriState.msoTrue, 350, 100, 350, 380);
            }
            catch
            {
            }

            try
            {
                ///
                ///Slide 26
                ///
                objSlide = objSlides[26];
                objShape = objSlide.Shapes[3];
                objShape.Delete();

                objSlide.Shapes.AddPicture(strHeatMap, Microsoft.Office.Core.MsoTriState.msoFalse,
                                           Microsoft.Office.Core.MsoTriState.msoTrue, 140, 120, 420, 330);


                ///
            }
            catch
            {
            }
        }
Пример #54
0
        /// <summary>
        /// If an instance of the PowerPoint application exits this method will export the notes of the active presentation to the selected file.
        /// </summary>
        public override void Perform()
        {
            streamWriter = null;

            if (File.Exists(fileName))
            {
                try
                {
                    // If the file exists we try to open it
                    FileStream stream = File.Open(fileName, FileMode.Create);
                    streamWriter = new StreamWriter(stream);
                }
                catch (Exception ex)
                {
                    ErrorLog.AddError(ErrorType.Failure, Strings.General_CantOpenFile);
                    Logger.WriteLine(ex.Message);
                    return;
                }
            }
            else
            {
                ErrorLog.AddError(ErrorType.Failure, Strings.General_FileNotFound);
                return;
            }

            try
            {
                app = (OPowerPoint.Application)Marshal.GetActiveObject("PowerPoint.Application");
            }
            catch (Exception ex)
            {
                ErrorLog.AddError(ErrorType.Failure, Strings.PowerPoint_ApplicationNotFound);
                Logger.WriteLine(ex);

                try
                {
                    if (streamWriter != null)
                    {
                        streamWriter.Close();
                    }
                }
                catch (IOException e)
                {
                    ErrorLog.AddError(ErrorType.Failure, Strings.CantCloseFileStream);
                    Logger.WriteLine(e);
                }

                return;
            }

            try
            {
                OPowerPoint.Presentation activePresentation = app.ActivePresentation;

                if (activePresentation == null)
                {
                    ErrorLog.AddError(ErrorType.Failure, Strings.PowerPoint_NoActivePresentation);
                }
                else
                if (!activePresentation.HasNotesMaster)
                {
                    // The current presentation doesn't have notes
                    ErrorLog.AddError(ErrorType.Message, Strings.PowerPoint_NoNotes);
                }
                else
                {
                    foreach (OPowerPoint.Slide slide in activePresentation.Slides)
                    {
                        if (slide.HasNotesPage == Microsoft.Office.Core.MsoTriState.msoTrue)
                        {
                            // If we have notes(the notes are kept on the position 2 in the placeholders collection) we save their text in the selected file
                            if (slide.NotesPage.Shapes.Placeholders.Count >= 2)
                            {
                                streamWriter.WriteLine(slide.NotesPage.Shapes.Placeholders[2].TextFrame.TextRange.Text);
                            }
                        }
                    }
                }

                streamWriter.Close();
            }
            catch (Exception ex)
            {
                ErrorLog.AddError(ErrorType.Warning, Strings.PowerPoint_CantExportNotes);
                Logger.Write(ex);

                try
                {
                    if (streamWriter != null)
                    {
                        streamWriter.Close();
                    }
                }
                catch (IOException e)
                {
                    ErrorLog.AddError(ErrorType.Failure, Strings.CantCloseFileStream);
                    Logger.WriteLine(e);
                }
            }
            finally
            {
                app = null;
            }
        }
Пример #55
0
 public static void WarnForTweeterOnNew_AfterNewPresentation(Application powerpointApplication, Presentation presentation)
 {
     warnForTwitter();
 }
Пример #56
0
 public void Open(string File)
 {
     pptApplication  = new PPT.Application();
     pptPresentation = pptApplication.Presentations.Open(File, MsoTriState.msoFalse, MsoTriState.msoCTrue, MsoTriState.msoCTrue);
 }
Пример #57
0
 public PresentationConnector(ppt.Presentation ppt)
 {
     pptApp          = new ppt.Application();
     pptPresentation = ppt;
 }
Пример #58
0
        static void Main(string[] args)
        {
            Program p = new Program();

            p.ReadDataFromFile();

            PowerPoint.Application   PowerPoint_App      = new PowerPoint.Application();
            PowerPoint.Presentations multi_presentations = PowerPoint_App.Presentations;
            PowerPoint.Presentation  presentation        = multi_presentations.Open(
                p.slideMasterPath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
            PowerPoint.TextFrame2.TextRange objText;

            var slideNum = presentation.Slides.Count;

            // i : the index of slide in master presentation
            for (int i = 1; i < slideNum; i++)
            {
                // j: the index of shapes in master presentation
                // j = 1: Word
                // j = 2: Kanji if any
                // j = 3: Meaning in Vietnamese
                // j = 4: Meaning in English
                // j = 5: Image
                for (int j = 0; j < 5; j++)
                {
                    // Get object of the current shape
                    PowerPoint.Shape shape = presentation.Slides[i + 1].Shapes[j + 1];

                    if (j < 4)
                    {
                        // Get object text range of this shape to insert text
                        objText = shape.TextFrame2.TextRange;
                        // Assign text read from data file to shape
                        objText.Text = p.fLine[i - 1, j];
                        // To fit text into shape
                        shape.TextFrame2.AutoSize = MsoAutoSize.msoAutoSizeTextToFitShape;
                    }
                    else if (j == 4)   // In case of shape to insert image
                    {
                        // Get the image link from data file
                        string imgFile = p.fLine[i - 1, j];

                        // Insert picture into the current shape
                        presentation.Slides[i + 1].Shapes.AddPicture(
                            imgFile, MsoTriState.msoTrue, MsoTriState.msoTrue,
                            shape.Left, shape.Top, shape.Width, shape.Height);
                    }
                }


                /*
                 * foreach (var item in presentation.Slides[i+1].Shapes)
                 * {
                 *  var shape = (PowerPoint.Shape)item;
                 *
                 *  if (shape.HasTextFrame == MsoTriState.msoTrue)
                 *  {
                 *      if (shape.TextFrame.HasText == MsoTriState.msoTrue)
                 *      {
                 *
                 *          shape.TextFrame.TextRange.Delete();
                 *          objText = shape.TextFrame.TextRange;
                 *          objText.Text = "I caught ya!!!";
                 *          objText.Font.Name = "Arial";
                 *          objText.Font.Size = 18;
                 *          //shape.TextFrame.TextRange.InsertAfter("Oh yeah I caught you!!!");
                 *          //textBox.TextFrame.TextRange.InsertAfter("Yes I am fine!");
                 *      }
                 *  }
                 * }
                 */
            }

            presentation.SaveAs(
                p.resultPath,
                PowerPoint.PpSaveAsFileType.ppSaveAsDefault,
                MsoTriState.msoTriStateMixed);

            PowerPoint_App.Quit();
        }
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ((Button)sender).IsEnabled = false;
                // Ouverture de Powerpoint, et création d'une nouvelle présentation
                app  = new PowerPoint.Application();
                pptx = app.Presentations.Add(Office.MsoTriState.msoTrue); // msoFalse permet de travailler en arrière plan sans afficher Office

                // On applique un thème
                string themePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase), "Circuit.thmx");
                pptx.ApplyTheme(themePath);

                // Les 2 layouts de slides qu'on utilise
                var titleLayout   = pptx.SlideMaster.CustomLayouts[1];
                var contentLayout = pptx.SlideMaster.CustomLayouts[2];

                // On parcours le texte pour créer les slides
                var          content = pptcontent.Text;
                StringReader reader  = new StringReader(content);

                int              currentIndex = 1;
                string           line;
                PowerPoint.Slide slide = null;
                while ((line = reader.ReadLine()) != null)
                {
                    if (string.IsNullOrWhiteSpace(line))
                    {
                        continue;
                    }

                    if (line.StartsWith("= "))
                    {
                        // Slide de titre
                        slide = pptx.Slides.AddSlide(currentIndex++, titleLayout);
                        slide.Shapes[1].TextFrame.TextRange.Text = line.Substring(2);
                    }
                    else if (line.StartsWith("# "))
                    {
                        // Le délais n'est là que pour ajouter un effet dramatique pendant la démo, enlevez le pour aller plus vite
                        await Task.Delay(150);

                        // Nouvelle slide de contenu
                        slide = pptx.Slides.AddSlide(currentIndex++, contentLayout);
                        slide.Shapes[1].TextFrame.TextRange.Text = line.Substring(2);
                    }
                    else
                    {
                        // On ajoute la ligne à la dernière slide
                        slide.Shapes[2].TextFrame.TextRange.Text += line + Environment.NewLine;
                    }
                }

                // Sauvegarde du document
                // pptx.SaveAs(@"C:\Temp\slides.pptx");
            }
            finally
            {
                // Ici je garde le document ouvert pour la démo,
                // normalement on pense toujours à fermer Office
                //if (pptx != null) pptx.Close();
                //if (app != null) app.Quit();
                ((Button)sender).IsEnabled = true;
            }
        }
Пример #60
0
        public void buttonSAB_Click(Office.IRibbonControl control)
        {
            // 現在開いているファイルを確認
            int iOpenFileCnt = 0;

            PowerPoint.Application pptApp = (PowerPoint.Application)global::PowerPointAddInSAB.Globals.ThisAddIn.Application;
            iOpenFileCnt = pptApp.Presentations.Count;

            if (iOpenFileCnt == 0)
            {
                return;
            }

            // 言語設定を取得
            string currentUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture.ToString();

            // プロパティ情報取得
            SettingForm settingForm = new SettingForm();

            settingForm.propPres = pptApp.ActivePresentation;

            // 共通設定エラー時処理
            if (settingForm.commonFileReadCompleted == false)
            {
                return;
            }

            // 共通設定ファイルと言語設定が異なる場合は言語設定を反映
            string strCulture = settingForm.clsCommonSettting.strCulture;

            if (currentUICulture != strCulture)
            {
                System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.GetCultureInfo(strCulture);
                System.Threading.Thread.CurrentThread.CurrentUICulture = culture;

                settingForm = new SettingForm();
            }

            // プロパティのセキュリティ情報が存在するか
            if (settingForm.IsSecrecyInfoRegistered() == true)
            {
                string filePropertySecrecyLevel = string.Empty; // ファイルプロパティ情報 機密区分
                string filePropertyClassNo      = string.Empty; // ファイルプロパティ情報 文書No.
                string filePropertyOfficeCode   = string.Empty; // ファイルプロパティ情報 事業所コード

                // ファイルプロパティ情報取得
                settingForm.GetDocumentProperty(ref filePropertySecrecyLevel, ref filePropertyClassNo, ref filePropertyOfficeCode);

                // プロパティ情報があればインフォメーション画面表示
                AddInsLibrary.InfomationForm infomationForm =
                    new AddInsLibrary.InfomationForm(filePropertySecrecyLevel);

                // SAB機密区分表示画面を表示
                System.Windows.Forms.DialogResult dialogResult = infomationForm.ShowDialog();

                // 修正ボタンが押されたら設定画面を表示
                if (dialogResult == System.Windows.Forms.DialogResult.OK)
                {
                    settingForm.ShowDialog();
                }
            }
            else
            {
                // プロパティ情報がなければ設定画面表示
                settingForm.ShowDialog();
            }
        }