.NET中实现Word,Excle文档到PDF文档的转化

来源:互联网 发布:unity3d 中国象棋 编辑:程序博客网 时间:2024/05/22 16:22

       以下文章介绍C#(.NET)下的将Word/Excle转化成PDF文档。

       1.使用微软Office的COM组件+iTextShape进行转化。

        主要思路如下:首先通过COM组件读取Word/Excle文档的相关的内容,然后使用iTextShape将独取出来的数据写入到PDF文档中。

        首先在项目中引入COM组件

       如图所示:

      

       引入COM组件之后,记住要进行引用(using)。然后就可以通过COM组件读取Word文档的内容了

    //用于打开Word程序的对象(word程序)            Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();            object nullobj = System.Reflection.Missing.Value;            object fileobj = filePath;            //打开的word文档            Microsoft.Office.Interop.Word.Document document = application.Documents.Open(            ref fileobj,            ref nullobj,            ref nullobj,            ref nullobj,            ref nullobj,            ref nullobj,            ref nullobj,            ref nullobj,            ref nullobj,            ref nullobj,            ref nullobj,            ref nullobj,            ref nullobj,            ref nullobj,            ref nullobj,            ref nullobj);            //取得doc中的文本            string file_text = document.Content.Text;            //替换一下敏感的字符            file_text=file_text.Replace('\a',' ');            file_text = file_text.Replace('\r', '\n');                        //关闭文档            document.Close(ref nullobj, ref nullobj, ref nullobj);            //关闭COM组件            application.Quit(ref nullobj, ref nullobj, ref nullobj);            GC.Collect();            GC.WaitForPendingFinalizers();            //将内容写到Pdf中            WriteToPdf(file_text, filePath);         

          写入到PDF文档代码如如下:

       //将内容写入到Pdf文档中        private void WriteToPdf(string file_text, string file_path)        {            /*将图片写入到Pdf文件中*/            iTextSharp.text.Document pdfdocument = new iTextSharp.text.Document(PageSize.A4, 9, 18, 36, 36);   //创建一个文档变量            string fileName = file_path.Split('\\').Last<string>().Split('.').First<string>();            PdfWriter write = PdfWriter.GetInstance(pdfdocument, new FileStream(@"D:\pdfTest\" + fileName + ".pdf", FileMode.App            end));//创建文档            pdfdocument.Open();            //使用Windows自带的字体库(确保系统盘在C盘)            BaseFont baseFT = BaseFont.CreateFont("C:\\Windows\\Fonts\\Simsun.TTC,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);            iTextSharp.text.Font font = new iTextSharp.text.Font(baseFT);            //写入一个段落, Paragraph            pdfdocument.Add(new iTextSharp.text.Paragraph(file_text, font));            //关闭document            pdfdocument.Close();        }

          但是这种方法会丢失Word文档中格式,这是一个致命的缺陷,也可能是我水平不够,没有发现更好的方法,哪位知道告诉我我一下,谢谢了。

          2.使用Aspose.Words第三方控件来进行转化,Aspose.Words最新版在我的资料可以进行下载,此版本支持中文。

          首先引入Aspose.Words控件,添加引用即可。转化的代码及其简单,如下:

 /*             *使用Aspose.Words第三方工具来进行Word到PDF文件的转化             */            string fileName = filePath.Split('\\').Last<string>().Split('.').First<string>();  //获取文件名            Aspose.Words.Document document = new Aspose.Words.Document(filePath);            document.Save(@"D:\pdfTest\" + fileName + ".pdf", SaveFormat.Pdf);

         接下来是Excle文档的转换。Excle文档具有伸缩的特点,所以需要读取每个单元格的信息然后在PDF文件中写入表格中,最后将表格插入到PDF文档中。

        代码如下:

/*         * 将Xls文件转化成Pdf文件         * 如果Xls文档单元格过多,分页显示         * */        private void XlsTransformPdf(string filePath)        {            Microsoft.Office.Interop.Excel.Application application = new Microsoft.Office.Interop.Excel.Application();            object nullobj = System.Reflection.Missing.Value;            object fileobj = filePath;            Microsoft.Office.Interop.Excel.WorkbookClass excleWorkClass= null;            //打开Excle的文档            excleWorkClass = (Microsoft.Office.Interop.Excel.WorkbookClass)application.Workbooks.Open(filePath, nullobj, false, nullobj, nullobj, nullobj, true, nullobj, nullobj, true, nullobj, nullobj, nullobj, nullobj, nullobj);            //获取所有的工作表            Microsoft.Office.Interop.Excel.Sheets sheets = excleWorkClass.Worksheets;            //循环所有的工作表            foreach (Microsoft.Office.Interop.Excel.Worksheet sheetItem in sheets)            {                //只转化存在数据的工作表单                if (sheetItem.UsedRange.Rows.Count > 1)                {                    //获取Excle已经使用的单元格的索引,避免获取大量的空单元格信息                    int columnCount = sheetItem.UsedRange.Columns.Count;                    int rowCount = sheetItem.UsedRange.Rows.Count;                                                            char endPosition = (char)('A' + columnCount - 1);                    //设置截取的区域的末尾                    string endString = new string(endPosition, 1) + rowCount.ToString();                    //判断工作表的区域,最多支持36列                    if (columnCount >= 27)                    {                        string[] columnArray = { "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ" };                        endString = columnArray[columnCount - 27] + rowCount.ToString();                    }                    Microsoft.Office.Interop.Excel.Range range = sheetItem.get_Range("A1", endString);                    //将单元格信息保存在数组中                    System.Array array = (System.Array)range.Cells.Value2;                    //将数据填充到PDF中,使用iTextShape将表格插入到PDF文件中                    iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(columnCount);   //创建指定列数的表格                    //设置中文字体                    BaseFont baseFT = BaseFont.CreateFont("C:\\Windows\\Fonts\\Simsun.TTC,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);                    iTextSharp.text.Font font = new iTextSharp.text.Font(baseFT);                    //循环读取数组,填充到PDF表格中                    for (int row = 1; row <= rowCount; row++)                    {                        for (byte column = 1; column <= columnCount; column++)                        {                            iTextSharp.text.pdf.PdfPCell cell = new PdfPCell(); //添加单元格                            object text = array.GetValue(row, column);                            Phrase phrase = null;                            //向表格中添加数据                            if (text == null)                                phrase = new Phrase();                            else                                phrase = new Phrase(text.ToString(), font);                            //设置边框                            cell.BorderWidth = 1;                            cell.Padding = 1;                            //向表格中添加数据                            cell.AddElement(phrase);                            table.AddCell(cell);                        }                    }                    //新建PDF文档,将表格放入文档中                    iTextSharp.text.Document pdfdocument = new iTextSharp.text.Document(PageSize.A4, 9, 18, 36, 36);   //创建一个文档变量                    string fileName = filePath.Split('\\').Last<string>().Split('.').First<string>();                    PdfWriter write = PdfWriter.GetInstance(pdfdocument, new FileStream(@"D:\pdfTest\" + fileName + ".pdf", FileMode.Append));//创建文档                    pdfdocument.Open();                    //写入一个段落, Paragraph                    pdfdocument.Add(table);                    //关闭document                    pdfdocument.Close();                     //*                     // * */                }           }        }




 

原创粉丝点击