码迷,mamicode.com
首页 > Windows程序 > 详细

c#word转换pdf

时间:2018-08-06 17:16:32      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:dex   file   dll   sof   添加引用   page   rdp   显示   off   

首先呢,在项目中创建一个文件夹 wordpath,这个文件夹是存放你的word和pdf的。

首先要准备一个word放进去(.doc)。

这个呢也是需要引用的,这个引用2015中就有  引用-添加引用-扩展 Microsoft.Office.Interop.Word.dll

然后呢  准备copy代码

public bool WordToPDF(string sourcePath)
        {
            bool result = false;
            Word.Application application = new Word.Application();
            Word.Document document = null;
            try
            {
                application.Visible = false;
                document = application.Documents.Open(sourcePath);
                string PDFPath = sourcePath.Replace(".doc", ".pdf");//pdf存放位置
                if (!File.Exists(@PDFPath))//存在PDF,不需要继续转换
                {
                    document.ExportAsFixedFormat(PDFPath, Word.WdExportFormat.wdExportFormatPDF);
                }
                result = true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                result = false;
            }
            finally
            {
                document.Close();
            }
            return result;
        }

贴上去之后你会发现  你的引用没加  会报错呦,因此就要加一个引用,像这样using Word = Microsoft.Office.Interop.Word;

等你加完引用之后 你会发现  艾玛  应该没什么问题了,有问题的话  你可以百度查查。哈哈哈...

其次就是找个地方调用了,这里呢就在Page_Load里面调用了

       if (!IsPostBack)
            {
                string strWord = Server.MapPath("/wordpath/***.doc");//文档路径
                WordToPDF(strWord);
                string browsertype = Page.Request.Browser.Type;//浏览器类型判断
                if (browsertype != "IE6" && browsertype != "IE7")
                {
        //这里是生成好的pdf是做一个显示,在这一步之前 pdf已经生成好了
                    Response.Write("<script language=‘javascript‘>window.open(‘/wordpath/***.pdf‘);</script>");
                }
            }

就是用微软的一个方法 以 PDF 或 XPS 格式保存文档。

如果需要扩展可以去官网看看

https://docs.microsoft.com/zh-cn/previous-versions/visualstudio/visual-studio-2010/bb398522(v=vs.100)

 

c#word转换pdf

标签:dex   file   dll   sof   添加引用   page   rdp   显示   off   

原文地址:https://www.cnblogs.com/wangxlei/p/9431149.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!