用心做好每一件事情!

word,excel,ppt,txt转换为 PDF

复制代码
/// <summary> 
/// 将word文档转换成PDF格式 
/// </summary> 
/// <param name="sourcePath"></param> 
/// <param name="targetPath"></param> 
/// <returns></returns> 
public static bool ConvertWord2Pdf(string sourcePath, string targetPath) 
{ 
    bool result; 
    Word.WdExportFormat exportFormat= Word.WdExportFormat.wdExportFormatPDF; 
    object paramMissing = Type.Missing; 
    Word.Application wordApplication = new Word.Application(); 
    Word.Document wordDocument = null; 
    try 
    { 
        object paramSourceDocPath = sourcePath; 
        string paramExportFilePath = targetPath;
        Word.WdExportFormat paramExportFormat = exportFormat; 
        Word.WdExportOptimizeFor paramExportOptimizeFor = 
                Word.WdExportOptimizeFor.wdExportOptimizeForPrint; 
        Word.WdExportRange paramExportRange = Word.WdExportRange.wdExportAllDocument; 
        int paramStartPage = 0; 
        int paramEndPage = 0; 
        Word.WdExportItem paramExportItem = Word.WdExportItem.wdExportDocumentContent; 
        Word.WdExportCreateBookmarks paramCreateBookmarks = 
                Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks; 
    
        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, false, 
                    paramExportOptimizeFor, paramExportRange, paramStartPage, 
                    paramEndPage, paramExportItem, true, 
                    true, paramCreateBookmarks, true, 
                    true, false, 
                    ref paramMissing); 
        result = true; 
    } 
    finally 
    { 
        if (wordDocument != null) 
        { 
            wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing); 
            wordDocument = null; 
        } 
        if (wordApplication != null) 
        { 
            wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing); 
            wordApplication = null; 
        } 
        GC.Collect(); 
        GC.WaitForPendingFinalizers(); 
        GC.Collect(); 
        GC.WaitForPendingFinalizers(); 
    } 
    return result; 
}
/// <summary> 
/// 将excel文档转换成PDF格式 
/// </summary> 
/// <param name="sourcePath"></param> 
/// <param name="targetPath"></param> 
/// <returns></returns> 
public static bool ConvertExcel2Pdf(string sourcePath, string targetPath) 
{ 
    bool result; 
    object missing = Type.Missing; 
    Excel.XlFixedFormatType targetType= Excel.XlFixedFormatType.xlTypePDF; 
    Excel.Application application = null; 
    Excel.Workbook workBook = null; 
    try 
    { 
        application = new Excel.Application(); 
        object target = targetPath; 
        workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing, 
                missing, missing, missing, missing, missing, missing, missing, missing, missing);
        workBook.ExportAsFixedFormat(targetType, target, Excel.XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing); 
        result = true; 
    } 
    catch 
    { 
        result = false; 
    } 
    finally 
    { 
        if (workBook != null) 
        { 
            workBook.Close(true, missing, missing); 
            workBook = null; 
        } 
        if (application != null) 
        { 
            application.Quit(); 
            application = null; 
        } 
        GC.Collect(); 
        GC.WaitForPendingFinalizers(); 
        GC.Collect(); 
        GC.WaitForPendingFinalizers(); 
    } 
    return result; 
}
/// <summary> 
/// 将ppt文档转换成PDF格式 
/// </summary> 
/// <param name="sourcePath"></param> 
/// <param name="targetPath"></param> 
/// <returns></returns> 
public static bool ConvertPowerPoint2Pdf(string sourcePath, string targetPath) 
{ 
    bool result; 
    PowerPoint.PpSaveAsFileType targetFileType= PowerPoint.PpSaveAsFileType.ppSaveAsPDF; 
    PowerPoint.Application application = null; 
    PowerPoint.Presentation persentation = null; 
    try 
    { 
        application = new PowerPoint.Application(); 
        persentation = application.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse); 
        persentation.SaveAs(targetPath, targetFileType, MsoTriState.msoTrue);
        result = true; 
    } 
    catch 
    { 
        result = false; 
    } 
    finally 
    { 
        if (persentation != null) 
        { 
            persentation.Close(); 
            persentation = null; 
        } 
        if (application != null) 
        { 
            application.Quit(); 
            application = null; 
        } 
        GC.Collect(); 
        GC.WaitForPendingFinalizers(); 
        GC.Collect(); 
        GC.WaitForPendingFinalizers(); 
    } 
    return result; 
} 


/// <summary> 
       /// 将Txt转换为PDF 
       /// </summary> 
       /// <param name="sourcePath"></param> 
       /// <param name="targetPath"></param> 
       /// <returns></returns> 
       public static bool ConvertText2Pdf(string sourcePath, string targetPath) 
       { 
           var text = FileHelper.ReadTextFile(sourcePath); 
           Document document = new Document(PageSize.A4);
           try 
           { 
               //step 2:创建一个writer用于监听Document以及通过PDF-stream指向一个文件  
               PdfWriter.GetInstance(document, new FileStream(targetPath, FileMode.Create)); 
               // step 3: 打开document  
               document.Open();
               var f = GetFont(); 
               // step 4: 添加一段话到document中  
               document.Add(new Paragraph(text, f)); 
           } 
           catch (Exception ex) 
           { 
               return false; 
           } 
           finally 
           { 
               if (document.IsOpen()) 
                   // step 5: 关闭document  
                   document.Close(); 
           } 
           return true; 
       }
       private static Font GetFont() 
       { 
           var fontPath = (string) ConfigurationManager.AppSettings["FontPath"]; 
           if (string.IsNullOrEmpty(fontPath))//没有指定字体就用楷体 
           { 
               var fontName = "楷体"; 
               if (!FontFactory.IsRegistered(fontName)) 
               { 
                   fontPath = Environment.GetFolderPath(Environment.SpecialFolder.Windows) + @"\Fonts\simkai.ttf"; 
                   FontFactory.Register(fontPath); 
               } 
               return FontFactory.GetFont(fontName, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); 
           } 
           BaseFont bfChinese = BaseFont.CreateFont(fontPath,BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED); 
           Font fontChinese = new Font(bfChinese, 16f, Font.NORMAL); 
           return fontChinese; 
       } 


public static bool ConvertHtml2Pdf(string text, string pdfPath) 
        { 
            Document document = new Document(PageSize.A4);
            try 
            { 
                PdfWriter.GetInstance(document, new FileStream(pdfPath, FileMode.Create)); 
                document.Open(); 
             
                var fontName = "楷体"; 
                if (!FontFactory.IsRegistered(fontName)) 
                { 
                    var fontPath = Environment.GetFolderPath(Environment.SpecialFolder.Windows) + @"\Fonts\simkai.ttf"; 
                    FontFactory.Register(fontPath); 
                } 
                var elements = iTextSharp.tool.xml.XMLWorkerHelper.ParseToElementList(text, @"body { 
    font-size: 16px; 
    color: #F00; 
    font-family: 楷体; 
}"); 
                //iTextSharp.text. 
                foreach (var element in elements) 
                { 
                    document.Add(element); 
                }
            } 
            catch (DocumentException de) 
            { 
                Console.Error.WriteLine(de.Message); 
            } 
            catch (IOException ioe) 
            { 
                Console.Error.WriteLine(ioe.Message); 
            } 
            document.Close(); 
            return true; 
        }


复制代码

 

from: https://www.cnblogs.com/studyzy/p/5338398.html

posted @   无 影  阅读(684)  评论(1编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
作者: Allen【QQ:96966 1314】 网名:无影 出处: http://www.cnblogs.com/allen0118/ 声明: 本文版权归作者和博客园共有!转载时必须保留此段声明,且在文章页面明显位置给出原文连接。
点击右上角即可分享
微信分享提示