Office2007需要借助SaveAsPDFandXPS的插件完成,Office2010可以直接兼容。

Office2PDF主要采用的是 Microsoft.Office.Interop的方式进行,PDF2SWF主要采用的是SWFTools的pdf2swf工具。至于SWFTools的各种命令,网上有很多的资料可以参考,这里就不一一举例了。

 /// <summary>
/// 把Word文件转换成为PDF格式文件
/// </summary>
/// <param name="sourcePath">源文件路径</param>
/// <param name="targetPath">目标文件路径</param>
/// <returns>true=转换成功</returns>
public static bool WordToPDF(string sourcePath, string targetPath)
{
bool result = false;
Word.WdExportFormat exportFormat = Word.WdExportFormat.wdExportFormatPDF;
object paramMissing = Type.Missing;
Word.Application wordApplication = new Word.Application();
Word.Document wordDocument = null;
try
{
object paramSourceDocPath = sourcePath;
string paramExportFilePath = targetPath;
Word.WdExportFormat paramExportFormat = exportFormat;
bool paramOpenAfterExport = false;
Word.WdExportOptimizeFor paramExportOptimizeFor = Microsoft.Office.Interop.Word.WdExportOptimizeFor.wdExportOptimizeForPrint;
Word.WdExportRange paramExportRange = Word.WdExportRange.wdExportAllDocument;
int paramStartPage = ;
int paramEndPage = ;
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;
//bool result = false;
//Microsoft.Office.Interop.Word.WdExportFormat exportFormat = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF;
//Microsoft.Office.Interop.Word.Application application = null; //Microsoft.Office.Interop.Word.Document document = null;
//try
//{
// application = new Microsoft.Office.Interop.Word.Application();
// application.Visible = false;
// document = application.Documents.Open(sourcePath);
// document.SaveAs();
// document.ExportAsFixedFormat(targetPath, exportFormat);
// result = true;
//}
//catch (Exception e)
//{ // result = false;
// throw e;
//}
//finally
//{
// if (document != null)
// {
// document.Close();
// document = null;
// }
// if (application != null)
// {
// application.Quit();
// application = null;
// }
// GC.Collect();
// GC.WaitForPendingFinalizers();
// GC.Collect();
// GC.WaitForPendingFinalizers();
//}
//return result;
}
ExcelToPDF

   /// <summary>
/// 把Microsoft.Office.Interop.Excel文件转换成PDF格式文件
/// </summary>
/// <param name="sourcePath">源文件路径</param>
/// <param name="targetPath">目标文件路径</param>
/// <returns>true=转换成功</returns>
public static bool ExcelToPDF(string sourcePath, string targetPath)
{
bool result = false;
Excel.XlFixedFormatType targetType = Excel.XlFixedFormatType.xlTypePDF;
object missing = Type.Missing;
Excel.Application application = null;
Excel.Workbook workBook = null;
try
{
application = new Excel.Application();
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;
//bool result = false;
//Microsoft.Office.Interop.Excel.XlFixedFormatType targetType = Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF;
//object missing = Type.Missing;
//Microsoft.Office.Interop.Excel.Application application = null;
//Microsoft.Office.Interop.Excel.Workbook workBook = null;
//try
//{
// application = new Microsoft.Office.Interop.Excel.Application();
// application.Visible = false;
// workBook = application.Workbooks.Open(sourcePath);
// workBook.SaveAs();
// workBook.ExportAsFixedFormat(targetType, targetPath);
// result = true;
//}
//catch (Exception e)
//{ // result = false;
// throw e;
//}
//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;
}
PowerPointToPDF

 /// <summary>
/// 把PowerPoint文件转换成PDF格式文件
/// </summary>
/// <param name="sourcePath">源文件路径</param>
/// <param name="targetPath">目标文件路径</param>
/// <returns>true=转换成功</returns>
public static bool PowerPointToPDF(string sourcePath, string targetPath)
{
bool result;
PowerPoint.PpSaveAsFileType targetFileType = PowerPoint.PpSaveAsFileType.ppSaveAsPDF; object missing = Type.Missing;
PowerPoint.Application application = null;
PowerPoint.Presentation persentation = null;
try
{
application = new PowerPoint.Application();
persentation = application.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
persentation.SaveAs(targetPath, targetFileType, Microsoft.Office.Core.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; //bool result;
//Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType targetFileType = Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPDF;
//object missing = Type.Missing;
//Microsoft.Office.Interop.PowerPoint.Application application = null;
//Microsoft.Office.Interop.PowerPoint.Presentation persentation = null;
//try
//{
// application = new Microsoft.Office.Interop.PowerPoint.Application();
// //application.Visible = MsoTriState.msoFalse;
// persentation = application.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
// persentation.SaveAs(targetPath, targetFileType, Microsoft.Office.Core.MsoTriState.msoTrue); // result = true;
//}
//catch (Exception e)
//{
// result = false;
// throw e;
//}
//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;
}
VisioToPDF

         /// <summary>
/// 把Visio文件转换成PDF格式文件
/// </summary>
/// <param name="sourcePath">源文件路径</param>
/// <param name="targetPath">目标文件路径</param>
/// <returns>true=转换成功</returns>
public static bool VisioToPDF(string sourcePath, string targetPath)
{
bool result; Microsoft.Office.Interop.Visio.VisFixedFormatTypes targetType = Microsoft.Office.Interop.Visio.VisFixedFormatTypes.visFixedFormatPDF;
object missing = Type.Missing;
Microsoft.Office.Interop.Visio.Application application = null;
Microsoft.Office.Interop.Visio.Document document = null;
try
{
application = new Microsoft.Office.Interop.Visio.Application();
application.Visible = false;
document = application.Documents.Open(sourcePath);
document.Save();
document.ExportAsFixedFormat(targetType, targetPath, Microsoft.Office.Interop.Visio.VisDocExIntent.visDocExIntentScreen, Microsoft.Office.Interop.Visio.VisPrintOutRange.visPrintAll);
result = true;
}
catch (Exception e)
{
result = false; throw e;
}
finally
{
if (application != null)
{
application.Quit();
application = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
return result;
}

因为这里的代码只支持Office2007以及以上版本,所以需要检测目标机器的Office版本,这里我的方法是查询注册表信息,对于绿色安装的Office楼主没有想到好的办法。

GetOfficePath

 /// <summary>
/// 获取当前某个版本Office的安装路径
/// </summary>
/// <param name="Path">返回当前系统Office安装路径</param>
/// <param name="Version">返回当前系统Office版本信息</param>
public static void GetOfficePath(out string Path, out string Version)
{
string strPathResult = "";
string strVersionResult = "";
string strKeyName = "Path";
object objResult = null;
Microsoft.Win32.RegistryValueKind regValueKind;
Microsoft.Win32.RegistryKey regKey = null;
Microsoft.Win32.RegistryKey regSubKey = null; try
{
regKey = Microsoft.Win32.Registry.LocalMachine;
if (regSubKey == null)
{//office2010
regSubKey = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Office\14.0\Common\InstallRoot", false);
strVersionResult = "office2010";
strKeyName = "Path";
try
{ objResult = regSubKey.GetValue(strKeyName); regValueKind = regSubKey.GetValueKind(strKeyName); } catch (Exception ex)
{ regSubKey = null; } }
if (regSubKey == null)
{//office2007
regSubKey = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Office\12.0\Common\InstallRoot", false);
strVersionResult = "office2007";
strKeyName = "Path";
try
{ objResult = regSubKey.GetValue(strKeyName); regValueKind = regSubKey.GetValueKind(strKeyName); } catch (Exception ex)
{ regSubKey = null; }
} if (regSubKey == null)
{//Office2003
regSubKey = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Office\11.0\Common\InstallRoot", false);
strVersionResult = "office2003";
strKeyName = "Path";
try
{ objResult = regSubKey.GetValue(strKeyName); regValueKind = regSubKey.GetValueKind(strKeyName); } catch (Exception ex)
{ regSubKey = null; }
}
if (regSubKey == null)
{//officeXp
regSubKey = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Office\10.0\Common\InstallRoot", false);
strVersionResult = "officeXP";
strKeyName = "Path";
try
{ objResult = regSubKey.GetValue(strKeyName); regValueKind = regSubKey.GetValueKind(strKeyName); } catch (Exception ex)
{ regSubKey = null; }
}
if (regSubKey == null)
{//Office2000
regSubKey = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Office\9.0\Common\InstallRoot", false);
strVersionResult = "office2000";
strKeyName = "Path";
try
{ objResult = regSubKey.GetValue(strKeyName); regValueKind = regSubKey.GetValueKind(strKeyName); } catch (Exception ex)
{ regSubKey = null; }
}
if (regSubKey == null)
{//office97
regSubKey = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Office\8.0\Common\InstallRoot", false);
strVersionResult = "office97";
strKeyName = "OfficeBin";
try
{ objResult = regSubKey.GetValue(strKeyName); regValueKind = regSubKey.GetValueKind(strKeyName); } catch (Exception ex)
{ regSubKey = null; }
} objResult = regSubKey.GetValue(strKeyName);
regValueKind = regSubKey.GetValueKind(strKeyName);
if (regValueKind == Microsoft.Win32.RegistryValueKind.String)
{
strPathResult = objResult.ToString();
}
}
catch (System.Security.SecurityException ex)
{
throw new System.Security.SecurityException("您没有读取注册表的权限", ex);
}
catch (Exception ex)
{
throw new Exception("读取注册表出错!", ex);
}
finally
{ if (regKey != null)
{
regKey.Close();
regKey = null;
} if (regSubKey != null)
{
regSubKey.Close();
regSubKey = null;
}
} Path = strPathResult;
Version = strVersionResult;
}

当文档转成PDF后,就成功一半啦,接下来就只剩下转换成SWF了。

转换的命令其实很简单的,但是楼主在实际操作的时候出现了问题,在转换的时候我们一般使用的是Process在进行命令行的执行,但是此类提供的标准output流只有2k,对于页数很多的PDF转换SWF的时候,会出现SWF无法生成的问题,借助网上很多同仁的资料,改良后的方面对于处理五六十页以内的PDF转SWF的问题不大,具体代码如下:

              //pdf转swf
string pdf2swfExe = @"SWFTools\pdf2swf.exe"; string args = " -t \"" + szPDF + "\" -o \"" + szSWF
+ "\" -s drawonlyshapes -s flashversion=9 -s poly2bitmap";
using (Process p = new Process())
{ string cmd = pdf2swfExe; p.StartInfo.FileName = cmd;
p.StartInfo.Arguments = args;
p.StartInfo.UseShellExecute = false; ////此类提供的标准output流只有2k,不要重定向
p.StartInfo.RedirectStandardOutput = true; p.StartInfo.CreateNoWindow = true;
p.Start(); p.PriorityClass = ProcessPriorityClass.High;
p.BeginOutputReadLine();
p.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived); }

主要采用的方式是自行读取OUTPUT中的数据流,

process_OutputDataReceived

 private void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{ // 这里仅做输出的示例,实际上您可以根据情况取消获取命令行的内容 // 参考:process.CancelOutputRead() (sender as Process).Close(); if (String.IsNullOrEmpty(e.Data) == false)
{ string szPDF = Fileinfo.FileNewName.Split('.')[] + ".pdf";
string szSWF = Fileinfo.FileNewName.Split('.')[] + ".swf";
if (File.Exists(szSWF))
{
try
{ ThreadDelegate changeProcessDel = delegate() //后台中要更改主线程中的UI,于是我们还是用委托来实现,再创建一个实例
{
DataGridTemplateColumn templeColumn = Datagrid.Columns[Datagrid.Columns.Count - ] as DataGridTemplateColumn;
FrameworkElement element = templeColumn.GetCellContent(Datagrid.Items[Index]);
GifImage img = (GifImage)templeColumn.CellTemplate.FindName("gifimage", element);
img.Visibility = System.Windows.Visibility.Hidden;
Label Successed = (Label)templeColumn.CellTemplate.FindName("Successed", element);
Successed.Visibility = System.Windows.Visibility.Visible;
Successed.Content = "文件转换成功!";
};//要调用的过程
Dispatcher.BeginInvoke(DispatcherPriority.Send, changeProcessDel); //使用分发器让这个委托等待执行
Thread.Sleep(); //删除原文件
if (File.Exists(Fileinfo.FileNewName))
{
File.Delete(Fileinfo.FileNewName);
}
//删除pdf
//if (File.Exists(szPDF))
//{
// File.Delete(szPDF);
//}
}
catch (Exception ex)
{
throw ex;
}
}
else
{
//ThreadDelegate changeProcessDel = delegate() //后台中要更改主线程中的UI,于是我们还是用委托来实现,再创建一个实例
//{
// DataGridTemplateColumn templeColumn = Datagrid.Columns[Datagrid.Columns.Count - 1] as DataGridTemplateColumn;
// FrameworkElement element = templeColumn.GetCellContent(Datagrid.Items[Index]);
// GifImage img = (GifImage)templeColumn.CellTemplate.FindName("gifimage", element);
// img.Visibility = System.Windows.Visibility.Hidden;
// Label Successed = (Label)templeColumn.CellTemplate.FindName("Successed", element);
// Successed.Visibility = System.Windows.Visibility.Visible;
// Successed.Content = "文件转换出错!";
//};//要调用的过程
//Dispatcher.BeginInvoke(DispatcherPriority.Send, changeProcessDel); //使用分发器让这个委托等待执行
//Thread.Sleep(3000); }
} }

本程序的框架是WPF搭建的。

关于PDF转SWF就说这么多了,当然楼主所有的代码中不乏是网上同仁的心血,楼主在这里只是对某些代码进行整改和总结,并非侵权。

Office转SWF的一些感想(Office2007和Office2010)的更多相关文章

  1. 完美解决Office2003、Office2007、Office2010、Office2013共存方法

    原文:http://www.360doc.com/content/14/0903/16/7555793_406799011.shtml 微软Office深受广大用户的青睐,特别是经典的Office 2 ...

  2. office2007安装时显示安装程序找不到 office.zh-cn\officeLR.cab怎么办

    根本原因是和VS2008有关解决方法如下:1. 找到vs2008安装程序(光盘,镜像文件,解压文件都一样),找到WCU文件夹在他里面找到WebDesignerCore文件夹,然后打开它找到WebDes ...

  3. 在线浏览office 文件

    http://blog.csdn.net/binyao02123202/article/details/20051683 [Asp.net]常见word,excel,ppt,pdf在线预览方案,有图有 ...

  4. excel,word,ppt,pdf,swf 文件互相转换

    转自:  http://www.cnblogs.com/wolf-sun/p/3569960.html 引言 之前项目需要,查找了office文档在线预览的解决方案,顺便记录一下,方便以后查询. 方案 ...

  5. 很不错的在线Office控件:IWebOffice与SOAOffice

    http://blog.csdn.net/cjh200102/article/details/17220441 iWebOffice2003文档控件 iWebOffice2003网络文档中间件能够在I ...

  6. (转)无法将类型为“Microsoft.Office.Interop.Word.ApplicationClass”的 COM 对象强制转换为接口类型“Microsoft.Office.Interop.Word._Application”。此操作失败的原因是对 IID 为“{00020970-

    HRESULT:0x80030002 无法将类型为“Microsoft.Office.Interop.Word.ApplicationClass”的 COM 对象强制转换为接口类型“Microsoft ...

  7. Atitit.office word  excel  ppt pdf 的web在线预览方案与html转换方案 attilax 总结

    Atitit.office word  excel  ppt pdf 的web在线预览方案与html转换方案 attilax 总结 1. office word  excel pdf 的web预览要求 ...

  8. 注册表检测office版本

    #region 查询注册表,判断本机是否安装Office2003,2007和WPS public int ExistsRegedit() { int ifused = 0; RegistryKey r ...

  9. 4步解决“Microsoft Office Professional Plus 2013在安装过程中出错”

    公司新搭建了AD域,公司内使用了1年多的电脑,现在要加入域,加域过程问题错综复杂. 其中一台电脑上,反应说Excel经常卡住,严重影响使用,所以考虑重装office2013.在控制面板卸载了: 卸载完 ...

随机推荐

  1. python爬虫入门三:requests库

    urllib库在很多时候都比较繁琐,比如处理Cookies.因此,我们选择学习另一个更为简单易用的HTTP库:Requests. requests官方文档 1. 什么是Requests Request ...

  2. BFS:UVa220 ACM/ICPC 1992-Othello(黑白棋)

    Othello Othello is a game played by two people on an 8 x 8 board, using disks that are white on one ...

  3. 利用Vert.x构建简单的API 服务、分布式服务

    目前已经使用Vertx已经一年多了,虽然没有太多的造诣,但也已在项目中推广了下:从最初的vertx搭建web服务,到项目上线运营,还算比较稳定.再到后来尝试搭建基于vertx的分布式服务,一路下来也积 ...

  4. OSPF 一 基础

    本节介绍ospf路由选择协议    为链路状态  路由选择协议 一  分类 open shortest path first   开放最短路优先   公有协议 单区域的ospf实施  运行在一个自治系 ...

  5. [uiautomator篇] 获取当前页面的方法

    Uiautomator 在2.0之前的版本里就提供了getCurrentActivity()的方法,但返回内容不正确:2.0 版本今天尝试了下,还是返回有问题的: 有点没描述清楚啊,是在uiautom ...

  6. TOJ 2541: Paper Cutting

    2541: Paper Cutting  Time Limit(Common/Java):1000MS/10000MS     Memory Limit:65536KByteTotal Submit: ...

  7. 机器学习实战之kNN算法

    机器学习实战这本书是基于python的,如果我们想要完成python开发,那么python的开发环境必不可少: (1)python3.52,64位,这是我用的python版本 (2)numpy 1.1 ...

  8. JAVA如何解压缩ZIP文档

    代码片段: package org.yu.units; import java.io.Closeable; import java.io.File; import java.io.FileInputS ...

  9. iOS学习笔记13-网络(二)NSURLSession

    在2013年WWDC上苹果揭开了NSURLSession的面纱,将它作为NSURLConnection的继任者.现在使用最广泛的第三方网络框架:AFNetworking.SDWebImage等等都使用 ...

  10. SHoj A序列

    A序列 发布时间: 2017年7月9日 18:17   最后更新: 2017年7月9日 21:05   时间限制: 1000ms   内存限制: 128M 描述 如果一个序列有奇数个正整数组成,不妨令 ...