在最近的一個項目中千網科技需要幫助客戶網站完成在線瀏覽word文件的功能,千網科技使用FlexPaper組件來現實這個效果,先介紹一下這個組件,FlexPaper是一個開源輕量級的在瀏覽器上顯示各種文檔的組件,被設計用來與PDF2SWF一起使用, 使在Flex中顯示PDF成為可能,而這個過程并無需PDF軟件環境的支持。它可以被當做Flex的庫來使用。
這個組件實際上是一個swf文件的閱讀器,所以要讓這個組件來顯示word文件,需要把word文件轉換成swf文件,而要將word轉swf,首先要轉換成pdf,然后再使用pdf2swf這個軟件將pdf轉換成swf,整個過程就是word轉pfd再轉swf。
下面貼出word文件轉pdf文件的c#代碼
private bool Func_word2pdf(string wordpath, string pdfpath)
{
MSWord.ApplicationClass wordApplicationClass = new MSWord.ApplicationClass();
MSWord.Document document = null;
wordApplicationClass.Visible = true;
object missing = System.Reflection.Missing.Value;
bool res = false;
try
{
object readOnly = false;
object filePathObject = wordpath;
document = wordApplicationClass.Documents.Open(ref filePathObject, ref missing,
ref readOnly, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing);
object savefilename = pdfpath;
object savefileformat = MSWord.WdSaveFormat.wdFormatPDF;
document.ExportAsFixedFormat(pdfpath, MSWord.WdExportFormat.wdExportFormatPDF);
res = true;
}
catch (Exception e)
{
Func_消息("生成PDF出現錯誤:" + e.Message);
}
finally
{
if (document != null)
{
document.Close(ref missing, ref missing, ref missing);
document = null;
}
if (wordApplicationClass != null)
{
wordApplicationClass.Quit(ref missing, ref missing, ref missing);
wordApplicationClass = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
return res;
}
千網科技用的word版本是2007,并且需要安裝SaveAsPDFandXPS插件,如果是使用2013版本,不需要安裝這個插件,但代碼稍有不同。
以上就完成了word轉pdf文件的功能,下面再貼出使用pdf2swf把pdf文件轉換成swf文件的c#代碼。
private bool PDF2SWF(string pdfPath, string swfPath, int beginpage, int endpage, int photoQuality)
{
try
{
string Pdf2Swfexe = @"D:\Program Files\SWFTools\pdf2swf.exe"; //pwf2swf 安裝目錄
StringBuilder sb = new StringBuilder();
sb.Append(" \"" + pdfPath + "\"");
sb.Append(" -o \"" + swfPath + "\"");
sb.Append(" -s flashversion=9");
int totalpage = GetPageCount(pdfPath);
if (endpage > totalpage || endpage == 0) endpage = totalpage;
sb.Append(" -p " + "\"" + beginpage + "" + "-" + endpage + "\"");
sb.Append(" -j " + photoQuality);
string Command = sb.ToString();
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = Pdf2Swfexe;
p.StartInfo.Arguments = Command;
p.StartInfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = false;
p.Start();
p.BeginErrorReadLine();
p.WaitForExit();
p.Close();
p.Dispose();
return true;
}
catch (Exception)
{
return false;
}
}
pdf2swf軟件可以到官網http://www.swftools.org下載,使用以上代碼就能將pdf文件轉換成swf文件,轉換效果好且速度好,千網科技推薦大家使用這個方法。同理也可以把ppt文件、excel文件等office轉換成swf文件,都是先轉pdf再轉swf,office文件轉pdf文件非常簡單,高版本的office文件都有直接轉pdf的功能,只需要用c#代碼調用一下就行。
這個word轉swf的c#教程就介紹到這里,有什么不懂可以聯系我們咨詢。