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

详情请看地址: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
    {


        /// <summary>
        /// Convert MSOffice file to PDF by calling required method
        /// </summary>
        /// <param name="sourcePath">MSOffice file path</param>
        /// <param name="targetPath">Target PDF path</param>
        /// <param name="sourceType">MSOffice file type</param>
        /// <returns>error code : 0(sucess)/ -1 or errorcode (unknown error or failure)</returns>
        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;
        }

        /// <summary>
        /// Convert Word file to PDF by calling required method
        /// </summary>
        /// <param name="originalDocPath">file path</param>
        /// <param name="pdfPath">Target PDF path</param>
        /// <returns>error code : 0(sucess)/ -1 or errorcode (unknown error or failure)</returns>
        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;
        }

        /// <summary>
        ///  Convert  excel file to PDF by calling required method
        /// </summary>
        /// <param name="originalXlsPath">file path</param>
        /// <param name="pdfPath">Target PDF path</param>
        /// <returns>error code : 0(sucess)/ -1 or errorcode (unknown error or failure)</returns>
        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;
        }

        /// <summary>
        ///  Convert  powerPoint file to PDF by calling required method
        /// </summary>
        /// <param name="originalPptPath">file path</param>
        /// <param name="pdfPath">Target PDF path</param>
        /// <returns>error code : 0(sucess)/ -1 or errorcode (unknown error or failure)</returns>
        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;
        }

        /// <summary>
        ///   Convert   visio file to PDF by calling required method
        /// </summary>
        /// <param name="originalVsdPath">file path</param>
        /// <param name="pdfPath">Target PDF path</param>
        /// <returns>error code : 0(sucess)/ -1 or errorcode (unknown error or failure)</returns>
        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;
        }


    }
}

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

 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用 C# 的 Microsoft.Office.Interop.Word 和 Microsoft.Office.Interop.Excel 库,将 WordExcel 文件换为 PDF 格式,然后使用第三方的 PDF 打印工具批量打印这些 PDF 文件。以下是具体步骤: 1. 引用 Microsoft.Office.Interop.Word 和 Microsoft.Office.Interop.Excel 库,如果您使用的是 Visual Studio,可以在“解决方案资源管理器”中右键单击项目名称,选择“添加”->“引用”->“COM”选项卡,然后勾选“Microsoft Word xx.x Object Library”和“Microsoft Excel xx.x Object Library”; 2. 创建 WordExcel 应用程序对象,打开需要换的 WordExcel 文件; 3. 使用应用程序对象的“ExportAsFixedFormat”方法将 WordExcel 文件换为 PDF 格式; 4. 关闭 WordExcel 文件,销毁应用程序对象; 5. 下载并安装一个第三方的 PDF 打印工具,如 Adobe Acrobat Reader 或 Foxit Reader; 6. 使用 C# 调用第三方的 PDF 打印工具,将需要打印的 PDF 文件添加到打印列表中; 7. 配置打印选项,如打印机、打印质量等; 8. 点击“打印”按钮,即可批量打印 PDF 文件。 需要注意的是,在WordExcel 文件为 PDF 格式时,可能会出现格式错位、字体不一致等问题。建议在换前进行一次预览,确保换后的 PDF 文件符合预期。同时,如果您打算开发一个批量打印工具,还需要考虑如何对文件进行批量处理、如何处理换和打印过程中可能发生的异常等问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值