c#word轉換pdf

首先呢,在項目中建立一個文件夾 wordpath,這個文件夾是存放你的word和pdf的。javascript

首先要準備一個word放進去(.doc)。java

這個呢也是須要引用的,這個引用2015中就有  引用-添加引用-擴展 Microsoft.Office.Interop.Word.dll瀏覽器

而後呢  準備copy代碼app

複製代碼
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;visual-studio

等你加完引用以後 你會發現  艾瑪  應該沒什麼問題了,有問題的話  你能夠百度查查。哈哈哈...spa

其次就是找個地方調用了,這裏呢就在Page_Load裏面調用了code

複製代碼
       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 格式保存文檔。orm

若是須要擴展能夠去官網看看blog

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

相關文章
相關標籤/搜索