热门标签 | 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



推荐阅读
  • Spring源码解密之默认标签的解析方式分析
    本文分析了Spring源码解密中默认标签的解析方式。通过对命名空间的判断,区分默认命名空间和自定义命名空间,并采用不同的解析方式。其中,bean标签的解析最为复杂和重要。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • 本文介绍了一个在线急等问题解决方法,即如何统计数据库中某个字段下的所有数据,并将结果显示在文本框里。作者提到了自己是一个菜鸟,希望能够得到帮助。作者使用的是ACCESS数据库,并且给出了一个例子,希望得到的结果是560。作者还提到自己已经尝试了使用"select sum(字段2) from 表名"的语句,得到的结果是650,但不知道如何得到560。希望能够得到解决方案。 ... [详细]
  • Android系统移植与调试之如何修改Android设备状态条上音量加减键在横竖屏切换的时候的显示于隐藏
    本文介绍了如何修改Android设备状态条上音量加减键在横竖屏切换时的显示与隐藏。通过修改系统文件system_bar.xml实现了该功能,并分享了解决思路和经验。 ... [详细]
  • FeatureRequestIsyourfeaturerequestrelatedtoaproblem?Please ... [详细]
  • Android开发实现的计时器功能示例
    本文分享了Android开发实现的计时器功能示例,包括效果图、布局和按钮的使用。通过使用Chronometer控件,可以实现计时器功能。该示例适用于Android平台,供开发者参考。 ... [详细]
  • 在Xamarin XAML语言中如何在页面级别构建ControlTemplate控件模板
    本文介绍了在Xamarin XAML语言中如何在页面级别构建ControlTemplate控件模板的方法和步骤,包括将ResourceDictionary添加到页面中以及在ResourceDictionary中实现模板的构建。通过本文的阅读,读者可以了解到在Xamarin XAML语言中构建控件模板的具体操作步骤和语法形式。 ... [详细]
  • Spring常用注解(绝对经典),全靠这份Java知识点PDF大全
    本文介绍了Spring常用注解和注入bean的注解,包括@Bean、@Autowired、@Inject等,同时提供了一个Java知识点PDF大全的资源链接。其中详细介绍了ColorFactoryBean的使用,以及@Autowired和@Inject的区别和用法。此外,还提到了@Required属性的配置和使用。 ... [详细]
  • SpringMVC接收请求参数的方式总结
    本文总结了在SpringMVC开发中处理控制器参数的各种方式,包括处理使用@RequestParam注解的参数、MultipartFile类型参数和Simple类型参数的RequestParamMethodArgumentResolver,处理@RequestBody注解的参数的RequestResponseBodyMethodProcessor,以及PathVariableMapMethodArgumentResol等子类。 ... [详细]
  • EPPlus绘制刻度线的方法及示例代码
    本文介绍了使用EPPlus绘制刻度线的方法,并提供了示例代码。通过ExcelPackage类和List对象,可以实现在Excel中绘制刻度线的功能。具体的方法和示例代码在文章中进行了详细的介绍和演示。 ... [详细]
  • Jquery 跨域问题
    为什么80%的码农都做不了架构师?JQuery1.2后getJSON方法支持跨域读取json数据,原理是利用一个叫做jsonp的概念。当然 ... [详细]
  • pythonMatplotlib(二)
    Matplotlib+pandas作图一、对csv文件进行提取ruixi.csv对上述表格进行提取并做图画出图像二、对.xlsx进行提取:rui ... [详细]
  • 人脸检测 pyqt+opencv+dlib
    一、实验目标绘制PyQT界面,调用摄像头显示人脸信息。在界面中,用户通过点击不同的按键可以实现多种功能:打开和关闭摄像头, ... [详细]
  • NetBPM的安装还是比较简单的,有比较详细的文档。1.当然是先下载运行程序了,netbpm-0.8.3.1.zip,官方网站ÿ ... [详细]
  • MyBatis多表查询与动态SQL使用
    本文介绍了MyBatis多表查询与动态SQL的使用方法,包括一对一查询和一对多查询。同时还介绍了动态SQL的使用,包括if标签、trim标签、where标签、set标签和foreach标签的用法。文章还提供了相关的配置信息和示例代码。 ... [详细]
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社区 版权所有