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

来源:http://www.cnblogs.com/FreedomAndLove/archive/2017/10/18/4481079.html
-Advertisement-
Play Games

自己上網查了好多種方法,最後還是選了這種不收費,還挺好用的方法 為了用戶有一個好的體驗我將word、excel、ppt轉Pdf,Pdf轉Swf寫在服務上,因為我當時做的時候Pdf轉Swf會執行pdf2swf.exe彈出黑框,對用戶體驗不好,還有就是ppt轉swf時會有一個彈出框,提示正在發佈,我沒搞 ...


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

           為了用戶有一個好的體驗我將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


    }
  • PDF2SwfHelper
 1         #region 1.0 轉換所有的頁,圖片質量100% +  bool PDF2SWF(string pdfPath, string swfPath)
 2         /// <summary>
 3         /// 轉換所有的頁,圖片質量100%
 4         /// </summary>
 5         /// <param name="pdfPath">PDF文件地址</param>
 6         /// <param name="swfPath">生成後的SWF文件地址</param>
 7         public static bool PDF2SWF(string pdfPath, string swfPath)
 8         {
 9             return PDF2SWF(pdfPath, swfPath, 1, GetPageCount(pdfPath), 100);
10         } 
11         #endregion
12 
13         #region 2.0 轉換前N頁,圖片質量100% + bool PDF2SWF(string pdfPath, string swfPath, int page)
14         /// <summary>
15         /// 轉換前N頁,圖片質量100%
16         /// </summary>
17         /// <param name="pdfPath">PDF文件地址</param>
18         /// <param name="swfPath">生成後的SWF文件地址</param>
19         /// <param name="page">頁數</param>
20         public static bool PDF2SWF(string pdfPath, string swfPath, int page)
21         {
22             return PDF2SWF(pdfPath, swfPath, 1, page, 100);
23         } 
24         #endregion
25 
26         #region 3.0 PDF格式轉為SWF + bool PDF2SWF(string pdfPath, string swfPath, int beginpage, int endpage, int photoQuality)
27         /// <summary>
28         /// PDF格式轉為SWF
29         /// </summary>
30         /// <param name="pdfPath">PDF文件地址</param>
31         /// <param name="swfPath">生成後的SWF文件地址</param>
32         /// <param name="beginpage">轉換開始頁</param>
33         /// <param name="endpage">轉換結束頁</param>
34         private static bool PDF2SWF(string pdfPath, string swfPath, int beginpage, int endpage, int photoQuality)
35         {
36             
37             //swftool,首先先安裝,然後將安裝目錄下的東西拷貝到相應目錄下
38             string exe = System.IO.Path.GetFullPath("pdf2swf.exe");
39             //string exe = System.Web.Hosting.HostingEnvironment.MapPath("~");
40             //pdfPath = HttpContext.Current.Server.MapPath(pdfPath);
41             //swfPath = HttpContext.Current.Server.MapPath(swfPath);
42             if (!System.IO.File.Exists(exe) || !System.IO.File.Exists(pdfPath))
43             {
44                 return false;
45             }
46             StringBuilder sb = new StringBuilder();
47             sb.Append(" \"" + pdfPath + "\"");
48             sb.Append(" -o \"" + swfPath + "\"");
49             sb.Append(" -s flashversion=9");
50             if (endpage > GetPageCount(pdfPath)) endpage = GetPageCount(pdfPath);
51             sb.Append(" -p " + "\"" + beginpage + "" + "-" + endpage + "\"");
52             sb.Append(" -j " + photoQuality);
53             string Command = sb.ToString();
54             System.Diagnostics.Process p = new System.Diagnostics.Process();
55             p.StartInfo.FileName = exe;
56             p.StartInfo.Arguments = Command;
57             p.StartInfo.WorkingDirectory = System.IO.Path.GetFullPath("../Release/");
58             string ss = p.StartInfo.WorkingDirectory;
59             p.StartInfo.UseShellExecute = false;
60             p.StartInfo.RedirectStandardError = true;
61             p.StartInfo.CreateNoWindow = false;
62             p.Start();
63             p.BeginErrorReadLine();
64             p.WaitForExit();
65             p.Close();
66             p.Dispose();
67             return true;
68         }
69         
70         #endregion
71 
72         #region 4.0 返回頁數 + int GetPageCount(string pdfPath)
73         /// <summary>
74         /// 返回頁數
75         /// </summary>
76         /// <param name="pdfPath">PDF文件地址</param>
77         private static int GetPageCount(string pdfPath)
78         {
79             byte[] buffer = System.IO.File.ReadAllBytes(pdfPath);
80             int length = buffer.Length;
81             if (buffer == null)
82                 return -1;
83             if (buffer.Length <= 0)
84                 return -1;
85             string pdfText = Encoding.Default.GetString(buffer);
86             System.Text.RegularExpressions.Regex rx1 = new System.Text.RegularExpressions.Regex(@"/Type\s*/Page[^s]");
87             System.Text.RegularExpressions.MatchCollection matches = rx1.Matches(pdfText);
88             return matches.Count;
89         } 
90         #endregion
  • 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>

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 做慣了後臺的沐雨一向覺得數據列表是一個系統裡面最重要的東西 所以熟悉ext也就從表格開始入手了 想看官方代碼的同學進這裡 官方預設表格教程 或是直接看我的也行,直接拷貝過來的 另外官方文檔沒有中文版的讓我這個二級都沒過的學渣倍感壓力啊 1. Views部分代碼 官方文檔一直沒看到下圖Layout的代 ...
  • MemLoadDll.h MemLoadDll.cpp ...
  • 轉自:http://blog.csdn.net/jxufewbt/article/details/1769312 應用程式之間的數據交換(互相通訊)一直是困擾廣大程式員的難題,儘管已經出現了各式各樣的解決方案,但迄今為止沒有哪一種方案是完美無缺的。因此,只有學習並瞭解了它們的優缺點後,才能在特定的情 ...
  • string param = "<xml>" +"<ToUserName><![CDATA[toUser]]></ToUserName>" +"<FromUserName><![CDATA[fromUser]] ></FromUserName>" +"<CreateTime> 1348831860 ...
  • 很多C 的初學者都會有這麼一個疑問, .Net程式代碼是如何被機器載入執行的? 最簡單的解答是, C 會通過編譯器(CodeDom, Roslyn)編譯成IL代碼, 然後CLR(.Net Framework, .Net Core, Mono)會把這些IL代碼編譯成目標機器的機器代碼並執行. 相信大多 ...
  • 30分鐘?不需要,輕鬆讀懂IL http://www.cnblogs.com/brookshi/p/5225801.html IL指令詳細 http://www.cnblogs.com/zery/p/3368460.html 進階篇:以IL為劍,直指async/await http://www.cn ...
  • 前言:去年剛工作的時候,也是剛剛正式接觸.net,當時瞭解了EF以及三種開發模式,Database First、Model First 、Code First。公司用的開發模式是Database First,由於公司有一套成熟的框架,我只需要按部就班的開發即可,因此就沒有詳細學習過這些開發模式,總覺 ...
  • C#多線程 一、使用線程的理由 1、可以使用線程將代碼同其他代碼隔離,提高應用程式的可靠性。 2、可以使用線程來簡化編碼。 3、可以使用線程來實現併發執行。 二、基本知識 1、進程與線程:進程作為操作系統執行程式的基本單位,擁有應用程式的資源,進程包含線程,進程的資源被線程共用,線程不擁有資源。 2 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...