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版本项目中使用)

Microsoft.Office.Interop.Word
Microsoft.Office.Interop.PowerPoint
Microsoft.Office.Interop.Excel
public class OfficeHelper
{
static Word.Application wordApplication = new Word.Application();
static Excel.Application excelApplication = new Excel.Application();
static PowerPoint.Application pptApplication = new PowerPoint.Application(); /// <summary>
/// 将Word文档转换成PDF格式
/// </summary>
/// <param name="sourcePath">源文件路径</param>
/// <param name="targetPath">目标文件路径</param>
/// <returns></returns>
public static bool WordConvertPDF(string sourcePath, string targetPath)
{
bool result;
Word.Document wordDocument = null;
try
{
wordDocument = wordApplication.Documents.Open(ref sourcePath);
if (wordDocument != null)
{
wordDocument.SaveAs2(targetPath, WdExportFormat.wdExportFormatPDF);
//wordDocument.ExportAsFixedFormat(targetPath, WdExportFormat.wdExportFormatPDF);
result = true;
}
}
catch (Exception ex)
{
result = false;
LogHelper.Log($"文件:{sourcePath} 生成失败,原因:{ex.Message}", ex.StackTrace);
}
finally
{
if (wordDocument != null)
{
wordDocument.Close();
wordDocument = null;
}
}
return result;
} /// <summary>
/// 将Excel文档转换成PDF格式
/// </summary>
/// <param name="sourcePath">源文件路径</param>
/// <param name="targetPath">目标文件路径</param>
/// <returns></returns>
public static bool ExcelConvertPDF(string sourcePath, string targetPath)
{
bool result;
Workbook workBook = null;
try
{
workBook = excelApplication.Workbooks.Open(sourcePath);
if (workBook != null)
{
workBook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, targetPath);
result = true;
}
}
catch (Exception ex)
{
result = false;
LogHelper.Log($"文件:{sourcePath} 生成失败,原因:{ex.Message}", ex.StackTrace);
}
finally
{
if (workBook != null)
{
workBook.Close();
workBook = null;
}
}
return result;
} /// <summary>
/// 将PPT文档转换成pdf格式
/// </summary>
/// <param name="sourcePath">源文件路径</param>
/// <param name="targetPath">目标文件路径</param>
/// <returns></returns>
public static bool PPTConvertPDF(string sourcePath, string targetPath)
{
bool result;
object missing = Type.Missing;
Presentation persentation = null;
try
{
persentation = pptApplication.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
if (persentation != null)
{
persentation.SaveAs(targetPath, PpSaveAsFileType.ppSaveAsPDF, Microsoft.Office.Core.MsoTriState.msoTrue);
//persentation.ExportAsFixedFormat(targetPath, PpFixedFormatType.ppFixedFormatTypePDF);
result = true;
}
}
catch (Exception ex)
{
result = false;
LogHelper.Log($"文件:{sourcePath} 生成失败,原因:{ex.Message}", ex.StackTrace);
}
finally
{
if (persentation != null)
{
persentation.Close();
persentation = null;
}
}
return result;
}
}

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

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

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

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

using NetOffice;
using NetOffice.PowerPointApi;
public static void PPTConvertPDF(string sourcePath, string targetPath)
{
using (Application _pptApp = new Application())
{
var pres = _pptApp.Presentations.Open(sourcePath, NetOffice.OfficeApi.Enums.MsoTriState.msoCTrue, NetOffice.OfficeApi.Enums.MsoTriState.msoFalse, NetOffice.OfficeApi.Enums.MsoTriState.msoFalse);
pres.SaveAs(targetPath, NetOffice.PowerPointApi.Enums.PpSaveAsFileType.ppSaveAsPDF);
pres.Close();
}
}

1.2 基于WPS实现的解决方案

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

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

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

其中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包管理安装需要用到的包

DocumentFormat.OpenXml
using DocumentFormat.OpenXml.Packaging;

/// <summary>
/// 导出PPT文件中所有图片
/// </summary>
/// <param name="sourcePath">源文件路径</param>
/// <param name="targetDir">目标文件存放目录</param>
/// <returns></returns>
public static void ExportPPTImages(string sourcePath,string targetDir)
{
using (PresentationDocument presentationDocument = PresentationDocument.Open(sourcePath, isEditable: false))
{
PresentationPart presentationPart = presentationDocument.PresentationPart;
DocumentFormat.OpenXml.Presentation.Presentation presentation = presentationPart.Presentation;
List<ImagePart> list = new List<ImagePart>();
foreach (DocumentFormat.OpenXml.Presentation.SlideId item in presentation.SlideIdList.OfType<DocumentFormat.OpenXml.Presentation.SlideId>())
{
SlidePart slidePart = presentationPart.GetPartById(item.RelationshipId) as SlidePart;
list.AddRange(slidePart.ImageParts);
}
List<IGrouping<string, ImagePart>> list2 = list.GroupBy(d => d.Uri.OriginalString).ToList(); //导出PPT所有的图片
for (int i = 0; i < list2.Count; i++)
{
ImagePart imagePart = list2[i].FirstOrDefault();
string tempFileName = Path.Combine(targetDir, $"image_{i}.jpg");
using (Stream stream = imagePart.GetStream(FileMode.Open))
{
using (Bitmap bitmap = new Bitmap(stream))
{
bitmap.Save(tempFileName, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
//presentation.Save();
}
} /// <summary>
/// 导出Word文件中所有图片
/// </summary>
/// <param name="sourcePath">源文件路径</param>
/// <param name="targetDir">目标文件存放目录</param>
/// <returns></returns>
public static void ExportWordImages(string sourcePath,string targetDir)
{
using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(sourcePath, isEditable: false))
{
var list2 = wordDocument.MainDocumentPart.ImageParts.GroupBy(d => d.Uri.OriginalString).ToList();
for (int i = 0; i < list2.Count; i++)
{
ImagePart imagePart = list2[i].FirstOrDefault();
string tempFileName = Path.Combine(targetDir, $"image_{i}.jpg");
using (Stream stream = imagePart.GetStream(FileMode.Open))
{
using (Bitmap bitmap = new Bitmap(stream))
{
bitmap.Save(tempFileName, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
}
}

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

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

using Spire.Presentation;

/// <summary>
/// 导出PPT文件中所有图片
/// </summary>
/// <param name="sourcePath">源文件路径</param>
/// <param name="targetDir">目标文件存放目录</param>
/// <returns></returns>
public static void ExportPPTImages2(string sourcePath, string targetDir)
{
using (Presentation pres = new Presentation())
{
pres.LoadFromFile(sourcePath);
for (int i = 0; i < pres.Images.Count; i++)
{
Image image = pres.Images[i].Image;
string tempFileName = Path.Combine(targetDir, $"image_{i}.jpg");
image.Save(tempFileName);
}
}
}

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. 关于STM32的CAN的过滤器

    关于STM32的CAN的过滤器STM32普通型芯片的CAN有14组过滤器组,互联型有28组过滤器组.一般我们用的都是普通型的,所以在本文中可以说STM32有14组过滤器组.根据配置,每1组过滤器组可以 ...

  2. stm32之can总线过滤器研究

    stm32的can总线的配置如下:       CAN_InitStructure.CAN_TTCM=DISABLE;//禁止时间触发通信模式      CAN_InitStructure.CAN_A ...

  3. 详细介绍如何自研一款"博客搬家"功能

    前言 现在的技术博客(社区)越来越多,比如:imooc.spring4All.csdn.cnblogs或者iteye等,有很多朋友可能在这些网站上都发表过博文,当有一天我们想自己搞一个博客网站时就会发 ...

  4. 循序渐进VUE+Element 前端应用开发(31)--- 系统的日志管理,包括登录日志、接口访问日志、实体变化历史日志

    在一个系统的权限管理模块中,一般都需要跟踪一些具体的日志,ABP框架的系统的日志管理,包括登录日志.接口访问日志.实体变化历史日志,本篇随笔介绍ABP框架中这些日志的管理和界面处理. 1.系统登录日志 ...

  5. C#自定义控件的应用(数据绑定,属性等)

    刚刚开始程序设计的码农生涯,也许一些开发工具上的控件可以满足我们的需求,但是随之时间的迁移,我们对控件的呈现形式需求越来越多样化,这个时候就需要我们来自定义控件,我是一个刚刚入职没多久的菜鸟,接触软件 ...

  6. 改进你的c#代码的5个技巧(二)

    在本文中,我将向你展示c#编程的5个最佳实践.我从日常编程经验中学到了这些实践.我在release模式下测试了所有的代码,并在开发环境稳定后进行了截屏.我想你会喜欢这些建议的. 在使用数据类型之前选择 ...

  7. HDFS 修改默认副本数

    描述:将HDFS副本数修改为2第一步:将HDFS上已有文件副本数修改为2 hdfs dfs -setrep 2 -R -w / 第二步:修改dfs.replication值为2(页面上操作),然后重启 ...

  8. label_form

    表单: action "URL" 如果为空,则本form接收 指定接收方 disabled 指定该标签是否可用 method "net" "http& ...

  9. linux安装ftp步骤

    1,查看是否安装了FTP:rpm -qa |grep vsftpd 2,如果没有安装,可以使用如下命令直接安装 yum -y install vsftpd 默认安装目录:/etc/vsftpd 3,添 ...

  10. Cisco常用命令

    • 首次配置网络设备        ○ 需要使用Console线连接进行初始化配置            § 在PC使用"超级终端"或其他软件.    • 交换机的工作模式:   ...