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