net core实现htlm转word

1、最开始用的Spire.Doc,但是Spire.Doc只能在windows上使用,部署到docker上无法使用,原因是Spire.Doc使用了库 System.Drawing.Common

2、 之后使用Aspose.Words,示例代码如下:

      public static void Run()
        {
            Document doc = new Document(@"D:\testhtml.html");
            doc.Save(@"D:\aspose_word.docx");
        }

可以在windows使用,也可以在linux上使用。不过免费版有水印

3、最后找到了一个库叫sautinsoft.document。可以实现功能,可以linux上使用,并且没有水印。示例代码如下

public static void ConvertFromStream()
        {
            // We need files only for demonstration purposes.
            // The conversion process will be done completely in memory.
            string inpFile = @"D:\testhtml2.html";
            string outFile = @"D:\sautinsoft_word2.docx";
            byte[] inpData = File.ReadAllBytes(inpFile);
            byte[] outData = null;

            using (MemoryStream msInp = new MemoryStream(inpData))
            {

                // Load a document.
                DocumentCore dc = DocumentCore.Load(msInp, new SautinSoft.Document.HtmlLoadOptions());

                // Save the document to DOCX format.
                using (MemoryStream outMs = new MemoryStream())
                {
                    dc.Save(outMs, new DocxSaveOptions());
                    outData = outMs.ToArray();
                }
                // Show the result for demonstration purposes.
                if (outData != null)
                {
                    File.WriteAllBytes(outFile, outData);
                    System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
                }
            }

 

html转doc给前端返回文件的base64示例代码如下:

          byte[] inpData = File.ReadAllBytes(htmlPath);
                using var msInp = new MemoryStream(inpData);
                DocumentCore dc = DocumentCore.Load(msInp, new SautinSoft.Document.HtmlLoadOptions());
                using MemoryStream outMs = new MemoryStream();
                dc.Save(outMs, new DocxSaveOptions());
                var outData = outMs.ToArray();

                var fileResult = new DownFileResult
                {
                    FileName = $"word_name.doc",
                    Base64Str = Convert.ToBase64String(outData)
                };

 

posted @ 2023-11-10 09:26  向萧  阅读(218)  评论(0编辑  收藏  举报