ASP.NET Core MVC(C#) 文件上传及后台输出响应Aspose.Words处理后文件

本文主要介绍ASP.NET MVC(C#) 中,使用Aspose.Words处理之后的文件,通过ASP.NET MVC(C#) 后台的方法输出到浏览器端的方法,以及相关的示例代码。

1、Aspose组件下载

Aspose下载地址:https://products.aspose.com/words/net

破解版下载地址:https://download.csdn.net/download/yedajiang44/10667863 (aspose.words 18.7破解版含net 和 .net core 2.0版本)

官方文档地址:https://docs.aspose.com/display/wordsnet/Home

官方Demo代码:https://github.com/aspose-words/Aspose.Words-for-.NET

2、Aspose.Words处理文件示例

Word文件使用Aspose.Words组件添加水印示例代码如下,

private static void InsertWatermarkText(Document doc, string watermarkText)
{
    // 创建一个水印形状。这将是一个WordArt形状。
    // 可以随意尝试其他形状类型作为水印。
    Shape watermark = new Shape(doc, ShapeType.TextPlainText);
    watermark.Name = "WaterMark";
    // 设置水印文本。
    watermark.TextPath.Text = watermarkText;
    watermark.TextPath.FontFamily = "Arial";
    watermark.Width = 500;
    watermark.Height = 100;
    // 文本将从左下角指向右上角。
    watermark.Rotation = -40;
    // 如果需要纯黑色文本,请删除以下两行。
    watermark.Fill.Color = Color.Gray; // 尝试LightGray得到更多文字风格的水印
    watermark.StrokeColor = Color.Gray; // 尝试LightGray得到更多文字风格的水印
    // 将水印放在页面中心。
    watermark.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
    watermark.RelativeVerticalPosition = RelativeVerticalPosition.Page;
    watermark.WrapType = WrapType.None;
    watermark.VerticalAlignment = VerticalAlignment.Center;
    watermark.HorizontalAlignment = HorizontalAlignment.Center;
    //创建一个新的段落,并附加水印到这段。
    Paragraph watermarkPara = new Paragraph(doc);
    watermarkPara.AppendChild(watermark);
    //在每个文档部分的所有标题中插入水印。
    foreach (Section sect in doc.Sections)
    {
      //每个部分可能有三个不同的标题,因为我们需要
      //水印将出现在所有页面,插入到所有页眉。
        InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderPrimary);
        InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderFirst);
        InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderEven);
    }
}
private static void InsertWatermarkIntoHeader(Paragraph watermarkPara, Section sect, HeaderFooterType headerType)
{
    HeaderFooter header = sect.HeadersFooters[headerType];
    if (header == null)
    {
        // There is no header of the specified type in the current section, create it.
        header = new HeaderFooter(sect.Document, headerType);
        sect.HeadersFooters.Add(header);
    }
    //在标题中插入一个水印的克隆。
    header.AppendChild(watermarkPara.Clone(true));
}

参考文件.NET Core Aspose Word(.doc,docx)文件加水印

3、文件上传及输出响应Aspose.Words处理后文件

1)上传方法

[HttpPost]
public IActionResult UploadFile(IFormFile file)
{
    if (file == null || file.Length == 0)
        return Content("file not selected");
    var path = Path.Combine(
                Directory.GetCurrentDirectory(), "wwwroot",
               file.FileName);
    WatermarkDoc(file.OpenReadStream(), GetSaveFormat(file.FileName), path);
    return RedirectToAction("Files");
}

2)下载方法

public IActionResult Download(string filename)
{
    if (filename == null)
        return Content("filename not present");

    var path = Path.Combine(
                   Directory.GetCurrentDirectory(),
                   "wwwroot", filename);
    Stream memory = null;
    //若没加过水印需要加水印
    if (path.IndexOf("watermark") == -1)
    {
        memory = WatermarkDoc(path, GetSaveFormat(path));
        memory.Position = 0;
        return File(memory, GetContentType(path), Path.GetFileName(path));
    }
    return File(path, GetContentType(path));
}

3)完整代码

using Aspose.Words;
using Aspose.Words.Drawing;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Threading.Tasks;
using Document = Aspose.Words.Document;

namespace WebApplication1.CJavaPy
{
    public class FileController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
        public Stream WatermarkDoc(string inputFile, SaveFormat saveFormat)
        {
            var doc = new Aspose.Words.Document(inputFile);
            InsertWatermarkText(doc, "https://www.cjavapy.com");
            var outputFile = new MemoryStream();
            outputFile.Seek(0, SeekOrigin.Begin);
            doc.Save(outputFile, saveFormat);
            return outputFile;
        }
        public void WatermarkDoc(Stream inputFile, SaveFormat saveFormat, string fileName)
        {
            var doc = new Aspose.Words.Document(inputFile);
            InsertWatermarkText(doc, "https://www.cjavapy.com");
            doc.Save(fileName, saveFormat);
        }
        private SaveFormat GetSaveFormat(string fileName)
        {
            FileFormatInfo info = FileFormatUtil.DetectFileFormat(fileName);
            SaveFormat result = SaveFormat.Unknown;
            // Display the document type.
            switch (info.LoadFormat)
            {
                case LoadFormat.Doc:
                    result = SaveFormat.Doc;
                    break;
                case LoadFormat.Dot:
                    result = SaveFormat.Dot;
                    break;
                case LoadFormat.Docx:
                    result = SaveFormat.Docx;
                    break;
                case LoadFormat.Docm:
                    result = SaveFormat.Docm;
                    break;
                case LoadFormat.Dotx:
                    result = SaveFormat.Dotx;
                    break;
                case LoadFormat.Dotm:
                    result = SaveFormat.Dotm;
                    break;
                case LoadFormat.FlatOpc:
                    Console.WriteLine("\tFlat OPC document.");
                    break;
                case LoadFormat.Rtf:
                    Console.WriteLine("\tRTF format.");
                    break;
                case LoadFormat.WordML:
                    Console.WriteLine("\tMicrosoft Word 2003 WordprocessingML format.");
                    break;
                case LoadFormat.Html:
                    Console.WriteLine("\tHTML format.");
                    break;
                case LoadFormat.Mhtml:
                    Console.WriteLine("\tMHTML (Web archive) format.");
                    break;
                case LoadFormat.Odt:
                    Console.WriteLine("\tOpenDocument Text.");
                    break;
                case LoadFormat.Ott:
                    Console.WriteLine("\tOpenDocument Text Template.");
                    break;
                case LoadFormat.DocPreWord60:
                    Console.WriteLine("\tMS Word 6 or Word 95 format.");
                    break;
                case LoadFormat.Unknown:
                default:
                    Console.WriteLine("\tUnknown format.");
                    break;
            }
            return result;

        }
        [HttpPost]
        public IActionResult UploadFile(IFormFile file)
        {
            if (file == null || file.Length == 0)
                return Content("file not selected");

            var path = Path.Combine(
                        Directory.GetCurrentDirectory(), "wwwroot",
                       file.FileName);
            WatermarkDoc(file.OpenReadStream(), GetSaveFormat(file.FileName), path);

            return RedirectToAction("Files");
        }
        /*[HttpPost]
        public async Task<IActionResult> UploadFile(IFormFile file)
        {
            if (file == null || file.Length == 0)
                return Content("file not selected");

            var path = Path.Combine(
                        Directory.GetCurrentDirectory(), "wwwroot",
                        file.GetFilename());

            using (var stream = new FileStream(path, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            return RedirectToAction("Files");
        }*/
        private static void InsertWatermarkText(Document doc, string watermarkText)
        {
            // 创建一个水印形状。这将是一个WordArt形状。
            // 可以随意尝试其他形状类型作为水印。
            Shape watermark = new Shape(doc, ShapeType.TextPlainText);
            watermark.Name = "WaterMark";
            // 设置水印文本。
            watermark.TextPath.Text = watermarkText;
            watermark.TextPath.FontFamily = "Arial";
            watermark.Width = 500;
            watermark.Height = 100;
            // 文本将从左下角指向右上角。
            watermark.Rotation = -40;
            // 如果需要纯黑色文本,请删除以下两行。
            watermark.Fill.ForeColor = Color.Gray; // 尝试LightGray得到更多文字风格的水印
            watermark.StrokeColor = Color.Gray; // 尝试LightGray得到更多文字风格的水印
            // 将水印放在页面中心。
            watermark.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
            watermark.RelativeVerticalPosition = RelativeVerticalPosition.Page;
            watermark.WrapType = WrapType.None;
            watermark.VerticalAlignment = VerticalAlignment.Center;
            watermark.HorizontalAlignment = HorizontalAlignment.Center;
            //创建一个新的段落,并附加水印到这段。
            Paragraph watermarkPara = new Paragraph(doc);
            watermarkPara.AppendChild(watermark);
            //在每个文档部分的所有标题中插入水印。
            foreach (Section sect in doc.Sections)
            {
                //每个部分可能有三个不同的标题,因为我们需要
                //水印将出现在所有页面,插入到所有页眉。
                InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderPrimary);
                InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderFirst);
                InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderEven);
            }
        }
        private static void InsertWatermarkIntoHeader(Paragraph watermarkPara, Section sect, HeaderFooterType headerType)
        {
            HeaderFooter header = sect.HeadersFooters[headerType];
            if (header == null)
            {
                // There is no header of the specified type in the current section, create it.
                header = new HeaderFooter(sect.Document, headerType);
                sect.HeadersFooters.Add(header);
            }
            //在标题中插入一个水印的克隆。
            header.AppendChild(watermarkPara.Clone(true));
        }
        public IActionResult Download(string filename)
        {
            if (filename == null)
                return Content("filename not present");

            var path = Path.Combine(
                           Directory.GetCurrentDirectory(),
                           "wwwroot", filename);
            Stream memory = null;
            //若没加过水印需要加水印
            if (path.IndexOf("watermark") == -1)
            {
                memory = WatermarkDoc(path, GetSaveFormat(path));
                memory.Position = 0;
                return File(memory, GetContentType(path), Path.GetFileName(path));
            }
            return File(path, GetContentType(path));
        }
        /* public async Task<IActionResult> Download(string filename)
        {
            if (filename == null)
                return Content("filename not present");

            var path = Path.Combine(
                           Directory.GetCurrentDirectory(),
                           "wwwroot", filename);

            var memory = new MemoryStream();
            using (var stream = new FileStream(path, FileMode.Open))
            {
                await stream.CopyToAsync(memory);
            }
            memory.Position = 0;
            return File(memory, GetContentType(path), Path.GetFileName(path));
        }*/

        private string GetContentType(string path)
        {
            var types = GetMimeTypes();
            var ext = Path.GetExtension(path).ToLowerInvariant();
            return types[ext];
        }

        private Dictionary<string, string> GetMimeTypes()
        {
            return new Dictionary<string, string>
            {
        {".txt", "text/plain"},
        {".pdf", "application/pdf"},
        {".doc", "application/vnd.ms-word"},
        {".docx", "application/vnd.ms-word"},
        {".xls", "application/vnd.ms-excel"},
        {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
        {".png", "image/png"},
        {".jpg", "image/jpeg"},
        {".jpeg", "image/jpeg"},
        {".gif", "image/gif"},
        {".csv", "text/csv"}
            };
        }
    }
}

推荐阅读
cjavapy编程之路首页