首先呢,在項目中創建一個文件夾 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)

