利用 Aspose.Words 组件,在不依赖与 Office 组件的情况下把 Word 文件转换成 HTML 代码。

首先利用 Nuget 获取 Aspose.Words.dll

public ActionResult AsposeWordsDemo()
{
    string srcFileName = Server.MapPath("~/Data/a.doc");
    Document doc = new Document(srcFileName);

    string basicDirVirtualPath = "/UploadFiles/";

    string tempDir = Server.MapPath(basicDirVirtualPath);

    HtmlSaveOptions saveOptions = new HtmlSaveOptions();
    // Specify folder where images will be saved.
    saveOptions.ImagesFolder = tempDir;
    // We want the images in the HTML to be referenced in the e-mail as attachments so add the cid prefix to the image file name.
    // This replaces what would be the path to the image with the "cid" prefix.
    saveOptions.ImagesFolderAlias = basicDirVirtualPath;
    // Header footers don't normally export well in HTML format so remove them.
    saveOptions.ExportHeadersFootersMode = ExportHeadersFootersMode.None; // saveOptions.ExportHeadersFooters = false; // 老版本用这个
            
    // Save the document to stream in HTML format.
    MemoryStream htmlStream = new MemoryStream();
    doc.Save(htmlStream, saveOptions);

    // Read the HTML from the stream as plain text.
    string htmlText = Encoding.UTF8.GetString(htmlStream.ToArray());
    htmlStream.Close();

    // Save the HTML into the temporary folder.

    string htmlFileNameWithoutPath = "Message.html";

    Stream htmlFile = new FileStream(Path.Combine(tempDir, htmlFileNameWithoutPath), FileMode.Create);
    StreamWriter htmlWriter = new StreamWriter(htmlFile);
    htmlWriter.Write(htmlText);
    htmlWriter.Close();
    htmlFile.Close();

    return Redirect(basicDirVirtualPath + htmlFileNameWithoutPath);
}

猜你喜欢

转载自www.cnblogs.com/johnblogs/p/8984372.html