zoukankan      html  css  js  c++  java
  • word转pdf(使用office)

    1.安装office软件

    2.在vs中写代码

    注意需要引入

    Microsoft.Office.Interop.Word插件
    /// <summary>
    /// 将word转换成pdf文件
    /// </summary>
    /// <param name="sourcePath">源文件的绝对位置</param>
    /// <param name="targetPath">目标文件的绝对位置</param>
    /// <returns>返回bool是否转换成功</returns>
     public bool WordToPDF(string sourcePath, string targetPath)
            {
                bool result = false;
                Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
                Document document = null;
                try
                {
                    application.Visible = false;
                    document = application.Documents.Open(sourcePath);
                    document.ExportAsFixedFormat(targetPath, WdExportFormat.wdExportFormatPDF);
                    result = true;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    result = false;
                }
                finally
                {
                    document.Close();
                }
                return result;
            }
    

     3.方法的调用

     #region 文件预览如果是pdf直接预览,如果是word进行转换之后预览
            /// <summary>
            /// 文件预览,如果是pdf直接预览,如果是word进行转换之后预览
            /// </summary>
            /// <param name="type">pdf还是word</param>
            /// <param name="url">文件地址</param>
            /// <returns></returns>
            public ActionResult PdfShow(string type, string url)
            {
                if (type == "word")
                {
                    //绝对的资源位置到D://.../wwwroot/
                    string webRootPath = _hostingEnvironment.WebRootPath;
                    url = webRootPath +url;
                    string target = webRootPath + "/files/wordToPdf/reportTest.pdf";
                   //判断是否转换成功
                    bool isSuccess = WordToPDF(url, target);
                    if (isSuccess)
                    {
                        //转换之后把文件的相对位置传给页面
                        ViewBag.files = "/files/wordToPdf/reportTest.pdf";
                    }
                }
                else
                {
                    ViewBag.files = url;
                }
                return View();
            }
            #endregion
    

      最终实现,对word文件的转换和pdf的预览

     转自:https://www.cnblogs.com/yunfeifei/p/4520414.html

  • 相关阅读:
    js,vue.js一些方法的总结
    confirm提示弹出确定和取消按钮
    移动端 meta 必备
    Vue.js总结 [2017.6.5]
    2017.6.5项目总结(移动端touch事件)
    微信公众平台接口开发(全面认识接口)
    数据库作业
    数据库子函数等
    判断一年是否为闰年
    数据库练习
  • 原文地址:https://www.cnblogs.com/xuqp/p/9758749.html
Copyright © 2011-2022 走看看