Trình soạn thảo văn bản ASP.NET MVC

Aspose.Words for .NET cung cấp một bộ tính năng hoàn chỉnh để thao tác và chuyển đổi tài liệu MS Word trong vô số ứng dụng .NET. Đặc biệt, bạn có thể tạo mới hoặc chỉnh sửa các tài liệu Word hiện có trong máy tính để bàn hoặc ứng dụng web. Trong bài đăng này, tôi sẽ chỉ cho bạn cách tận dụng khả năng xử lý Word của Aspose.Words for .NET và tạo một Trình soạn thảo MS Word dựa trên web trong ASP.NET MVC.

ASP.NET MVC Word Editor - Tạo tài liệu Word

Chúng ta sẽ tạo một ASP.NET MVC Word Editor dựa trên trình soạn thảo WYSIWYG HTML để viết và cập nhật nội dung của tài liệu. Hơn nữa, Aspose.Words for .NET sẽ được sử dụng để hiển thị nội dung của tài liệu Word thành HTML để chỉnh sửa và tạo tài liệu Word từ nội dung được cập nhật.

Các bước để tạo MS Word Editor trong ASP.NET MVC

Để trình diễn, tôi đã sử dụng trình soạn thảo WYSIWYG Suneditor dựa trên JavaScript trong ứng dụng này. Bạn có thể sử dụng cùng một trình soạn thảo HTML hoặc chọn bất kỳ trình soạn thảo HTML nào khác phù hợp với yêu cầu của mình. Sau đây là các bước để tạo ASP.NET Word Editor.

  • Đầu tiên, tạo một Ứng dụng web ASP.NET Core mới trong Visual Studio.
  • Chọn mẫu Ứng dụng web (Model-View-Controller).
  • Tải xuống các tệp của trình soạn thảo WYSIWYG và giữ chúng trong thư mục wwwroot.
  • Mở Trình quản lý gói NuGet và cài đặt gói Aspose.Words for .NET.
  • Thêm tập lệnh sau vào chế độ xem index.cshtml.
@{
    ViewData["Title"] = "Word Editor in ASP.NET";
}
<div class="row">
    <div class="col-md-12">
        <form asp-controller="Home" asp-action="UploadFile" method="post" class="form-inline"
              enctype="multipart/form-data">
            <br />
            <div class="form-group">
                <input type="file" name="file" accept=".doc, .docx" class="form-control custom-file-input" />
            </div>
            <div class="form-group">
                <button type="submit" class="form-control btn btn-primary">Open</button>
            </div>
            <div class="form-group" style="position:relative; float :right">
                <button type="button" id="download" class="form-control btn btn-success" value="Save and Download">Save and Download</button>
            </div>
        </form>
        <br />
        <form method="post" asp-action="Index" id="formDownload">
            <textarea name="editor" id="editor" rows="80" cols="100">
                @if (ViewBag.HtmlContent == null)
                 {
                    <p>Write something or open an existing Word document. </p>
                 }
                 else
                 {
                     @ViewBag.HtmlContent;
                 }
                </textarea>
        </form>
    </div>
</div>
<!-- suneditor -->
<link href="~/suneditor/dist/css/suneditor.min.css" rel="stylesheet">
<!-- suneditor -->
<script src="~/suneditor/dist/suneditor.min.js"></script>
<script>
    var suneditor = SUNEDITOR.create('editor', {
        display: 'block',
        width: '100%',
        height: '30%',
        popupDisplay: 'full',
        buttonList: [
            ['font', 'fontSize', 'formatBlock'],
            ['paragraphStyle', 'blockquote'],
            ['bold', 'underline', 'align', 'strike', 'subscript', 'superscript', 'horizontalRule', 'list'],
            ['table', 'link', 'image'],
            ['align', 'horizontalRule', 'list', 'lineHeight'],
            ['codeView']
        ],
        placeholder: 'Start typing something...'
    });
</script>
<script>
    $(document).ready(function() {
        $("#download").click(function() {
            suneditor.save();
            $("#formDownload").submit();
        });
    });
</script>
  • Thêm các phương thức sau vào bộ điều khiển HomeController.cs.
[HttpPost]
public FileResult Index(string editor)
{
	try
	{
		// Tạo một tên tệp duy nhất
		string fileName = Guid.NewGuid() + ".docx";
		// Chuyển đổi văn bản HTML thành mảng byte
		byte[] byteArray = Encoding.UTF8.GetBytes(editor.Contains("<html>") ? editor : "<html>" + editor + "</html>");
		// Tạo tài liệu Word từ HTML
		MemoryStream stream = new MemoryStream(byteArray);
		Document Document = new Document(stream);
		// Tạo dòng bộ nhớ cho file Word
		var outputStream = new MemoryStream();
		Document.Save(outputStream, SaveFormat.Docx);
		outputStream.Position = 0;
		// Trả lại tệp Word đã tạo
		return File(outputStream, System.Net.Mime.MediaTypeNames.Application.Rtf, fileName);
	}
	catch (Exception exp)
	{
		return null;
	}
}
[HttpPost]
public ViewResult UploadFile(IFormFile file)
{
	// Đặt đường dẫn tệp
	var path = Path.Combine("wwwroot/uploads", file.FileName);
	using (var stream = new FileStream(path, FileMode.Create))
	{
		file.CopyTo(stream);
	}
	// Tải tài liệu Word
	Document doc = new Document(path);
	var outStream = new MemoryStream();
	// Đặt tùy chọn HTML
	HtmlSaveOptions opt = new HtmlSaveOptions();
	opt.ExportImagesAsBase64 = true;
	opt.ExportFontsAsBase64 = true; 
	// Chuyển đổi tài liệu Word sang HTML
	doc.Save(outStream, opt);
	// Đọc văn bản từ dòng
	outStream.Position = 0;
	using(StreamReader reader = new StreamReader(outStream))
	{
		ViewBag.HtmlContent = reader.ReadToEnd();
	}
	return View("Index");
}
  • Cuối cùng, xây dựng và chạy ứng dụng trong trình duyệt yêu thích của bạn.

Thử nghiệm

Sau đây là minh họa cách tạo hoặc chỉnh sửa tài liệu Word trong ASP.NET Word Editor.

Tạo một tài liệu Word trong ASP.NET

Chỉnh sửa tài liệu Word trong ASP.NET

Tải xuống mã nguồn

Bạn có thể tải về mã nguồn của MS Word Editor từ tại đây.

Sự kết luận

Trong bài này, bạn đã học cách tạo tài liệu MS Word trong ASP.NET. Hướng dẫn từng bước cùng với các mẫu mã đã chỉ ra cách tạo trình soạn thảo MS Word dựa trên web đơn giản trong ASP.NET MVC. Ngoài ra, bạn có thể khám phá thêm về Aspose.Words for .NET bằng cách sử dụng các tài nguyên sau.

Dùng thử miễn phí Aspose.Words for .NET

Bạn có thể dùng thử miễn phí Aspose.Words for .NET bằng cách yêu cầu giấy phép tạm thời.

Những bài viết liên quan