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



推荐阅读
  • 优化ListView性能
    本文深入探讨了如何通过多种技术手段优化ListView的性能,包括视图复用、ViewHolder模式、分批加载数据、图片优化及内存管理等。这些方法能够显著提升应用的响应速度和用户体验。 ... [详细]
  • 本文详细介绍了Java中org.neo4j.helpers.collection.Iterators.single()方法的功能、使用场景及代码示例,帮助开发者更好地理解和应用该方法。 ... [详细]
  • 本文详细介绍了如何在Linux系统上安装和配置Smokeping,以实现对网络链路质量的实时监控。通过详细的步骤和必要的依赖包安装,确保用户能够顺利完成部署并优化其网络性能监控。 ... [详细]
  • 本文详细介绍了Java编程语言中的核心概念和常见面试问题,包括集合类、数据结构、线程处理、Java虚拟机(JVM)、HTTP协议以及Git操作等方面的内容。通过深入分析每个主题,帮助读者更好地理解Java的关键特性和最佳实践。 ... [详细]
  • 将Web服务部署到Tomcat
    本文介绍了如何在JDeveloper 12c中创建一个Java项目,并将其打包为Web服务,然后部署到Tomcat服务器。内容涵盖从项目创建、编写Web服务代码、配置相关XML文件到最终的本地部署和验证。 ... [详细]
  • XNA 3.0 游戏编程:从 XML 文件加载数据
    本文介绍如何在 XNA 3.0 游戏项目中从 XML 文件加载数据。我们将探讨如何将 XML 数据序列化为二进制文件,并通过内容管道加载到游戏中。此外,还会涉及自定义类型读取器和写入器的实现。 ... [详细]
  • 本文探讨了如何在给定整数N的情况下,找到两个不同的整数a和b,使得它们的和最大,并且满足特定的数学条件。 ... [详细]
  • 本文详细介绍了 Java 中 org.apache.xmlbeans.SchemaType 类的 getBaseEnumType() 方法,提供了多个代码示例,并解释了其在不同场景下的使用方法。 ... [详细]
  • Explore a common issue encountered when implementing an OAuth 1.0a API, specifically the inability to encode null objects and how to resolve it. ... [详细]
  • 本文详细介绍了Java中org.eclipse.ui.forms.widgets.ExpandableComposite类的addExpansionListener()方法,并提供了多个实际代码示例,帮助开发者更好地理解和使用该方法。这些示例来源于多个知名开源项目,具有很高的参考价值。 ... [详细]
  • 使用 Azure Service Principal 和 Microsoft Graph API 获取 AAD 用户列表
    本文介绍了一段通用代码示例,该代码不仅能够操作 Azure Active Directory (AAD),还可以通过 Azure Service Principal 的授权访问和管理 Azure 订阅资源。Azure 的架构可以分为两个层级:AAD 和 Subscription。 ... [详细]
  • 在前两篇文章中,我们探讨了 ControllerDescriptor 和 ActionDescriptor 这两个描述对象,分别对应控制器和操作方法。本文将基于 MVC3 源码进一步分析 ParameterDescriptor,即用于描述 Action 方法参数的对象,并详细介绍其工作原理。 ... [详细]
  • 本文详细介绍了Akka中的BackoffSupervisor机制,探讨其在处理持久化失败和Actor重启时的应用。通过具体示例,展示了如何配置和使用BackoffSupervisor以实现更细粒度的异常处理。 ... [详细]
  • 本文介绍了如何在C#中启动一个应用程序,并通过枚举窗口来获取其主窗口句柄。当使用Process类启动程序时,我们通常只能获得进程的句柄,而主窗口句柄可能为0。因此,我们需要使用API函数和回调机制来准确获取主窗口句柄。 ... [详细]
  • RecyclerView初步学习(一)
    RecyclerView初步学习(一)ReCyclerView提供了一种插件式的编程模式,除了提供ViewHolder缓存模式,还可以自定义动画,分割符,布局样式,相比于传统的ListVi ... [详细]
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社区 版权所有