1、Office系列—将Office文件(Word、PPT、Excel)转换为PDF文件

将Office文件作为文章并在网页上预览,主要为(Word、PPT、Excel)3种类型文件。

将Office转换为PDF在网页中预览:

1.1 基于Office实现的解决方案

实现方式:在本地服务器上安装Microsoft Office,通过C#代码调用服务器上的COM接口,将Office文件转换为PDF(类似于用Office软件打开Word文档,然后另存为PDF文件)。

不要直接调Office的COM组件,用NetOffice间接调:https://netoffice.io

通过Nuget包管理器安装需要的包(这些包只能在.Net FrameWork版本项目中使用)

  1. Microsoft.Office.Interop.Word
  2. Microsoft.Office.Interop.PowerPoint
  3. Microsoft.Office.Interop.Excel
  1. public class OfficeHelper
  2. {
  3. static Word.Application wordApplication = new Word.Application();
  4. static Excel.Application excelApplication = new Excel.Application();
  5. static PowerPoint.Application pptApplication = new PowerPoint.Application();
  6. /// <summary>
  7. /// 将Word文档转换成PDF格式
  8. /// </summary>
  9. /// <param name="sourcePath">源文件路径</param>
  10. /// <param name="targetPath">目标文件路径</param>
  11. /// <returns></returns>
  12. public static bool WordConvertPDF(string sourcePath, string targetPath)
  13. {
  14. bool result;
  15. Word.Document wordDocument = null;
  16. try
  17. {
  18. wordDocument = wordApplication.Documents.Open(ref sourcePath);
  19. if (wordDocument != null)
  20. {
  21. wordDocument.SaveAs2(targetPath, WdExportFormat.wdExportFormatPDF);
  22. //wordDocument.ExportAsFixedFormat(targetPath, WdExportFormat.wdExportFormatPDF);
  23. result = true;
  24. }
  25. }
  26. catch (Exception ex)
  27. {
  28. result = false;
  29. LogHelper.Log($"文件:{sourcePath} 生成失败,原因:{ex.Message}", ex.StackTrace);
  30. }
  31. finally
  32. {
  33. if (wordDocument != null)
  34. {
  35. wordDocument.Close();
  36. wordDocument = null;
  37. }
  38. }
  39. return result;
  40. }
  41. /// <summary>
  42. /// 将Excel文档转换成PDF格式
  43. /// </summary>
  44. /// <param name="sourcePath">源文件路径</param>
  45. /// <param name="targetPath">目标文件路径</param>
  46. /// <returns></returns>
  47. public static bool ExcelConvertPDF(string sourcePath, string targetPath)
  48. {
  49. bool result;
  50. Workbook workBook = null;
  51. try
  52. {
  53. workBook = excelApplication.Workbooks.Open(sourcePath);
  54. if (workBook != null)
  55. {
  56. workBook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, targetPath);
  57. result = true;
  58. }
  59. }
  60. catch (Exception ex)
  61. {
  62. result = false;
  63. LogHelper.Log($"文件:{sourcePath} 生成失败,原因:{ex.Message}", ex.StackTrace);
  64. }
  65. finally
  66. {
  67. if (workBook != null)
  68. {
  69. workBook.Close();
  70. workBook = null;
  71. }
  72. }
  73. return result;
  74. }
  75. /// <summary>
  76. /// 将PPT文档转换成pdf格式
  77. /// </summary>
  78. /// <param name="sourcePath">源文件路径</param>
  79. /// <param name="targetPath">目标文件路径</param>
  80. /// <returns></returns>
  81. public static bool PPTConvertPDF(string sourcePath, string targetPath)
  82. {
  83. bool result;
  84. object missing = Type.Missing;
  85. Presentation persentation = null;
  86. try
  87. {
  88. persentation = pptApplication.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
  89. if (persentation != null)
  90. {
  91. persentation.SaveAs(targetPath, PpSaveAsFileType.ppSaveAsPDF, Microsoft.Office.Core.MsoTriState.msoTrue);
  92. //persentation.ExportAsFixedFormat(targetPath, PpFixedFormatType.ppFixedFormatTypePDF);
  93. result = true;
  94. }
  95. }
  96. catch (Exception ex)
  97. {
  98. result = false;
  99. LogHelper.Log($"文件:{sourcePath} 生成失败,原因:{ex.Message}", ex.StackTrace);
  100. }
  101. finally
  102. {
  103. if (persentation != null)
  104. {
  105. persentation.Close();
  106. persentation = null;
  107. }
  108. }
  109. return result;
  110. }
  111. }

Office COM API提供SaveAs和ExportAsFixedFormat两个方法来生成文档,需要注意调用时参数不同,大部分使用默认值就可以了(接口文档地址)。

上面代码中将wordApplication作为一个静态变量提出来,每次在加载文件时,再通过它打开(相当于一直开着Office.Word程序)。

直接调Office的COM组件有版本兼容的问题,可以采用NetOffice间接调用。

通过Nuget安装NetOffice,不同的Office文件需要引用不同的Apidll。

  1. using NetOffice;
  2. using NetOffice.PowerPointApi;
  1. public static void PPTConvertPDF(string sourcePath, string targetPath)
  2. {
  3. using (Application _pptApp = new Application())
  4. {
  5. var pres = _pptApp.Presentations.Open(sourcePath, NetOffice.OfficeApi.Enums.MsoTriState.msoCTrue, NetOffice.OfficeApi.Enums.MsoTriState.msoFalse, NetOffice.OfficeApi.Enums.MsoTriState.msoFalse);
  6. pres.SaveAs(targetPath, NetOffice.PowerPointApi.Enums.PpSaveAsFileType.ppSaveAsPDF);
  7. pres.Close();
  8. }
  9. }

1.2 基于WPS实现的解决方案

和基于Office的解决方案一样,通过代码调用COM接口,实现文件的转换。当然需要提前在服务器上安装WPS软件。

在本地的WPS安装目录中,找到以下几个dll文件,并将其引用到项目中,

  1. wpsapi.dll
  2. wpsapiex.dll
  1. public static void WordConvertPDF(string sourcePath, string targetPath)
  2. {
  3. var app = new Word.Application();
  4. var doc = app.Documents.Open(sourcePath,Visible: MsoTriState.msoFalse);
  5. doc.SaveAs2(targetPath, Word.WdExportFormat.wdExportFormatPDF);
  6. doc.Close();
  7. app.Close();
  8. }

其中Word是wpsapi.dll添加到程序中后,程序集命名空间名称。

2、提取Office文件(Word、PPT)中的所有图片

2.1 基于OpenXml的解决方案

Office Open XML 是由Microsoft开发的一种以XML为基础并以ZIP格式压缩的电子文件规范,支持文件、表格、备忘录、幻灯片等文件格式。

简单来说一个PPT文件(.pptx后缀),其实是一个ZIP格式压缩的电子文件,压缩文件内通过XML标记了文档的内容,比如,引用的图片、文字的排列方式等等。

常用的几种Office文件中的,Word文件有.doc和.docx两种后缀,PowerPoint文件有.ppt和.pptx两种后缀,Excel文件有.xls和.xlsx两种后缀。这其实就是文件版本的差异。 OpenXml也只能用在2007及以后的文件版本中(后缀为.docx、.pptx、.xlsx)。

测试:准备同一PPT文件分别另存为.ppt和.pptx两个版本,直接修改文件后缀为.zip。



通过Nuget包管理安装需要用到的包

  1. DocumentFormat.OpenXml
  1. using DocumentFormat.OpenXml.Packaging;
  2. /// <summary>
  3. /// 导出PPT文件中所有图片
  4. /// </summary>
  5. /// <param name="sourcePath">源文件路径</param>
  6. /// <param name="targetDir">目标文件存放目录</param>
  7. /// <returns></returns>
  8. public static void ExportPPTImages(string sourcePath,string targetDir)
  9. {
  10. using (PresentationDocument presentationDocument = PresentationDocument.Open(sourcePath, isEditable: false))
  11. {
  12. PresentationPart presentationPart = presentationDocument.PresentationPart;
  13. DocumentFormat.OpenXml.Presentation.Presentation presentation = presentationPart.Presentation;
  14. List<ImagePart> list = new List<ImagePart>();
  15. foreach (DocumentFormat.OpenXml.Presentation.SlideId item in presentation.SlideIdList.OfType<DocumentFormat.OpenXml.Presentation.SlideId>())
  16. {
  17. SlidePart slidePart = presentationPart.GetPartById(item.RelationshipId) as SlidePart;
  18. list.AddRange(slidePart.ImageParts);
  19. }
  20. List<IGrouping<string, ImagePart>> list2 = list.GroupBy(d => d.Uri.OriginalString).ToList();
  21. //导出PPT所有的图片
  22. for (int i = 0; i < list2.Count; i++)
  23. {
  24. ImagePart imagePart = list2[i].FirstOrDefault();
  25. string tempFileName = Path.Combine(targetDir, $"image_{i}.jpg");
  26. using (Stream stream = imagePart.GetStream(FileMode.Open))
  27. {
  28. using (Bitmap bitmap = new Bitmap(stream))
  29. {
  30. bitmap.Save(tempFileName, System.Drawing.Imaging.ImageFormat.Jpeg);
  31. }
  32. }
  33. }
  34. //presentation.Save();
  35. }
  36. }
  37. /// <summary>
  38. /// 导出Word文件中所有图片
  39. /// </summary>
  40. /// <param name="sourcePath">源文件路径</param>
  41. /// <param name="targetDir">目标文件存放目录</param>
  42. /// <returns></returns>
  43. public static void ExportWordImages(string sourcePath,string targetDir)
  44. {
  45. using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(sourcePath, isEditable: false))
  46. {
  47. var list2 = wordDocument.MainDocumentPart.ImageParts.GroupBy(d => d.Uri.OriginalString).ToList();
  48. for (int i = 0; i < list2.Count; i++)
  49. {
  50. ImagePart imagePart = list2[i].FirstOrDefault();
  51. string tempFileName = Path.Combine(targetDir, $"image_{i}.jpg");
  52. using (Stream stream = imagePart.GetStream(FileMode.Open))
  53. {
  54. using (Bitmap bitmap = new Bitmap(stream))
  55. {
  56. bitmap.Save(tempFileName, System.Drawing.Imaging.ImageFormat.Jpeg);
  57. }
  58. }
  59. }
  60. }
  61. }

2.2 基于第三方插件的解决方案

Spire,用Spire正式版插件导出来的图片没有水印。

  1. using Spire.Presentation;
  2. /// <summary>
  3. /// 导出PPT文件中所有图片
  4. /// </summary>
  5. /// <param name="sourcePath">源文件路径</param>
  6. /// <param name="targetDir">目标文件存放目录</param>
  7. /// <returns></returns>
  8. public static void ExportPPTImages2(string sourcePath, string targetDir)
  9. {
  10. using (Presentation pres = new Presentation())
  11. {
  12. pres.LoadFromFile(sourcePath);
  13. for (int i = 0; i < pres.Images.Count; i++)
  14. {
  15. Image image = pres.Images[i].Image;
  16. string tempFileName = Path.Combine(targetDir, $"image_{i}.jpg");
  17. image.Save(tempFileName);
  18. }
  19. }
  20. }

Office系列---将Office文件(Word、PPT、Excel)转换为PDF文件,提取Office文件(Word、PPT)中的所有图片的更多相关文章

  1. Office系列(1)---将Office文件(Word、PPT、Excel)转换为PDF文件

    需求: 将Office文件作为文章并在网页上预览,主要为(Word.PPT.Excel)3种类型文件. 研究了一下,找到了两种解决方案 直接调用微软的在线预览功能实现(预览前提:预览资源必须可以直接通 ...

  2. java操作office和pdf文件java读取word,excel和pdf文档内容

    在平常应用程序中,对office和pdf文档进行读取数据是比较常见的功能,尤其在很多web应用程序中.所以今天我们就简单来看一下Java对word.excel.pdf文件的读取.本篇博客只是讲解简单应 ...

  3. C# 基于NPOI+Office COM组件 实现20行代码在线预览文档(word,excel,pdf,txt,png)

    由于项目需要,需要一个在线预览office的功能,小编一开始使用的是微软提供的方法,简单快捷,但是不符合小编开发需求, 就另外用了:将文件转换成html文件然后预览html文件的方法.对微软提供的方法 ...

  4. Asp.net实现直接在浏览器预览Word、Excel、PDF、Txt文件(附源码)

    功能说明 输入文件路径,在浏览器输出文件预览信息,经测试极速(Chrome).IE9.Firefox通过 分类文件及代码说明  DemoFiles 存放可测试文件 Default.aspx  启动页 ...

  5. C#在线预览文档(word,excel,pdf,txt,png)

    C#在线预览文档(word,excel,pdf,txt,png) 1.预览方式:将word文件转换成html文件然后预览html文件2.预览word文件:需要引入Interop.Microsoft.O ...

  6. java操作word,excel,pdf

    在平常应用程序中,对office和pdf文档进行读取数据是比较常见的功能,尤其在很多web应用程序中.所以今天我们就简单来看一下java对word.excel.pdf文件的读取.本篇博客只是讲解简单应 ...

  7. 自制 Word、Excel 批转 PDF 工具

    原文:自制 Word.Excel 批转 PDF 工具 目前做金融业的项目,该公司每天会产生很多 Word.Excel 文档,需要大量地转换为 PDF,除了自己保存外,也要给金融主管机构作为备份.由于文 ...

  8. java 实现Word或Excel 转Pdf

    1:首先需要引入相关的jar word转pdf需要引入 aspose-words-15.8.0-jdk16.jar 下载JAR包 Word http://note.youdao.com/notesha ...

  9. Java实现windows,linux服务器word,excel转为PDF;aspose-words,Documents4j

    Java实现windows,linux服务器word,excel转为PDF:aspose-words,Documents4j 一.通过aspose-words将word,Excel文档转为PDF 1. ...

随机推荐

  1. maven打包,跳过生成javadoc

    有时候由于代码中注释错误(比如方法参数)或者maven javadoc插件版本有问题,导致打包报错,而我们着急打包验证问题,没有时间一一修改错误,这时候可以先跳过生成javadoc,继续下一步工作. ...

  2. java时间的一些处理

    获取当前时间 System.currentTimeMillis() //第一种 Date date = new Date(); System.out.println(date.getTime()); ...

  3. logback运行时动态创建日志文件

    package com.example.demo.config; import ch.qos.logback.classic.Level; import ch.qos.logback.classic. ...

  4. Inno Step软件安装包制作教程

    Inno setup制作软件安装包教程 1,Inno Setup介绍 Inno Setup 是一个免费的安装制作软件,小巧.简便.精美是其最大特点,支持pascal脚本,能快速制作出标准Windows ...

  5. Alpha冲刺--总结随笔

    一.项目预期计划 时间 (天) 前端预期计划 完成情况 后端预期计划 完成情况 1-2 前端开始基本页面的设计 完成 整合项目依赖,搭建基本框架,建立数据库 完成 3-5 前端基础页面的实现与完善 完 ...

  6. hive中一般取top n时,row_number(),rank,dense_ran()常用三个函数

    一. 分区函数Partition By与row_number().rank().dense_rank()的用法(获取分组(分区)中前几条记录) 一.数据准备 --1.创建学生成绩表 id int,   ...

  7. PHP将数据集转换成树状结构

    /** * 把返回的数据集转换成Tree * @param array $list 要转换的数据集 * @param string $pid parent标记字段 * @param string $l ...

  8. 串的模式匹配算法1 BF算法

    BF算法 字符串的模式匹配不一定要从主串的第一个位置开始,可以指定主串中查找的起始位置 pos. 2. 算法步骤: 1)分别利用计数器指针 i 和 j 指定主串和模式串即小字符串待比较的位置,初始化为 ...

  9. MyISAM与InnoDB两者之间区别与选择(转)

    Mysql在V5.1之前默认存储引擎是MyISAM:在此之后默认存储引擎是InnoDB MyISAM:默认表类型,它是基于传统的ISAM类型,ISAM是Indexed Sequential Acces ...

  10. 【Linux】nohup和&的区别

    同样都是后台执行进程,但是nohup和&有什么区别呢? & 是指后台运行: nohup 的功能和& 之间的功能并不相同. 其中,nohup 可以使得命令永远运行下去和用户终端没 ...