word,excel,ppt轉Pdf,Pdf轉Swf,通過flexpaper+swftools實現在線預覽


  • 其實這是我好幾年前的項目,現在再用這種方式我也不建議了,畢竟未來flash慢慢會淘汰,此方式也是因為目測大部分人都裝了flash,才這么做的,但是頁面展示效果也不好。其實還是考慮收費的控件,畢竟收費的還是做的不錯的!

而且此方式服務器要安裝office組件,項目實施也不好!

以上為最新更新建議!

 

  • 自己上網查了好多種方法,最后還是選了這種不收費,還挺好用的方法

           為了用戶有一個好的體驗我將word、excel、ppt轉Pdf,Pdf轉Swf寫在服務上,因為我當時做的時候Pdf轉Swf會執行pdf2swf.exe彈出黑框,對用戶體驗不好,還有就是ppt轉swf時會有一個彈出框,提示正在發布,我沒搞明白,就把他們都寫在服務上了。

  • Office2Pdf
/// <summary>
    /// Office2Pdf 將Office文檔轉化為pdf
    /// </summary>
    public class Office2PDFHelper
    {
        public Office2PDFHelper()
        {
            //
            // TODO: 在此處添加構造函數邏輯
            //
        }
        #region 1.0 Word轉換成pdf + bool DOCConvertToPDF(string sourcePath, string targetPath)
        /// <summary>
        /// Word轉換成pdf
        /// </summary>
        /// <param name="sourcePath">源文件路徑(物理路徑)</param>
        /// <param name="targetPath">目標文件路徑(物理路徑)</param>
        /// <returns>true=轉換成功</returns>
        public static bool DOCConvertToPDF(string sourcePath, string targetPath)
        {
        //    string targetPath = "G:\\工作\\ceshi\\ceshi.pdf";
        //    sourcePath = "G:\\工作\\OfficePreview\\Preview\\SourceFile\\測試.doc"; 
            bool result = false;
            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
            {
                result = false;
            }
            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;
        } 
        #endregion

        #region 2.0 把Excel文件轉換成PDF格式文件 + 把Excel文件轉換成PDF格式文件  
        /// <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;
            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
            {
                result = false;
            }
            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;
        } 
        #endregion

        #region 3.0 把PowerPoint文件轉換成PDF格式文件   + bool PPTConvertToPDF(string sourcePath, string targetPath)
        ///<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;
            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);
                if (persentation != null)
                {
                    //寫入
                    persentation.SaveAs(targetPath, targetFileType, MsoTriState.msoTrue);
                }
                result = true;
            }
            catch
            {
                result = false;
            }
            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;
        } 
        #endregion


    }
View Code
  • PDF2SwfHelper
#region 1.0 轉換所有的頁,圖片質量100% +  bool PDF2SWF(string pdfPath, string swfPath)
        /// <summary>
        /// 轉換所有的頁,圖片質量100%
        /// </summary>
        /// <param name="pdfPath">PDF文件地址</param>
        /// <param name="swfPath">生成后的SWF文件地址</param>
        public static bool PDF2SWF(string pdfPath, string swfPath)
        {
            return PDF2SWF(pdfPath, swfPath, 1, GetPageCount(pdfPath), 100);
        } 
        #endregion

        #region 2.0 轉換前N頁,圖片質量100% + bool PDF2SWF(string pdfPath, string swfPath, int page)
        /// <summary>
        /// 轉換前N頁,圖片質量100%
        /// </summary>
        /// <param name="pdfPath">PDF文件地址</param>
        /// <param name="swfPath">生成后的SWF文件地址</param>
        /// <param name="page">頁數</param>
        public static bool PDF2SWF(string pdfPath, string swfPath, int page)
        {
            return PDF2SWF(pdfPath, swfPath, 1, page, 100);
        } 
        #endregion

        #region 3.0 PDF格式轉為SWF + bool PDF2SWF(string pdfPath, string swfPath, int beginpage, int endpage, int photoQuality)
        /// <summary>
        /// PDF格式轉為SWF
        /// </summary>
        /// <param name="pdfPath">PDF文件地址</param>
        /// <param name="swfPath">生成后的SWF文件地址</param>
        /// <param name="beginpage">轉換開始頁</param>
        /// <param name="endpage">轉換結束頁</param>
        private static bool PDF2SWF(string pdfPath, string swfPath, int beginpage, int endpage, int photoQuality)
        {
            
            //swftool,首先先安裝,然后將安裝目錄下的東西拷貝到相應目錄下
            string exe = System.IO.Path.GetFullPath("pdf2swf.exe");
            //string exe = System.Web.Hosting.HostingEnvironment.MapPath("~");
            //pdfPath = HttpContext.Current.Server.MapPath(pdfPath);
            //swfPath = HttpContext.Current.Server.MapPath(swfPath);
            if (!System.IO.File.Exists(exe) || !System.IO.File.Exists(pdfPath))
            {
                return false;
            }
            StringBuilder sb = new StringBuilder();
            sb.Append(" \"" + pdfPath + "\"");
            sb.Append(" -o \"" + swfPath + "\"");
            sb.Append(" -s flashversion=9");
            if (endpage > GetPageCount(pdfPath)) endpage = GetPageCount(pdfPath);
            sb.Append(" -p " + "\"" + beginpage + "" + "-" + endpage + "\"");
            sb.Append(" -j " + photoQuality);
            string Command = sb.ToString();
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = exe;
            p.StartInfo.Arguments = Command;
            p.StartInfo.WorkingDirectory = System.IO.Path.GetFullPath("../Release/");
            string ss = p.StartInfo.WorkingDirectory;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = false;
            p.Start();
            p.BeginErrorReadLine();
            p.WaitForExit();
            p.Close();
            p.Dispose();
            return true;
        }
        
        #endregion

        #region 4.0 返回頁數 + int GetPageCount(string pdfPath)
        /// <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;
        } 
        #endregion
View Code

 

  • flexpaper+swftools
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="OfficePreview.aspx.cs" Inherits="Preview.OfficePreview" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- saved from url=(0014)about:internet -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script src="js/swfPreview/jquery.js" type="text/javascript"></script>
    <script src="js/swfPreview/flexpaper_flash_debug.js" type="text/javascript"></script>
    <script src="js/swfPreview/flexpaper_flash.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            var winWidth = 0;
            var winHeight = 0;
            function findDimensions() //函數:獲取尺寸 
            {
                ////獲取窗口寬度 
                //if (window.innerWidth)
                //    winWidth = window.innerWidth;
                //else if ((document.body) && (document.body.clientWidth))
                //    winWidth = document.body.clientWidth;

                //獲取窗口高度 
                if (window.innerHeight)
                    winHeight = window.innerHeight;
                else if ((document.body) && (document.body.clientHeight))
                    winHeight = document.body.clientHeight;
                //通過深入Document內部對body進行檢測,獲取窗口大小 && document.documentElement.clientWidth
                if (document.documentElement && document.documentElement.clientHeight) {
                    winHeight = document.documentElement.clientHeight;
                    //winWidth = document.documentElement.clientWidth;
                }
                //高度
                $("#viewerPlaceHolder").height(winHeight);
            }
            findDimensions();
            //調用函數,獲取數值 
            window.onresize = findDimensions;
        })
    </script>
    <style type="text/css">
        body
        {
            margin-left: 0px;
            margin-top: 0px;
            margin-bottom: 0px;
            margin-right: 0px;
            height: 100%;
        }

        #div1
        {
            margin: 0px auto;
            /*border: 0px solid #0094ff;*/
            width: 100%;
            height: 100%;
        }

        #viewerPlaceHolder
        {
            /*height: 598px;*/
        }
    </style>
</head>
<body style="overflow-y: hidden">
    <div id="center">
        <a id="viewerPlaceHolder" style="display: block;"></a>
        <script type="text/javascript">
            $(function () {
                $("#pageloading").show();
                var fp = new FlexPaperViewer(
       'js/swfPreview/FlexPaperViewer',
       'viewerPlaceHolder',
       {
           config: {
               SwfFile: escape('TargetFile/Swf/swf.swf'),//這里是要顯示的swf的位置,相對根目錄
               Scale: 1,//縮放比例
               ZoomTransition: 'easeOut',//Flexpaper中縮放樣式,它使用和Tweener一樣的樣式,默認參數值為easeOut.其他可選值包括: easenone, easeout, linear, easeoutquad
               ZoomTime: 0.5,//從一個縮放比例變為另外一個縮放比例需要花費的時間,該參數值應該為0或更大。
               ZoomInterval: 0.2,//縮放比例之間間隔,默認值為0.1,該值為正數。
               FitPageOnLoad: false,//初始化的時候自適應頁面,與使用工具欄上的適應頁面按鈕同樣的效果。
               FitWidthOnLoad: false,//初始化的時候自適應頁面寬度,與工具欄上的適應寬度按鈕同樣的效果。
               PrintEnabled: false,//是否支持打印
               FullScreenAsMaxWindow: false,//是否支持打印
               ProgressiveLoading: false,//當設置為true的時候,展示文檔時不會加載完整個文檔,而是逐步加載,但是需要將文檔轉化為9以上的flash版本(使用pdf2swf的時候使用-T 9 標簽)。
               MinZoomSize: 0.2,//最小的縮放比例。
               MaxZoomSize: 5,//設置最大的縮放比例。
               SearchMatchAll: false,//設置為true的時候,單擊搜索所有符合條件的地方高亮顯示。
               InitViewMode: 'TwoPage',//啟動模式,如”Portrait” or “TwoPage”.
               ViewModeToolsVisible: false,//工具欄上是否顯示樣式選擇框(就是顯示縮略圖或分頁顯示的工具)
               ZoomToolsVisible: true,//工具欄上是否顯示縮放工具
               NavToolsVisible: false,//工具欄上是否顯示導航工具(也就是頁碼工具)
               CursorToolsVisible: true,//工具欄上是否顯示光標工具
               SearchToolsVisible: true,//工具欄上是否顯示搜索
               localeChain: 'zh_CN'//語言
           }
       }
       );
                $("#pageloading").fadeOut(1000);
            });
        </script>
    </div>
    <div id="pageloading" style="background-color: White; width: 100%; height: 100%; position: fixed; top: 0; left: 0; display: none; text-align: center; margin: 0px auto; vertical-align: middle; z-index: 999">
        <img src="/images/loading.gif" style="width: 48px; height: 48px; position: fixed; top: 45%; left: 45%; right: 50%; bottom: 50%;" />
    </div>
    <div id="txtPreview" style="width: 100%; height: 100%; top: 0; left: 0;">
        <pre id="pre"></pre>
    </div>
</body>
</html>
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM