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. 解决windows管理员已阻止你运行此应用问题

    按WIN+R键,打开“运行”,然后输入“gpedit.msc",就是打开组策略,这个在控制面板中也可以打开. 在组策略里找到“计算机配置”-“Windows设置”-“安全设置”-“本地策略” ...

  2. stm32L011F3——串口实例

    /* STM32L0xx HAL library initialization: - Configure the Flash prefetch, Flash preread and Buffer ca ...

  3. 在loadrunner中用头文件的形式对字符串进行MD5加密操作

    1.首先要有md5.h的头文件 2.然后在global.h中加入#include "md5.h" 3.在action中调用md5.h中的Change_to_Md5(const ch ...

  4. BRVAH(让RecyclerView变得更高效) (3)

    本文来自网易云社区 作者:吴思博 3 实现列表加载动画效果    3.1默认动画 我们只需将自建的 adapter 继承它对应满足需求的 Adapter,然后在 Activity 中实例化,通过ope ...

  5. 【LeetCode】Reorder Log Files(重新排列日志文件)

    这道题是LeetCode里的第937道题. 题目描述: 你有一个日志数组 logs.每条日志都是以空格分隔的字串. 对于每条日志,其第一个字为字母数字标识符.然后,要么: 标识符后面的每个字将仅由小写 ...

  6. NYOJ 469 擅长排列的小明 II

    擅长排列的小明 II 时间限制:1000 ms  |  内存限制:65535 KB 难度:3   描述 小明十分聪明,而且十分擅长排列计算. 有一天小明心血来潮想考考你,他给了你一个正整数n,序列1, ...

  7. oracle表空间,分区表,以及索引的总结

    表空间: Oracle的UNDOTBS01.DBF文件太大的解决办法 1..禁止undo tablespace自动增长 alter   database   datafile   'full_path ...

  8. 【JavaScript 8—基础知识点】:DOM

    一.总体概述 1.1,什么是DOM DOM(Document Object Model):D(文档):整个web加载的网页文档:O(对象):类似于window对象之类的东西,可以调用属性和方法,在这里 ...

  9. POJ-2318 TOYS,暴力+叉积判断!

                                                                 TOYS 2页的提交记录终于搞明白了. 题意:一个盒子由n块挡板分成n+1块区 ...

  10. 构建maven的web项目时注意的问题(出现Error configuring application listener of class org.springframework.web.context.ContextLoaderListener 或者前端控制器无法加载)

    构建项目后或者导入项目后,我们需要bulid path--->config build path 特别是maven的依赖一定要 发布到WEB_INF的lib下面,不然在发布项目的时候,这些依赖都 ...