博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#将文档(Word\ Excel\ PowerPoint\ Visio\ text\ XML\ RTF\ CSV )转成Pdf
阅读量:5096 次
发布时间:2019-06-13

本文共 14501 字,大约阅读时间需要 48 分钟。

详情请看地址:

使用的时候服务器端要安装一套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 application msWordDoc = new Microsoft.Office.Interop.Word.Application { Visible = false, ScreenUpdating = false }; //Open Document doc = 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 PDF object 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 Objects Microsoft.Office.Interop.Excel.Application excelApplication = null; Microsoft.Office.Interop.Excel.Workbook excelWorkbook = null; object unknownType = Type.Missing; // Create new instance of Excel try { //open excel application excelApplication = new Microsoft.Office.Interop.Excel.Application { ScreenUpdating = false, DisplayAlerts = false }; //open excel sheet if (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 document pptPresentation = pptApplication.Presentations.Open((string)originalPptPath, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse); //export PDF from PPT if (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 application msVisioDoc = new Visio.ApplicationClass { Visible = false }; //open visio document vsdDoc = 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; } }}

 源码下载:

 

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

你可能感兴趣的文章
PHP批量覆盖文件并执行cmd命令脚本
查看>>
Unity之fragment shader中如何获得视口空间中的坐标
查看>>
支持向量机——内核
查看>>
MFC注册热键
查看>>
万能的SQLHelper帮助类
查看>>
如何在 Terminal 内可以“用惯用的编辑器”快速打开“目前正在做”的专案(project)呢?...
查看>>
uboot分析:uboot的启动过程分析
查看>>
tmux的简单快捷键
查看>>
springboot笔记04——读取配置文件+使用slf4j日志
查看>>
[Swift]LeetCode653. 两数之和 IV - 输入 BST | Two Sum IV - Input is a BST
查看>>
[Swift]LeetCode922.按奇偶排序数组 II | Sort Array By Parity II
查看>>
微信小程序的wxml文件和wxss文件在webstrom的支持
查看>>
[AngularJS] Lazy Loading modules with ui-router and ocLazyLoad
查看>>
.Net Com口通信编程例子
查看>>
js 编程笔记 【无名函数】
查看>>
Java相对路径/绝对路径总结
查看>>
一个优秀的研发团队应该具备什么特征
查看>>
Jenkins问题汇总
查看>>
QT 项目文件介绍
查看>>
tr69c 调试报错检查
查看>>