安装Spire.Doc组件 首先需要安装Spire.Doc组件,可以在Nuget包管理器中搜索并安装Spire.Doc。
创建控制器和视图 在ASP.Net MVC应用程序中,创建一个控制器并添加一个动作方法来处理文档操作。例如,“HomeController”控制器和“Index”动作方法。
在“Views/Home”文件夹中添加一个视图文件(.cshtml),该视图负责呈现Word文档。
using Spire.Doc;
public ActionResult Index()
{
//创建Word文档
Document document = new Document();
//保存文件到服务器
document.SaveToFile(Server.MapPath("~/document.docx"), FileFormat.Docx);
//返回视图
return View();
}
这里使用“SaveToFile”方法将文档保存到服务器上,并设置文件格式为“.docx”。
@using Spire.Doc
@{
Document document = new Document();
document.LoadFromFile(Server.MapPath("~/document.docx"));
}
@Spire.Doc.WebViewer.HtmlConverter.ConvertToHtml(document)
这里使用了Spire.Doc的“HtmlConverter.ConvertToHtml”方法将Word文档转换为HTML代码,并使用了Razor语法呈现到页面上。
string fileName = "document.pdf";
document.SaveToFile(Server.MapPath("~/" + fileName),FileFormat.PDF);
return File(Server.MapPath("~/" + fileName), "application/pdf", fileName);
这里将