1. 程式人生 > >.net 實現word、excel、ppt、pdf預覽功能

.net 實現word、excel、ppt、pdf預覽功能

先說一下我的思路:word-->pdf-->swf-->顯示  我是把word最終用flash 來顯示,所以要經過兩個步驟來轉化

第一步  word轉pdf (其他文件一樣

1.引用微軟的office元件

如上圖,當然你必須先安裝office2007或office2010,直接編譯會報錯

解決方案是把嵌入互操作型別改為false ,如下圖

using System;
using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Core;
using System.IO;

namespace SZHomeCRM.Common
{
    /// <summary>
    /// Office2Pdf 將Office文件轉化為pdf
    /// </summary>
    public class OfficeToPdf
    {
        /// <summary>
        /// Word轉換成pdf
        /// </summary>
        /// <param name="sourcePath">原始檔路徑</param>
        /// <param name="targetPath">目標檔案路徑</param>
        /// <returns>true=轉換成功</returns>
        public static bool DOCConvertToPDF(string sourcePath,string targetPath)
        {
            bool result = false;
            if (File.Exists(targetPath))
            {
                result = true;
                return result;
            }
            string targetDic=Path.GetDirectoryName(targetPath);
            if (!Directory.Exists(targetDic))
            {
                Directory.CreateDirectory(targetDic);
            }
            Word.WdExportFormat exportFormat = Word.WdExportFormat.wdExportFormatPDF;
            object paramMissing = Type.Missing;
            Word.ApplicationClass wordApplication = new Word.ApplicationClass();
            Word.Document wordDocument = null;
            try
            {
                object paramSourceDocPath = sourcePath;
                string paramExportFilePath = targetPath;
                Word.WdExportFormat paramExportFormat = exportFormat;
                bool paramOpenAfterExport = false;
                Word.WdExportOptimizeFor paramExportOptimizeFor = Word.WdExportOptimizeFor.wdExportOptimizeForPrint;
                Word.WdExportRange paramExportRange = Word.WdExportRange.wdExportAllDocument;
                int paramStartPage = 0;
                int paramEndPage = 0;
                Word.WdExportItem paramExportItem = Word.WdExportItem.wdExportDocumentContent;
                bool paramIncludeDocProps = true;
                bool paramKeepIRM = true;
                Word.WdExportCreateBookmarks paramCreateBookmarks = 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)
            {
                result = false;
                throw new ApplicationException(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();
            }
            return result;
        }

        /// <summary>
        /// 把Excel檔案轉換成PDF格式檔案  
        /// </summary>
        /// <param name="sourcePath">原始檔路徑</param>
        /// <param name="targetPath">目標檔案路徑</param>
        /// <returns>true=轉換成功</returns>
        public static bool XLSConvertToPDF(string sourcePath, string targetPath)
        {
            bool result = false;
            if (File.Exists(targetPath))
            {
                result = true;
                return result;
            }
            string targetDic = Path.GetDirectoryName(targetPath);
            if (!Directory.Exists(targetDic))
            {
                Directory.CreateDirectory(targetDic);
            }
            Excel.XlFixedFormatType targetType = Excel.XlFixedFormatType.xlTypePDF;
            object missing = Type.Missing;
            Excel.ApplicationClass application = null;
            Excel.Workbook workBook = null;
            try
            {
                application = new Excel.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, Excel.XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing);
                result = true;
            }
            catch(Exception ex)
            {
                result = false;
                throw new ApplicationException(ex.Message);
            }
            finally
            {
                if (workBook != null)
                {
                    workBook.Close(true, missing, missing);
                    workBook = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }

        ///<summary>        
        /// 把PowerPoint檔案轉換成PDF格式檔案       
        ///</summary>        
        ///<param name="sourcePath">原始檔路徑</param>     
        ///<param name="targetPath">目標檔案路徑</param> 
        ///<returns>true=轉換成功</returns> 
        public static bool PPTConvertToPDF(string sourcePath, string targetPath)
        {
            bool result = false;
            if (File.Exists(targetPath))
            {
                result = true;
                return result;
            }
            string targetDic = Path.GetDirectoryName(targetPath);
            if (!Directory.Exists(targetDic))
            {
                Directory.CreateDirectory(targetDic);
            }
            PowerPoint.PpSaveAsFileType targetFileType = PowerPoint.PpSaveAsFileType.ppSaveAsPDF;
            object missing = Type.Missing;
            PowerPoint.ApplicationClass application = null;
            PowerPoint.Presentation persentation = null;
            try
            {
                application = new 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)
            {
                result = false;
                throw new ApplicationException(ex.Message);
            }
            finally
            {
                if (persentation != null)
                {
                    persentation.Close();
                    persentation = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }
    }

}

  轉化程式碼如上,對於已轉化的檔案就直接返回,這樣能大大加快訪問速度

第二步  把pdf 轉化為swf 

這個很簡單,就是安裝一個轉化工具即可 swftools-0.9.0,百度一下下載

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;
using System.Web;
using SZHomeDLL;

namespace SZHomeCRM.Common
{
    public class PdfToSwf
    {
        public static void ConvertToSwf(string pdfPath, string swfPath)
        {
            try
            {
                if (File.Exists(swfPath))
                {
                    return ;
                }
                string targetDic = Path.GetDirectoryName(swfPath);
                if (!Directory.Exists(targetDic))
                {
                    Directory.CreateDirectory(targetDic);
                }
                string exe = ConfigHelper.GetConfigString("pdf2swfPath");
                if (!File.Exists(exe))
                {
                    throw new ApplicationException("Can not find: " + exe);
                }
                StringBuilder sb = new StringBuilder();
                int endPage = GetPageCount(pdfPath);

                sb.Append(" -o \"" + swfPath + "\"");//output

                sb.Append(" -z");

                sb.Append(" -s flashversion=9");//flash version

                sb.Append(" -s disablelinks");//禁止PDF裡面的連結

                sb.Append(" -p " + "1" + "-" + endPage);//page range

                sb.Append(" -j 100");//Set quality of embedded jpeg pictures to quality. 0 is worst (small), 100 is best (big). (default:85)

                sb.Append(" \"" + pdfPath + "\"");//input

                Process proc = new Process();

                proc.StartInfo.FileName = exe;

                proc.StartInfo.Arguments = sb.ToString();

                proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

                proc.Start();

                proc.WaitForExit();

                proc.Close();

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>

        /// 返回頁數

        /// </summary>

        /// <param name="pdfPath">PDF檔案地址</param>

        private static int GetPageCount(string pdfPath)
        {

            byte[] buffer = System.IO.File.ReadAllBytes(pdfPath);

            int length = buffer.Length;

            if (buffer == null)

                return -1;

            if (buffer.Length <= 0)

                return -1;

            string pdfText = Encoding.Default.GetString(buffer);

            System.Text.RegularExpressions.Regex rx1 = new System.Text.RegularExpressions.Regex(@"/Type\s*/Page[^s]");

            System.Text.RegularExpressions.MatchCollection matches = rx1.Matches(pdfText);

            return matches.Count;

        }


    }
}

  以上就是轉化程式碼,pdf2swfPath 是配置轉化工具的安裝路徑  

到這裡就已經把word轉化成了swf,最後就是要顯示的問題了

第三步  用 flexpaper來顯示 ,點選下載附件

在本地測試的時候一切順利,沒成想部署到伺服器上時一堆問題,真是令人崩潰。

第一個錯誤就是

百度一查說是許可權的問題,好了那就按上面的配置唄,這過程也有些曲折

一.安裝office 2007 和 SaveAsPDFandXPS 或 安裝office 2010
二.設定元件許可權
1. 在"開始"->"執行"中輸入dcomcnfg.exe啟動"元件服務" (comexp.msc -32)
2. 依次雙擊"元件服務"->"計算機"->"我的電腦"->"DCOM配置"
3:在"DCOM配置"中找到"Microsoft word 應用程式",在它上面點選右鍵,然後點選"屬性",彈出"Microsoft word 應用程式屬性"對話方塊
4.點選"標識"標籤,選擇"互動式使用者"
5:點選"安全"標籤,在"啟動和啟用許可權"上點選"自定義",然後點選對應的"編輯"按鈕,在彈出的"安全性"對話方塊中填加一個"authenticated users"使用者(注意要選擇本計算機名),並給它賦予"本地啟動"和"本地啟用"許可權.
6:依然是"安全"標籤,在"訪問許可權"上點選"自定義",然後點選"編輯",在彈出的"安全性"對話方塊中也填加一個"authenticated users"使用者,然後賦予"本地訪問"許可權.

注:網上查到的方法是新增 “NETWORK SERVICE”使用者 我試了不行,換成 “authenticated users”就可以了

總結:剛做的時候感覺有點複雜,完成之後再理了理思路就簡單多了。剛部署的伺服器的時候有問題,我又不好操作伺服器,就只能先在本機裝一個虛擬機器hyper-v,配置一個生產環境,要學習怎麼裝虛擬機器,要裝作業系統,要怎麼共享網路,要怎麼共享檔案等等,感覺這次接觸的新東西蠻多,收穫也多,下次有時間寫寫這方面的東西。 希望可以幫到有需求的人。

注:如果你還有疑問,可以留言....