热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

C#将文档(Word\Excel\PowerPoint\Visio\text\XML\RTF\CSV)转成Pdf

详情请看地址:http:www.codeproject.comTips592957Converting-Document-Word-Excel使用的时候服务器端要安装

详情请看地址:http://www.codeproject.com/Tips/592957/Converting-Document-Word-Excel

使用的时候服务器端要安装一套office,版本至少office2007以上,使用该类要引用几个office的dll

核心操作类如下:

      

using System;
using System.Diagnostics;
using Microsoft.Office.Core;
using Microsoft.Office.Interop.Word;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Visio = Microsoft.Office.Interop.Visio;
using System.Reflection;
using System.Runtime.InteropServices;
using System.IO;namespace DocumentConverter
{
public class ConvDoc2PdfWithMsOffice{///

/// Convert MSOffice file to PDF by calling required method/// /// MSOffice file path/// Target PDF path/// MSOffice file type/// error code : 0(sucess)/ -1 or errorcode (unknown error or failure)public short convert(String sourcePath, String targetPath, ContentType sourceType){Console.WriteLine("Class: " + GetType() + " Method: " + MethodBase.GetCurrentMethod().Name + " Started ");short convDoc2PdfWithMsOfficeResult = 0;if (sourceType == ContentType.DOC || sourceType == ContentType.DOCX || sourceType == ContentType.TXT || sourceType == ContentType.RTF || sourceType == ContentType.XML){convDoc2PdfWithMsOfficeResult = word2Pdf((Object)sourcePath, (Object)targetPath);}else if (sourceType == ContentType.XLS || sourceType == ContentType.XLSX || sourceType == ContentType.CSV){convDoc2PdfWithMsOfficeResult = excel2Pdf(sourcePath, targetPath);}else if (sourceType == ContentType.PPT || sourceType == ContentType.PPTX){convDoc2PdfWithMsOfficeResult = powerPoint2Pdf((Object)sourcePath, (Object)targetPath);}else if (sourceType == ContentType.VSD || sourceType == ContentType.VDX){convDoc2PdfWithMsOfficeResult = visio2Pdf(sourcePath, targetPath);}else convDoc2PdfWithMsOfficeResult = -1;Console.WriteLine("Class: " + GetType() + " Method: " + MethodBase.GetCurrentMethod().Name + " Ended ");return convDoc2PdfWithMsOfficeResult;}/// /// Convert Word file to PDF by calling required method/// /// file path/// Target PDF path/// error code : 0(sucess)/ -1 or errorcode (unknown error or failure)public short word2Pdf(object originalDocPath, object pdfPath){Console.WriteLine("Class: " + GetType() + " Method: " + MethodBase.GetCurrentMethod().Name + " Started ");short convertWord2PdfResult = -1;Microsoft.Office.Interop.Word.Application msWordDoc = null;Microsoft.Office.Interop.Word.Document doc = null;// C# doesn't have optional arguments so we'll need a dummy value object oMissing = System.Reflection.Missing.Value;try{//start MS word applicationmsWordDoc = new Microsoft.Office.Interop.Word.Application{Visible = false,ScreenUpdating = false};//Open Documentdoc = msWordDoc.Documents.Open(ref originalDocPath, ref oMissing,ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,ref oMissing, ref oMissing, ref oMissing, ref oMissing);if (doc != null){doc.Activate();// save Document as PDFobject fileFormat = WdSaveFormat.wdFormatPDF;doc.SaveAs(ref pdfPath,ref fileFormat, ref oMissing, ref oMissing,ref oMissing, ref oMissing, ref oMissing, ref oMissing,ref oMissing, ref oMissing, ref oMissing, ref oMissing,ref oMissing, ref oMissing, ref oMissing, ref oMissing);convertWord2PdfResult = 0;}else{Console.WriteLine("Error occured for conversion of office Word to PDF");convertWord2PdfResult = 504;}}catch (Exception exWord2Pdf){Console.WriteLine("Error occured for conversion of office Word to PDF, Exception: ", exWord2Pdf);convertWord2PdfResult = 504;}finally{// Close and release the Document object.if (doc != null){object saveChanges = WdSaveOptions.wdDoNotSaveChanges;doc.Close(ref saveChanges, ref oMissing, ref oMissing);Util.releaseObject(doc);}// Quit Word and release the ApplicationClass object.((_Application)msWordDoc).Quit(ref oMissing, ref oMissing, ref oMissing);Util.releaseObject(msWordDoc);msWordDoc = null;}Console.WriteLine("Class: " + GetType() + " Method: " + MethodBase.GetCurrentMethod().Name + " Ended ");return convertWord2PdfResult;}/// /// Convert excel file to PDF by calling required method/// /// file path/// Target PDF path/// error code : 0(sucess)/ -1 or errorcode (unknown error or failure)public short excel2Pdf(string originalXlsPath, string pdfPath){Console.WriteLine("Class: " + GetType() + " Method: " + MethodBase.GetCurrentMethod().Name + " Started ");short convertExcel2PdfResult = -1;// Create COM ObjectsMicrosoft.Office.Interop.Excel.Application excelApplication = null;Microsoft.Office.Interop.Excel.Workbook excelWorkbook = null;object unknownType = Type.Missing;// Create new instance of Exceltry{//open excel applicationexcelApplication = new Microsoft.Office.Interop.Excel.Application{ScreenUpdating = false,DisplayAlerts = false};//open excel sheetif (excelApplication != null)excelWorkbook = excelApplication.Workbooks.Open(originalXlsPath, unknownType, unknownType,unknownType, unknownType, unknownType,unknownType, unknownType, unknownType,unknownType, unknownType, unknownType,unknownType, unknownType, unknownType);if (excelWorkbook != null){// Call Excel's native export function (valid in Office 2007 and Office 2010, AFAIK)
excelWorkbook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF,pdfPath,unknownType, unknownType, unknownType, unknownType, unknownType,unknownType, unknownType);convertExcel2PdfResult = 0;}else{Console.WriteLine("Error occured for conversion of office excel to PDF ");convertExcel2PdfResult = 504;}}catch (Exception exExcel2Pdf){Console.WriteLine("Error occured for conversion of office excel to PDF, Exception: ", exExcel2Pdf);convertExcel2PdfResult = 504;}finally{// Close the workbook, quit the Excel, and clean up regardless of the results...if (excelWorkbook != null)excelWorkbook.Close(unknownType, unknownType, unknownType);if (excelApplication != null) excelApplication.Quit();Util.releaseObject(excelWorkbook);Util.releaseObject(excelApplication);}Console.WriteLine("Class: " + GetType() + " Method: " + MethodBase.GetCurrentMethod().Name + " Ended ");return convertExcel2PdfResult;}/// /// Convert powerPoint file to PDF by calling required method/// /// file path/// Target PDF path/// error code : 0(sucess)/ -1 or errorcode (unknown error or failure)public short powerPoint2Pdf(object originalPptPath, object pdfPath){Console.WriteLine("Class: " + GetType() + " Method: " + MethodBase.GetCurrentMethod().Name + " Started ");short convertPowerPoint2PdfResult = -1;PowerPoint.Application pptApplication = null;PowerPoint.Presentation pptPresentation = null;object unknownType = Type.Missing;try{//start power point pptApplication = new PowerPoint.Application();//open powerpoint documentpptPresentation = pptApplication.Presentations.Open((string)originalPptPath,Microsoft.Office.Core.MsoTriState.msoTrue,Microsoft.Office.Core.MsoTriState.msoTrue,Microsoft.Office.Core.MsoTriState.msoFalse);//export PDF from PPTif (pptPresentation != null){pptPresentation.ExportAsFixedFormat((string)pdfPath,PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF,PowerPoint.PpFixedFormatIntent.ppFixedFormatIntentPrint,MsoTriState.msoFalse,PowerPoint.PpPrintHandoutOrder.ppPrintHandoutVerticalFirst,PowerPoint.PpPrintOutputType.ppPrintOutputSlides,MsoTriState.msoFalse, null,PowerPoint.PpPrintRangeType.ppPrintAll, string.Empty,true, true, true, true, false, unknownType);convertPowerPoint2PdfResult = 0;}else{Console.WriteLine("Error occured for conversion of office PowerPoint to PDF");convertPowerPoint2PdfResult = 504;}}catch (Exception exPowerPoint2Pdf){Console.WriteLine("Error occured for conversion of office PowerPoint to PDF, Exception: ", exPowerPoint2Pdf);convertPowerPoint2PdfResult = 504;}finally{// Close and release the Document object.if (pptPresentation != null){pptPresentation.Close();Util.releaseObject(pptPresentation);pptPresentation = null;}// Quit Word and release the ApplicationClass object.
pptApplication.Quit();Util.releaseObject(pptApplication);pptApplication = null;}Console.WriteLine("Class: " + GetType() + " Method: " + MethodBase.GetCurrentMethod().Name + " Ended ");return convertPowerPoint2PdfResult;}/// /// Convert visio file to PDF by calling required method/// /// file path/// Target PDF path/// error code : 0(sucess)/ -1 or errorcode (unknown error or failure)public short visio2Pdf(string originalVsdPath, string pdfPath){Console.WriteLine("Class: " + GetType() + " Method: " + MethodBase.GetCurrentMethod().Name + " Started ");short convertVisio2PdfResult = -1;Microsoft.Office.Interop.Visio.ApplicationClass msVisioDoc = null;Visio.Document vsdDoc = null;try{//start applicationmsVisioDoc = new Visio.ApplicationClass { Visible = false };//open visio documentvsdDoc = msVisioDoc.Documents.Open(originalVsdPath);if (vsdDoc != null){//convert visio to PDF
vsdDoc.ExportAsFixedFormat(Visio.VisFixedFormatTypes.visFixedFormatPDF, pdfPath,Visio.VisDocExIntent.visDocExIntentScreen,Visio.VisPrintOutRange.visPrintAll,1, vsdDoc.Pages.Count, false, true, true, true, true,System.Reflection.Missing.Value);convertVisio2PdfResult = 0;}}catch (Exception exVisio2Pdf){Console.WriteLine("Error occured for conversion of office Visio to PDF, Exception: ", exVisio2Pdf);convertVisio2PdfResult = 504;}finally{// Close and release the Document object.if (vsdDoc != null){vsdDoc.Close();Util.releaseObject(vsdDoc);}// Quit Word and release the ApplicationClass object.
msVisioDoc.Quit();Util.releaseObject(msVisioDoc);}Console.WriteLine("Class: " + GetType() + " Method: " + MethodBase.GetCurrentMethod().Name + " Ended ");return convertVisio2PdfResult;}}
}

 源码下载:http://pan.baidu.com/share/link?shareid=2259872815&uk=3289148388

 


转:https://www.cnblogs.com/iwenwen/archive/2013/06/09/3128021.html



推荐阅读
  • 基于PgpoolII的PostgreSQL集群安装与配置教程
    本文介绍了基于PgpoolII的PostgreSQL集群的安装与配置教程。Pgpool-II是一个位于PostgreSQL服务器和PostgreSQL数据库客户端之间的中间件,提供了连接池、复制、负载均衡、缓存、看门狗、限制链接等功能,可以用于搭建高可用的PostgreSQL集群。文章详细介绍了通过yum安装Pgpool-II的步骤,并提供了相关的官方参考地址。 ... [详细]
  • 本文介绍了Java工具类库Hutool,该工具包封装了对文件、流、加密解密、转码、正则、线程、XML等JDK方法的封装,并提供了各种Util工具类。同时,还介绍了Hutool的组件,包括动态代理、布隆过滤、缓存、定时任务等功能。该工具包可以简化Java代码,提高开发效率。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • 本文介绍了C#中生成随机数的三种方法,并分析了其中存在的问题。首先介绍了使用Random类生成随机数的默认方法,但在高并发情况下可能会出现重复的情况。接着通过循环生成了一系列随机数,进一步突显了这个问题。文章指出,随机数生成在任何编程语言中都是必备的功能,但Random类生成的随机数并不可靠。最后,提出了需要寻找其他可靠的随机数生成方法的建议。 ... [详细]
  • 如何使用Java获取服务器硬件信息和磁盘负载率
    本文介绍了使用Java编程语言获取服务器硬件信息和磁盘负载率的方法。首先在远程服务器上搭建一个支持服务端语言的HTTP服务,并获取服务器的磁盘信息,并将结果输出。然后在本地使用JS编写一个AJAX脚本,远程请求服务端的程序,得到结果并展示给用户。其中还介绍了如何提取硬盘序列号的方法。 ... [详细]
  • 阿,里,云,物,联网,net,core,客户端,czgl,aliiotclient, ... [详细]
  • ZSI.generate.Wsdl2PythonError: unsupported local simpleType restriction ... [详细]
  • 本文介绍了RPC框架Thrift的安装环境变量配置与第一个实例,讲解了RPC的概念以及如何解决跨语言、c++客户端、web服务端、远程调用等需求。Thrift开发方便上手快,性能和稳定性也不错,适合初学者学习和使用。 ... [详细]
  • 计算机存储系统的层次结构及其优势
    本文介绍了计算机存储系统的层次结构,包括高速缓存、主存储器和辅助存储器三个层次。通过分层存储数据可以提高程序的执行效率。计算机存储系统的层次结构将各种不同存储容量、存取速度和价格的存储器有机组合成整体,形成可寻址存储空间比主存储器空间大得多的存储整体。由于辅助存储器容量大、价格低,使得整体存储系统的平均价格降低。同时,高速缓存的存取速度可以和CPU的工作速度相匹配,进一步提高程序执行效率。 ... [详细]
  • 闭包一直是Java社区中争论不断的话题,很多语言都支持闭包这个语言特性,闭包定义了一个依赖于外部环境的自由变量的函数,这个函数能够访问外部环境的变量。本文以JavaScript的一个闭包为例,介绍了闭包的定义和特性。 ... [详细]
  • 本文介绍了如何使用C#制作Java+Mysql+Tomcat环境安装程序,实现一键式安装。通过将JDK、Mysql、Tomcat三者制作成一个安装包,解决了客户在安装软件时的复杂配置和繁琐问题,便于管理软件版本和系统集成。具体步骤包括配置JDK环境变量和安装Mysql服务,其中使用了MySQL Server 5.5社区版和my.ini文件。安装方法为通过命令行将目录转到mysql的bin目录下,执行mysqld --install MySQL5命令。 ... [详细]
  • Linux服务器密码过期策略、登录次数限制、私钥登录等配置方法
    本文介绍了在Linux服务器上进行密码过期策略、登录次数限制、私钥登录等配置的方法。通过修改配置文件中的参数,可以设置密码的有效期、最小间隔时间、最小长度,并在密码过期前进行提示。同时还介绍了如何进行公钥登录和修改默认账户用户名的操作。详细步骤和注意事项可参考本文内容。 ... [详细]
  • Spring源码解密之默认标签的解析方式分析
    本文分析了Spring源码解密中默认标签的解析方式。通过对命名空间的判断,区分默认命名空间和自定义命名空间,并采用不同的解析方式。其中,bean标签的解析最为复杂和重要。 ... [详细]
  • 开发笔记:加密&json&StringIO模块&BytesIO模块
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了加密&json&StringIO模块&BytesIO模块相关的知识,希望对你有一定的参考价值。一、加密加密 ... [详细]
  • 本文介绍了如何使用iptables添加非对称的NAT规则段,以实现内网穿透和端口转发的功能。通过查阅相关文章,得出了解决方案,即当匹配的端口在映射端口的区间内时,可以成功进行端口转发。详细的操作步骤和命令示例也在文章中给出。 ... [详细]
author-avatar
mobiledu2502921803
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有