類似百度文庫在線預覽文檔flash版(支持word、excel、ppt、pdf)+在線預覽文檔html版

清明假期最後一天寫點東西吧,明天就要上課了。最近在學習如何進行文檔的在線預覽。

1.首先上網搜索一下有什麼解決方案 (1).將文檔轉換爲html,只支持支持office文檔 (2).將文檔轉換爲flash,實現類似百度文庫的效果,除支持office文檔外還支持pdf

  (1) a.首先添加引用:

using Microsoft.Office.Core;
using Word = Microsoft.Office.Interop.Word;

  b.其次編寫文檔轉換的方法:

複製代碼
 1     /// <summary> 2     /// word轉成html
 3     /// </summary> 4     /// <param name="path">要轉換的文檔的路徑</param> 5     /// <param name="savePath">轉換成的html的保存路徑</param> 6     /// <param name="wordFileName">轉換後html文件的名字</param> 7     private static void WordToHtml(string path, string savePath, string wordFileName)
 8     {
 9       Word.ApplicationClass word = new Word.ApplicationClass();
10         Type wordType = word.GetType();
11         Word.Documents docs = word.Documents;
12         Type docsType = docs.GetType();
13         Word.Document doc = (Word.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] {(object)path, true, true });
14      Type docType = doc.GetType();
15         string strSaveFileName = savePath + wordFileName + ".html";
16         object saveFileName = (object)strSaveFileName;
17         docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, Word.WdSaveFormat.wdFormatFilteredHTML });
18         docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, null);
19         wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
20     }
21     /// <summary>22     /// excel 轉換爲html
23   /// </summary>24   /// <param name="path">要轉換的文檔的路徑</param>25   /// <param name="savePath">轉換成的html的保存路徑</param>26   /// <param name="wordFileName">轉換後html文件的名字</param>27     public static void ExcelToHtml(string path, string savePath, string wordFileName)
28     {
29         string str = string.Empty;
30         Microsoft.Office.Interop.Excel.Application repExcel = new Microsoft.Office.Interop.Excel.Application();
31         Microsoft.Office.Interop.Excel.Workbook workbook = null;
32         Microsoft.Office.Interop.Excel.Worksheet worksheet = null;
33         workbook = repExcel.Application.Workbooks.Open(path, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
34         worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
35         object htmlFile = savePath + wordFileName + ".html";
36         object ofmt = Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;
37         workbook.SaveAs(htmlFile, ofmt, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
38         object osave = false;
39         workbook.Close(osave, Type.Missing, Type.Missing);
40         repExcel.Quit();
41     }
42     /// <summary>43   /// ppt轉換爲html
44   /// </summary>45   /// <param name="path">要轉換的文檔的路徑</param>46   /// <param name="savePath">轉換成的html的保存路徑</param>47   /// <param name="wordFileName">轉換後html文件的名字</param>48     public static void PPTToHtml(string path, string savePath, string wordFileName)
49     {
50         Microsoft.Office.Interop.PowerPoint.Application ppApp = new Microsoft.Office.Interop.PowerPoint.Application();
51         string strSourceFile = path;
52         string strDestinationFile = savePath + wordFileName + ".html";
53         Microsoft.Office.Interop.PowerPoint.Presentation prsPres = ppApp.Presentations.Open(strSourceFile, Microsoft.Office.Core.MsoTriState.msoTrue,          Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);
54         prsPres.SaveAs(strDestinationFile, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsHTML, MsoTriState.msoTrue);
55         prsPres.Close();
56         ppApp.Quit();
57     }
複製代碼

  c.接下來就是調用方法:WordToHtml(string path, string savePath, string wordFileName);ExcelToHtml(string path, string savePath, string wordFileName);PPTToHtml(string path, string savePath, string wordFileName)實現相應文檔的轉換

  然後就可以看見效果了

WORD

PPT

 

大家看一下這樣的效果確實感覺挺醜的,特別是word,excel格式都沒有了,這樣的效果是難以滿足要求的,那接下來我們就學習第二種方案。。。。

 

 

  (2).在網上搜索如何和將office文檔的pdf文檔轉換爲flash,實現在線預覽,你會發現有好幾種解決方案

    a.使用flashpaper將需要的文檔通過簡單的設置轉換爲SWF格式的Flash,擴展閱讀:http://baike.baidu.com/view/917746.htm,不過由於我的電腦室win7,而flashpaper又不支持win7,所以只好

    放棄此種方案。

    b.在網上發現可以使用swftools(http://www.swftools.org/謝天謝地啊,它支持win7)將pdf格式的文件轉換爲flash,但是不能講office文檔轉換爲flash,那怎麼辦呢,難道這種方法又不行,可是仔

    細想一下如果我們能將office文檔先轉換爲pdf文件不就解決問題了嗎,突然之間隱隱約約覺得使用office軟件就可實現這一功能,於是打開word看一下究竟

    哈哈果然有,不過要先裝一個插件                  

    一切準備工作結束以後我們就可以進行編碼了

    c.首先說一下swftools使用:在命令行中運行pdf2swf src.pdf des.swf一般能滿足需求。然後就行主要的代碼的編寫(即將office文檔轉換爲pdf文檔)

    編寫Office2Pdf.cs類

複製代碼
  1 using System;
2 using System.Data;
3 using System.Configuration;
4 using System.Web;
5 using System.Web.Security;
6 using System.Web.UI;
7 using System.Web.UI.WebControls;
8 using System.Web.UI.WebControls.WebParts;
9 using System.Web.UI.HtmlControls;
10 using Word = Microsoft.Office.Interop.Word;
11 using Excel = Microsoft.Office.Interop.Excel;
12 using PowerPoint = Microsoft.Office.Interop.PowerPoint;
13 using Microsoft.Office.Core;
14
15 /// <summary>
16 /// Office2Pdf 將Office文檔轉化爲pdf
17 /// </summary>
18 public class Office2Pdf
19 {
20 public Office2Pdf()
21 {
22 //
23 // TODO: 在此處添加構造函數邏輯
24 //
25 }
26 /// <summary>
27 /// Word轉換成pdf
28 /// </summary>
29 /// <param name="sourcePath">源文件路徑</param>
30 /// <param name="targetPath">目標文件路徑</param>
31 /// <returns>true=轉換成功</returns>
32 public bool DOCConvertToPDF(string sourcePath, string targetPath)
33 {
34 bool result = false;
35 Word.WdExportFormat exportFormat = Word.WdExportFormat.wdExportFormatPDF;
36 object paramMissing = Type.Missing;
37 Word.ApplicationClass wordApplication = new Word.ApplicationClass();
38 Word.Document wordDocument = null;
39 try
40 {
41 object paramSourceDocPath = sourcePath;
42 string paramExportFilePath = targetPath;
43 Word.WdExportFormat paramExportFormat = exportFormat;
44 bool paramOpenAfterExport = false;
45 Word.WdExportOptimizeFor paramExportOptimizeFor = Word.WdExportOptimizeFor.wdExportOptimizeForPrint;
46 Word.WdExportRange paramExportRange = Word.WdExportRange.wdExportAllDocument;
47 int paramStartPage = 0;
48 int paramEndPage = 0;
49 Word.WdExportItem paramExportItem = Word.WdExportItem.wdExportDocumentContent;
50 bool paramIncludeDocProps = true;
51 bool paramKeepIRM = true;
52 Word.WdExportCreateBookmarks paramCreateBookmarks = Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks;
53 bool paramDocStructureTags = true;
54 bool paramBitmapMissingFonts = true;
55 bool paramUseISO19005_1 = false;
56 wordDocument = wordApplication.Documents.Open(
57 ref paramSourceDocPath, ref paramMissing, ref paramMissing,
58 ref paramMissing, ref paramMissing, ref paramMissing,
59 ref paramMissing, ref paramMissing, ref paramMissing,
60 ref paramMissing, ref paramMissing, ref paramMissing,
61 ref paramMissing, ref paramMissing, ref paramMissing,
62 ref paramMissing);
63 if (wordDocument != null)
64 wordDocument.ExportAsFixedFormat(paramExportFilePath,
65 paramExportFormat, paramOpenAfterExport,
66 paramExportOptimizeFor, paramExportRange, paramStartPage,
67 paramEndPage, paramExportItem, paramIncludeDocProps,
68 paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
69 paramBitmapMissingFonts, paramUseISO19005_1,
70 ref paramMissing);
71 result = true;
72 }
73 catch
74 {
75 result = false;
76 }
77 finally
78 {
79 if (wordDocument != null)
80 {
81 wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
82 wordDocument = null;
83 }
84 if (wordApplication != null)
85 {
86 wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
87 wordApplication = null;
88 }
89 GC.Collect();
90 GC.WaitForPendingFinalizers();
91 GC.Collect();
92 GC.WaitForPendingFinalizers();
93 }
94 return result;
95 }
96
97 /// <summary>
98 /// 把Excel文件轉換成PDF格式文件
99 /// </summary>
100 /// <param name="sourcePath">源文件路徑</param>
101 /// <param name="targetPath">目標文件路徑</param>
102 /// <returns>true=轉換成功</returns>
103 public bool XLSConvertToPDF(string sourcePath, string targetPath)
104 {
105 bool result = false;
106 Excel.XlFixedFormatType targetType = Excel.XlFixedFormatType.xlTypePDF;
107 object missing = Type.Missing;
108 Excel.ApplicationClass application = null;
109 Excel.Workbook workBook = null;
110 try
111 {
112 application = new Excel.ApplicationClass();
113 object target = targetPath;
114 object type = targetType;
115 workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing,
116 missing, missing, missing, missing, missing, missing, missing, missing, missing);
117 workBook.ExportAsFixedFormat(targetType, target, Excel.XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing);
118 result = true;
119 }
120 catch
121 {
122 result = false;
123 }
124 finally
125 {
126 if (workBook != null)
127 {
128 workBook.Close(true, missing, missing);
129 workBook = null;
130 }
131 if (application != null)
132 {
133 application.Quit();
134 application = null;
135 }
136 GC.Collect();
137 GC.WaitForPendingFinalizers();
138 GC.Collect();
139 GC.WaitForPendingFinalizers();
140 }
141 return result;
142 }
143 ///<summary>
144 /// 把PowerPoint文件轉換成PDF格式文件
145 ///</summary>
146 ///<param name="sourcePath">源文件路徑</param>
147 ///<param name="targetPath">目標文件路徑</param>
148 ///<returns>true=轉換成功</returns>
149 public bool PPTConvertToPDF(string sourcePath, string targetPath)
150 {
151 bool result;
152 PowerPoint.PpSaveAsFileType targetFileType = PowerPoint.PpSaveAsFileType.ppSaveAsPDF;
153 object missing = Type.Missing;
154 PowerPoint.ApplicationClass application = null;
155 PowerPoint.Presentation persentation = null;
156 try
157 {
158 application = new PowerPoint.ApplicationClass();
159 persentation = application.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse); persentation.SaveAs(targetPath, targetFileType, Microsoft.Office.Core.MsoTriState.msoTrue);
160 result = true;
161 }
162 catch
163 {
164 result = false;
165 }
166 finally
167 {
168 if (persentation != null)
169 {
170 persentation.Close();
171 persentation = null;
172 }
173 if (application != null)
174 {
175 application.Quit();
176 application = null;
177 }
178 GC.Collect();
179 GC.WaitForPendingFinalizers();
180 GC.Collect();
181 GC.WaitForPendingFinalizers();
182 }
183 return result;
184 }
185 }
複製代碼

    然後編寫Pdf2Swf.cs類調用命令行將pdf轉換爲swf格式的flash

複製代碼
 1 using System;
 2 using System.Data;
 3 using System.Configuration;
 4 using System.Web;
 5 using System.Web.Security;
 6 using System.Web.UI;
 7 using System.Web.UI.WebControls;
 8 using System.Web.UI.WebControls.WebParts;
 9 using System.Web.UI.HtmlControls;
10 using System.Diagnostics;
11 using System.IO;
12 
13 /// <summary>14 /// Pdf2Swf 將pdf轉化爲swf
15 /// </summary>16 public class Pdf2Swf
17 {
18     public Pdf2Swf()
19     {
20         //21 // TODO: 在此處添加構造函數邏輯
22 //
23     }
24     public void PDFConvertToSWF(string sourcePath, string targetPath)
25     {
26         Process p = new Process();
27         p.StartInfo.FileName = "cmd.exe ";
28         p.StartInfo.UseShellExecute = false;
29         p.StartInfo.RedirectStandardInput = true;
30         p.StartInfo.RedirectStandardOutput = true;
31         p.StartInfo.RedirectStandardError = true;
32         p.StartInfo.CreateNoWindow = true;
33         p.Start();
34         string cmd = "pdf2swf.exe" + " " + sourcePath + " -o " + targetPath;
35         p.StandardInput.WriteLine(cmd);
36         p.Close();
37     }
38 }
複製代碼

 

  然後只需要調用這兩個類就可以實現將office轉換爲pdf再轉換爲flash的功能了

 (3)最後就是實現flash的顯示:這時我們還要藉助工具來實現功能,那就是flexpaper,首先在網上下載所需要的flash文件、javascript文件,然後編寫html代碼:

View Code
 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
2 <!-- saved from url=(0014)about:internet -->
3 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
4 <head>
5 <title>中勤文庫-Flash版</title>
6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
7 <style type="text/css" media="screen">
8 html, body { height:100%; }
9 body { margin:0; padding:0; overflow:auto; }
10 #flashContent { display:none; }
11 </style>
12
13 <script type="text/javascript" src="js/swfobject/swfobject.js"></script>
14 <script type="text/javascript" src="js/flexpaper_flash_debug.js"></script>
15 <script type="text/javascript" src="js/jquery.js"></script>
16 <script>
17 //獲得參數的方法
18 var request =
19 {
20 QueryString : function(val)
21 {
22 var uri = window.location.search;
23 var re = new RegExp("" +val+ "=([^&?]*)", "ig");
24 return ((uri.match(re))?(uri.match(re)[0].substr(val.length+1)):null);
25 }
26 }
27 </script>
28 <script type="text/javascript">
29 <!-- For version detection, set to min. required Flash Player version, or 0 (or 0.0.0), for no version detection. -->
30 var swfVersionStr = "10.0.0";
31 <!-- To use express install, set to playerProductInstall.swf, otherwise the empty string. -->
32 var xiSwfUrlStr = "playerProductInstall.swf";
33 var swfFile = emotion;//這填寫文檔轉換成的flash文件的路徑
34
35 var flashvars = {
36 SwfFile : escape(swfFile),
37 Scale : 0.6,
38 ZoomTransition : "easeOut",
39 ZoomTime : 0.5,
40 ZoomInterval : 0.2,
41 FitPageOnLoad : true,
42 FitWidthOnLoad : false,
43 PrintEnabled : true,
44 FullScreenAsMaxWindow : false,
45 ProgressiveLoading : true,
46
47 PrintToolsVisible : true,
48 ViewModeToolsVisible : true,
49 ZoomToolsVisible : true,
50 FullScreenVisible : true,
51 NavToolsVisible : true,
52 CursorToolsVisible : true,
53 SearchToolsVisible : true,
54
55 localeChain: "en_US"
56 };
57
58 var params = {
59
60 }
61 params.quality = "high";
62 params.bgcolor = "#ffffff";
63 params.allowscriptaccess = "sameDomain";
64 params.allowfullscreen = "true";
65 var attributes = {};
66 attributes.id = "FlexPaperViewer";
67 attributes.name = "FlexPaperViewer";
68 swfobject.embedSWF(
69 "FlexPaperViewer.swf", "flashContent",
70 "730", "580",
71 swfVersionStr, xiSwfUrlStr,
72 flashvars, params, attributes);
73 swfobject.createCSS("#flashContent", "display:block;text-align:left;");
74
75 </script>
76
77
78 </head>
79 <body>
80 <div align="center">
81 <div id="flashContent">
82 <p>
83 To view this page ensure that Adobe Flash Player version
84 10.0.0 or greater is installed.
85 </p>
86 <script type="text/javascript">
87 var pageHost = ((document.location.protocol == "https:") ? "https://" : "http://");
88 document.write("<a href='http://www.adobe.com/go/getflashplayer'><img src='"
89 + pageHost + "www.adobe.com/p_w_picpaths/shared/download_buttons/get_flash_player.gif' alt='Get Adobe Flash player' /></a>" );
90
91 </script>
92 </div>
93 </div>
94
95 </body>
96 </html>

效果就這樣:

還不錯吧,上面的工具欄也可以實現各種功能

至此爲止,所有工作全部結束,大家只需要將這些代碼進行整合,配合數據庫使用,編寫管理後臺,就可以實現百度文庫的效果,甚至可以投入實際使用。

歡迎大家閱讀留言,望批評指正,謝謝!!
 

源碼下載:http://files.cnblogs.com/expectszc/Web.zip

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章