将文档转成pdf格式
前段时间有研究下讲文件转成pdf档,搜了很多资料,现记录下来。
网上介绍常用的做法是使用 itextsharp.dll 创建一个pdf文档,然后将文档的内容读出来写到创建的pdf档里面。相关主要代码如下:
StreamReader reader = new StreamReader(this.sourceFilePath, Encoding.Default);//读取目标文件 sourceFilePath:源文件路径 string str = reader.ReadToEnd(); reader.Close(); Document document = new Document(new Rectangle(PageSize.A4.Rotate()), 25f, 25f, 25f, 25f); PdfWriter.GetInstance(document, new FileStream(pdfFileSavePath, FileMode.Create)); document.Open(); document.Add(new Paragraph(str)); document.close();
可是当word中有图片的时候,用 ReadToEnd()就会将图片过滤掉,当时也没找到好的解决方案。
由于常用的需要转换的文档基本是office文档,大家可以在office软件中看到 保存为pdf的功能。这个时候就会想到一种思路来做这个事情,就是直接调用office自带的这个功能,来实现office文件向pdf转换。主要代码如下:
word:
Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application(); oWord.Visible = false; Microsoft.Office.Interop.Word.Document oDoc; object oMissing = System.Reflection.Missing.Value; object strFileName = sourceFilePath; oDoc = null; oWord = null; oWord = new Microsoft.Office.Interop.Word.Application(); oDoc = oWord.Documents.OpenNoRepairDialog(ref strFileName, 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); try { string strFilePDFName = Path.GetFileName(pdfSavePath).Replace(Path.GetExtension(pdfSavePath), ".pdf"); object strFileName2 = pdfSavePath; object type = WdSaveFormat.wdFormatPDF; oDoc.SaveAs(ref strFileName2, ref type, 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); } catch(Exception ex) { throw ex; } finally { oDoc.Close(ref oMissing, ref oMissing, ref oMissing); oWord.Quit(ref oMissing, ref oMissing, ref oMissing); GC.Collect(); }
其它类型的写法差不多,可以根据这种思路一一实现的。