Office 转 PDF & PDF 转 SWF Windows版

当网站有Office文件对外进行展示时,我们经常是不希望用户进行下载,而是在线进行预览。

这个时候就有必要把Office文件进行转换成SWF文件在网页中显示了

但现在还没有Office文件直接转化成SWF文件的方法,所以现在用PDF进行中转

也就是Office =》 PDF =》 SWF

以下是相应的转化代码(Windows环境):Linux版请点:Office 转 PDF & PDF 转 SWF Linux版

-----------------------------------------------------

添加Office2013引用

命令行方式接收

namespace OfficeToSWF
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                if (args.Length == 5)
                {
                    string type = args[0];
                    string officeFile = args[1];
                    string pdfFile = args[2];
                    string swfExe = args[3];
                    string swfName = args[4];
                    Timeout timeout = new Timeout();

                    if (type == "word")
                    {
                        timeout.Do = Word2PDF.Convert;
                    }
                    else if (type == "excel")
                    {
                        timeout.Do = Excel2PDF.Convert;
                    }
                    else if (type == "powerpoint")
                    {
                        timeout.Do = PowerPoint2PDF.Convert;
                    }
                    bool bo = timeout.DoWithTimeout(officeFile, pdfFile, new TimeSpan(0, 0, 0, 40));
                    //(officeFile, pdfFile)
                    if (bo == true)
                    {
                        Log("Do:超过40秒退出", pdfFile);
                    }

                    //生成SWF
                    try
                    {
                        string cmd = swfExe;
                        string argsSWF = "  -t \"" + pdfFile + "\" -s poly2bitmap flashversion=9 -o \"" + swfName + "\"";
                        Excute(cmd, argsSWF);
                        Console.Write("完成");
                    }
                    catch (Exception ex)
                    {
                        Log("pdfFile:" + pdfFile, ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }

        public static void Excute(string cmd, string args)
        {
            using (Process p = new Process())
            {
                ProcessStartInfo psi = new ProcessStartInfo(cmd, args);
                p.StartInfo = psi;
                p.Start();
                p.WaitForExit();
            }
        }


        private static string LogFilePath = (AppDomain.CurrentDomain.BaseDirectory + "log.txt");

        public static void Log(string title, string message)
        {
            using (StreamWriter sw = new StreamWriter(LogFilePath, true))
            {
                sw.WriteLine("----------------------------------------");
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss "));
                sw.WriteLine(title + message);
                sw.Close();
                sw.Dispose();
            }
            var file = new System.IO.FileInfo(LogFilePath);
            if (file.Length > 1024 * 1024)
            {
                file.Delete();
                file = null;
            }
        }
    }
}

  

因为调用Office不一定100%成功,有时不成功会卡死不关线程,这里进行定时断开

namespace OfficeToSWF
{
    public delegate bool DoHandler(string source, string target);
    public class Timeout
    {
        private ManualResetEvent mTimeoutObject;
        //标记变量
        private bool mBoTimeout;
        public DoHandler Do;

        public Timeout()
        {
            //  初始状态为 停止
            this.mTimeoutObject = new ManualResetEvent(true);
        }
        ///<summary>
        /// 指定超时时间 异步执行某个方法
        ///</summary>
        ///<returns>执行 是否超时</returns>
        public bool DoWithTimeout(string source, string target, TimeSpan timeSpan)
        {
            if (this.Do == null)
            {
                return false;
            }
            this.mTimeoutObject.Reset();
            this.mBoTimeout = true; //标记
            this.Do.BeginInvoke(source, target, DoAsyncCallBack, null);
            // 等待 信号Set
            if (!this.mTimeoutObject.WaitOne(timeSpan, false))
            {
                this.mBoTimeout = true;
            }
            return this.mBoTimeout;
        }
        ///<summary>
        /// 异步委托 回调函数
        ///</summary>
        ///<param name="result"></param>
        private void DoAsyncCallBack(IAsyncResult result)
        {
            try
            {
                this.Do.EndInvoke(result);
                // 指示方法的执行未超时
                this.mBoTimeout = false;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                this.mBoTimeout = true;
            }
            finally
            {
                this.mTimeoutObject.Set();
            }
        }
    }
}

  

 

以下是各类文件的转换代码

namespace OfficeToSWF
{
    public static class Excel2PDF
    {
        public static bool Convert(string sourcePath, string targetPath)
        {
            var targetType = XlFixedFormatType.xlTypePDF;
            bool result = false;
            object missing = Type.Missing;
            ApplicationClass application = null;
            Workbook workBook = null;
            try
            {
                application = new ApplicationClass();
                object target = targetPath;
                object type = targetType;
                workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing,
                        missing, missing, missing, missing, missing, missing, missing, missing, missing);

                workBook.ExportAsFixedFormat(targetType, target, XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing);
                result = true;
            }
            catch (Exception ex)
            {
                Program.Log("Excel:" + sourcePath + "=>" + targetPath, ex.Message);
            }
            finally
            {
                if (workBook != null)
                {
                    workBook.Close(true, missing, missing);
                    workBook = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }
    }
}

  

namespace OfficeToSWF
{
    public static class PowerPoint2PDF
    {
        //private static bool Convert(string sourcePath, string targetPath, PpSaveAsFileType targetFileType)
        public static bool Convert(string sourcePath, string targetPath)
        {
            var targetFileType = PpSaveAsFileType.ppSaveAsPDF;
            bool result = false;
            object missing = Type.Missing;
            ApplicationClass application = null;
            Presentation persentation = null;
            try
            {
                application = new Microsoft.Office.Interop.PowerPoint.ApplicationClass();
                persentation = application.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
                persentation.SaveAs(targetPath, targetFileType, Microsoft.Office.Core.MsoTriState.msoTrue);

                result = true;
            }
            catch (Exception ex)
            {
                Program.Log("Excel:" + sourcePath + "=>" + targetPath, ex.Message);
            }
            finally
            {
                if (persentation != null)
                {
                    persentation.Close();
                    persentation = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }
    }
}

  

namespace OfficeToSWF
{
    public static class Word2PDF
    {
        //public static bool Convert(string sourcePath, string targetPath, Microsoft.Office.Interop.Word.WdExportFormat exportFormat)
        public static bool Convert(string sourcePath, string targetPath)
        {
            var exportFormat = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF;
            bool result = false;
            object paramMissing = Type.Missing;
            Microsoft.Office.Interop.Word.ApplicationClass wordApplication = new Microsoft.Office.Interop.Word.ApplicationClass();
            Microsoft.Office.Interop.Word.Document wordDocument = null;
            try
            {
                object paramSourceDocPath = sourcePath;
                string paramExportFilePath = targetPath;

                Microsoft.Office.Interop.Word.WdExportFormat paramExportFormat = exportFormat;
                bool paramOpenAfterExport = false;
                Microsoft.Office.Interop.Word.WdExportOptimizeFor paramExportOptimizeFor =
                        Microsoft.Office.Interop.Word.WdExportOptimizeFor.wdExportOptimizeForPrint;
                Microsoft.Office.Interop.Word.WdExportRange paramExportRange = Microsoft.Office.Interop.Word.WdExportRange.wdExportAllDocument;
                int paramStartPage = 0;
                int paramEndPage = 0;
                Microsoft.Office.Interop.Word.WdExportItem paramExportItem = Microsoft.Office.Interop.Word.WdExportItem.wdExportDocumentContent;
                bool paramIncludeDocProps = true;
                bool paramKeepIRM = true;
                Microsoft.Office.Interop.Word.WdExportCreateBookmarks paramCreateBookmarks =
                        Microsoft.Office.Interop.Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks;
                bool paramDocStructureTags = true;
                bool paramBitmapMissingFonts = true;
                bool paramUseISO19005_1 = false;

                wordDocument = wordApplication.Documents.Open(
                        ref paramSourceDocPath, ref paramMissing, ref paramMissing,
                        ref paramMissing, ref paramMissing, ref paramMissing,
                        ref paramMissing, ref paramMissing, ref paramMissing,
                        ref paramMissing, ref paramMissing, ref paramMissing,
                        ref paramMissing, ref paramMissing, ref paramMissing,
                        ref paramMissing);

                if (wordDocument != null)
                    wordDocument.ExportAsFixedFormat(paramExportFilePath,
                            paramExportFormat, paramOpenAfterExport,
                            paramExportOptimizeFor, paramExportRange, paramStartPage,
                            paramEndPage, paramExportItem, paramIncludeDocProps,
                            paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                            paramBitmapMissingFonts, paramUseISO19005_1,
                            ref paramMissing);
                result = true;
            }
            catch (Exception ex)
            {
                Program.Log("WORD:" + sourcePath + "=>" + targetPath, ex.Message);
            }
            finally
            {
                if (wordDocument != null)
                {
                    wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordDocument = null;
                }
                if (wordApplication != null)
                {
                    wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordApplication = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }
    }
}

  

posted @ 2015-09-01 17:13  张永存(Jerry)  阅读(349)  评论(0编辑  收藏  举报