PDF文件转换 excel、world、PowerPoing文件转换成PDF

csharp

浏览数:636

2019-1-7

片段 1片段 2片段 3片段 4片段 5片段 6片段 7


Word转换成pdf

        /// <summary>
        /// 把Word文件转换成为PDF格式文件
        /// 作者:zhongjyuan
        /// 日期:2018-12-17
        /// </summary>
        /// <param name="sourcePath">源文件路径</param>
        /// <param name="targetPath">目标文件路径</param>
        /// <returns>true=转换成功</returns>
        public static bool DOCConvertToPDF(string sourcePath, string targetPath,out string strErrMsg)
        {
            bool result = false;
            strErrMsg = "";
            Microsoft.Office.Interop.Word.WdExportFormat exportFormat = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF;
            object paramMissing = Type.Missing;
            
            try
            {
                Microsoft.Office.Interop.Word.ApplicationClass wordApplication = new Microsoft.Office.Interop.Word.ApplicationClass();            
                Microsoft.Office.Interop.Word.Document wordDocument = null;            
            
                object paramSourceDocPath = sourcePath;
                string paramExportFilePath = targetPath;
                
                Microsoft.Office.Interop.Word.WdExportFormat paramExportFormat = exportFormat;
                bool paramOpenAfterExport = false;
                Microsoft.Office.Interop.Word.WdExportOptimizeFor paramExportOptimizeFor = Microsoft.Office.Interop.Word.WdExportOptimizeFor.wdExportOptimizeForPrint;
                Microsoft.Office.Interop.Word.WdExportRange paramExportRange = Microsoft.Office.Interop.Word.WdExportRange.wdExportAllDocument;
                int paramStartPage = 0;
                int paramEndPage = 0;
                Microsoft.Office.Interop.Word.WdExportItem paramExportItem = Microsoft.Office.Interop.Word.WdExportItem.wdExportDocumentContent;
                bool paramIncludeDocProps = true;
                bool paramKeepIRM = true;
                Microsoft.Office.Interop.Word.WdExportCreateBookmarks paramCreateBookmarks = Microsoft.Office.Interop.Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks;
                bool paramDocStructureTags = true;
                bool paramBitmapMissingFonts = true;
                bool paramUseISO19005_1 = false;
                
                wordDocument = wordApplication.Documents.Open(
                ref paramSourceDocPath, ref paramMissing, ref paramMissing,
                ref paramMissing, ref paramMissing, ref paramMissing,
                ref paramMissing, ref paramMissing, ref paramMissing,
                ref paramMissing, ref paramMissing, ref paramMissing,
                ref paramMissing, ref paramMissing, ref paramMissing,
                ref paramMissing);
                   
                if (wordDocument != null)
                    wordDocument.ExportAsFixedFormat(paramExportFilePath,
                    paramExportFormat, paramOpenAfterExport,
                    paramExportOptimizeFor, paramExportRange, paramStartPage,
                    paramEndPage, paramExportItem, paramIncludeDocProps,
                    paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                    paramBitmapMissingFonts, paramUseISO19005_1,
                    ref paramMissing);

                if (wordDocument != null)
                {
                    wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDocument);
                    wordDocument = null;
                }
                
                if (wordApplication != null)
                {
                    wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApplication);
                    wordApplication = null;
                }
                
                result = true;
            }
            catch(Exception ex)
            {
                strErrMsg = ex.Message;
                result = false;
            }
            finally
            {                
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
            
        }


Excel文件转换成PDF格式文件

        /// <summary>
        /// 把Excel文件转换成PDF格式文件
        /// 作者:zhongjyuan
        /// 日期:2018-12-17
        /// </summary>
        /// <param name="sourcePath">源文件路径</param>
        /// <param name="targetPath">目标文件路径</param>
        /// <returns>true=转换成功</returns>
        public static bool XLSConvertToPDF(string sourcePath, string targetPath,out string strErrMsg)
        {
            bool result = false;
            strErrMsg = "";
            Microsoft.Office.Interop.Excel.XlFixedFormatType targetType = Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF;
            object missing = Type.Missing;
            Microsoft.Office.Interop.Excel.ApplicationClass application = null;
            Microsoft.Office.Interop.Excel.Workbook workBook = null;
            try
            {
                application = new Microsoft.Office.Interop.Excel.ApplicationClass();
                object target = targetPath;
                object type = targetType; 
                workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing,
                        missing, missing, missing, missing, missing, missing, missing, missing, missing);
                
                //将excel里每个sheet页面缩放设置为将整个工作表打印在一页
                for (int i = 0; i < workBook.Worksheets.Count; i++)
                {
                    Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Worksheets[i + 1];
                    ws.PageSetup.Orientation = Microsoft.Office.Interop.Excel.XlPageOrientation.xlLandscape;//页面方向竖向
                    ws.PageSetup.Zoom = false;
                    ws.PageSetup.FitToPagesWide = 1;
                    ws.PageSetup.FitToPagesTall = false;
                }
                
                workBook.ExportAsFixedFormat(targetType, target, Microsoft.Office.Interop.Excel.XlFixedFormatQuality.xlQualityMinimum, true, false, missing, missing, missing, missing);
                result = true;
                
                if (workBook != null)
                {
                    workBook.Close(true, missing, missing);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);

                    workBook = null;
                }
                if (application != null)
                {
                    application.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(application);
                    application = null;
                }
            }
            catch(Exception ex)
            {
                strErrMsg = ex.Message; 
                result = false;
            }
            finally
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }


PowerPoing文件转换成PDF格式文件

        /// <summary>
        /// 把PowerPoing文件转换成PDF格式文件
        /// 作者:zhongjyuan
        /// 日期:2018-12-17
        /// </summary>
        /// <param name="sourcePath">源文件路径</param>
        /// <param name="targetPath">目标文件路径</param>
        /// <returns>true=转换成功</returns>
        public static bool PPTConvertToPDF(string sourcePath, string targetPath, out string strErrMsg)
        {
            bool result;
            strErrMsg = "";
            Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType targetFileType = Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPDF;
           
            object missing = Type.Missing;
            Microsoft.Office.Interop.PowerPoint.ApplicationClass application = null;            
            Microsoft.Office.Interop.PowerPoint.Presentation persentation = null;
            
            try
            {
                application = new Microsoft.Office.Interop.PowerPoint.ApplicationClass();                
                persentation = application.Presentations.Open(sourcePath, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);                
                persentation.SaveAs(targetPath, targetFileType, Microsoft.Office.Core.MsoTriState.msoTrue);
                
                if (persentation != null)
                {
                    persentation.Close();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(persentation);
                    persentation = null;
                }
                if (application != null)
                {
                    application.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(application);
                    application = null;
                }

                result = true;
            }
            catch(Exception ex)
            {
                strErrMsg = ex.Message;
                result = false;
            }
            finally
            {
                
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }


Word转PDF=》2

        /// <summary>
        /// word文档转pdf
        /// </summary>
        /// <param name="strSourcePath">源文件物理路径</param>
        /// <param name="strTargetPath">生成pdf文件物理路径</param>
        /// <param name="strErrMsg">错误信息</param>
        /// <returns></returns>
        public static bool WordConvertToPdf(string strSourcePath, string strTargetPath, out string strErrMsg)
        {
            strErrMsg = "";
            try
            {
                //检查源文件是否存在
                if(System.IO.File.Exists(strSourcePath)==false)
                {
                    strErrMsg = "源文件不存在。";
                    return false;
                }

                //如果已经存在要生成的pdf文件,则不需重新生成,直接返回,节省下载时间
                if(System.IO.File.Exists(strTargetPath)==true)
                {
                    return true;
                }

                Aspose.Words.Document doc = new Aspose.Words.Document(strSourcePath);
                doc.Save(strTargetPath, Aspose.Words.SaveFormat.Pdf);                
            }
            catch(Exception ex)
            {
                strErrMsg = ex.Message;
                return false;
            }

            return true;
        }


Excel转PDF=》2

        /// <summary>
        /// excel转pdf
        /// </summary>
        /// <param name="strSourcePath">源文件物理路径</param>
        /// <param name="strTargetPath">生成pdf文件物理路径</param>
        /// <param name="strErrMsg">错误信息</param>
        /// <returns></returns>
        public static bool ExcelConvertToPdf(string strSourcePath, string strTargetPath, out string strErrMsg)
        {
            strErrMsg = "";
            try
            {
                //检查源文件是否存在
                if (System.IO.File.Exists(strSourcePath) == false)
                {
                    strErrMsg = "源文件不存在。";
                    return false;
                }

                //如果已经存在要生成的pdf文件,则不需重新生成,直接返回,节省下载时间
                if (System.IO.File.Exists(strTargetPath) == true)
                {
                    return true;
                }

                Aspose.Cells.Workbook excel = new Aspose.Cells.Workbook(strSourcePath);
                excel.Save(strTargetPath, Aspose.Cells.SaveFormat.Pdf);
            }
            catch (Exception ex)
            {
                strErrMsg = ex.Message;
                return false;
            }

            return true;
        }


PPT转PDF=》2

        /// <summary>
        /// ppf转pdf
        /// </summary>
        /// <param name="strSourcePath">源文件物理路径</param>
        /// <param name="strTargetPath">生成pdf文件物理路径</param>
        /// <param name="strErrMsg">错误信息</param>
        /// <returns></returns>
        public static bool PPTConvertToPdf(string strSourcePath, string strTargetPath, out string strErrMsg)
        {
            strErrMsg = "";
            try
            {
                //检查源文件是否存在
                if (System.IO.File.Exists(strSourcePath) == false)
                {
                    strErrMsg = "源文件不存在。";
                    return false;
                }

                //如果已经存在要生成的pdf文件,则不需重新生成,直接返回,节省下载时间
                if (System.IO.File.Exists(strTargetPath) == true)
                {
                    return true;
                }

                Aspose.Slides.Presentation ppt = new Aspose.Slides.Presentation(strSourcePath);
                ppt.Save(strTargetPath, Aspose.Slides.Export.SaveFormat.Pdf);
            }
            catch (Exception ex)
            {
                strErrMsg = ex.Message;
                return false;
            }

            return true;
        }


给PDF文件加水印(可加文字和图片)

        /// <summary>
        /// 给PDF文件加水印(可加文字和图片)
        /// 此方法为金地定制,格式为水印倾斜度为45度,左下角为金地logo图片,右上角为“金地集团”,右下角为当前用户名+当前日期
        /// </summary>
        /// <param name="filePath">PDF文件物理路径</param>
        /// <param name="waterMarkPic">水印图片物理路径,图片尺寸为64X64</param>
        /// <param name="waterMarkText">水印文本内容</param>
        /// <returns></returns>
        public static bool AddWaterMark(string strInputFilePath, string strOutputFilePath, string strWaterMarkPic, string strWaterMarkText,out string strErrMsg)
        {
            strErrMsg = "";
            

            FileInfo file = new FileInfo(strInputFilePath);
            if(!file.Exists)
            {
                strErrMsg = "源文件不存在。";
                return false;
            }

            if(file.Extension.ToLower()!=".pdf")
            {
                strErrMsg = "源文件不是PDF文件。";
                return false;
            }
            
            //MemoryStream msWater = new MemoryStream();
            PdfReader pdfReader = null;
            PdfStamper pdfStamper = null;
            try
            {
                pdfReader = new PdfReader(strInputFilePath);
                if (File.Exists(strOutputFilePath))
                {
                    File.Delete(strOutputFilePath);
                }
                pdfStamper = new PdfStamper(pdfReader, new FileStream(strOutputFilePath,FileMode.Create));// msWater);                
                
                int total = pdfReader.NumberOfPages + 1;//获取PDF的总页数
                iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);//获取第一页
                float width = psize.Width;//PDF页面的宽度,用于计算水印倾斜
                float height = psize.Height;

                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(strWaterMarkPic);
                image.GrayFill = 0.1f;//透明度,灰色填充
                image.SetAbsolutePosition(width / 2 - 200, height / 2 - 160);
                image.RotationDegrees = 40;

                PdfContentByte overContent;
                BaseFont basefont = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\msyh.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                PdfGState gs = new PdfGState();
                gs.FillOpacity = 0.2F;
                
                for (int i = 1; i < total; i++)
                {                    
                    overContent = pdfStamper.GetOverContent(i);//在内容上方加水印
                    //透明度
                    overContent.SetGState(gs);

                    //添加水印图片 
                    overContent.AddImage(image);
                  
                    //开始写入文本
                    overContent.BeginText();
                    overContent.SetColorFill(BaseColor.LIGHT_GRAY);
                    overContent.SetFontAndSize(basefont, 70);
                    overContent.SetTextMatrix(0, 0);
                    overContent.ShowTextAligned(Element.ALIGN_LEFT, "金地集团", width / 2-20, height/2, 40);

                    overContent.SetFontAndSize(basefont, 30);//strWaterMarkText
                    overContent.ShowTextAligned(Element.ALIGN_LEFT, strWaterMarkText + " " + DateTime.Now.ToString("yyyyMMdd"), width / 2 + 10, height / 2 - 30, 40);

                    overContent.EndText();
                }
            }
            catch (System.Exception ex)
            {
                strErrMsg = ex.Message;
                
                return false;
            }
            finally
            {
                if (pdfStamper != null)
                    pdfStamper.Close();

                if (pdfReader != null)
                    pdfReader.Close();               
                
            }           

            return true;
        }