ASP.NET MVC 워드 편집기

Aspose.Words for .NET은 다양한 .NET 응용 프로그램 내에서 MS Word 문서를 조작하고 변환하기 위한 완전한 기능 세트를 제공합니다. 특히 데스크톱이나 웹 애플리케이션 내에서 새 문서를 만들거나 기존 Word 문서를 편집할 수 있습니다. 이 게시물에서는 .NET용 Aspose.Words의 워드 프로세싱 기능을 활용하고 ASP.NET MVC에서 웹 기반 MS Word 편집기를 만드는 방법을 보여 드리겠습니다.

ASP.NET MVC Word 편집기 - Word 문서 만들기

문서의 내용을 작성하고 업데이트하기 위해 WYSIWYG HTML 편집기를 기반으로 하는 ASP.NET MVC Word Editor를 만들 것입니다. 또한 Aspose.Words for .NET은 업데이트된 콘텐츠에서 Word 문서를 편집하고 생성하기 위해 Word 문서의 콘텐츠를 HTML로 렌더링하는 데 사용됩니다.

ASP.NET MVC에서 MS Word 편집기를 만드는 단계

데모를 위해 이 응용 프로그램에서 JavaScript 기반 Suneditor WYSIWYG 편집기를 사용했습니다. 동일한 것을 사용하거나 요구 사항에 맞는 다른 HTML 편집기를 선택할 수 있습니다. 다음은 ASP.NET Word Editor를 만드는 단계입니다.

  • 먼저 Visual Studio에서 새 ASP.NET Core 웹 응용 프로그램을 만듭니다.
  • 웹 애플리케이션(Model-View-Controller) 템플릿을 선택합니다.
  • WYSIWYG 편집기의 파일을 다운로드하여 wwwroot 디렉토리에 보관하십시오.
  • NuGet 패키지 관리자를 열고 .NET용 Aspose.Words 패키지를 설치합니다.
  • 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>
  • HomeController.cs 컨트롤러에 다음 메서드를 추가합니다.
[HttpPost]
public FileResult Index(string editor)
{
	try
	{
		// 고유한 파일 이름 만들기
		string fileName = Guid.NewGuid() + ".docx";
		// HTML 텍스트를 바이트 배열로 변환
		byte[] byteArray = Encoding.UTF8.GetBytes(editor.Contains("<html>") ? editor : "<html>" + editor + "</html>");
		// HTML에서 Word 문서 생성
		MemoryStream stream = new MemoryStream(byteArray);
		Document Document = new Document(stream);
		// Word 파일에 대한 메모리 스트림 생성
		var outputStream = new MemoryStream();
		Document.Save(outputStream, SaveFormat.Docx);
		outputStream.Position = 0;
		// 생성된 Word 파일 반환
		return File(outputStream, System.Net.Mime.MediaTypeNames.Application.Rtf, fileName);
	}
	catch (Exception exp)
	{
		return null;
	}
}
[HttpPost]
public ViewResult UploadFile(IFormFile file)
{
	// 파일 경로 설정
	var path = Path.Combine("wwwroot/uploads", file.FileName);
	using (var stream = new FileStream(path, FileMode.Create))
	{
		file.CopyTo(stream);
	}
	// Word 문서 로드
	Document doc = new Document(path);
	var outStream = new MemoryStream();
	// HTML 옵션 설정
	HtmlSaveOptions opt = new HtmlSaveOptions();
	opt.ExportImagesAsBase64 = true;
	opt.ExportFontsAsBase64 = true; 
	// Word 문서를 HTML로 변환
	doc.Save(outStream, opt);
	// 스트림에서 텍스트 읽기
	outStream.Position = 0;
	using(StreamReader reader = new StreamReader(outStream))
	{
		ViewBag.HtmlContent = reader.ReadToEnd();
	}
	return View("Index");
}
  • 마지막으로 즐겨 사용하는 브라우저에서 애플리케이션을 빌드하고 실행합니다.

데모

다음은 ASP.NET Word Editor에서 Word 문서를 만들거나 편집하는 방법에 대한 데모입니다.

ASP.NET에서 Word 문서 만들기

ASP.NET에서 Word 문서 편집

소스 코드 다운로드

MS Word Editor의 소스 코드는 여기에서 다운로드할 수 있습니다.

결론

이 기사에서는 ASP.NET에서 MS Word 문서를 만드는 방법을 배웠습니다. 코드 샘플과 함께 단계별 가이드는 ASP.NET MVC에서 간단한 웹 기반 MS Word 편집기를 만드는 방법을 보여주었습니다. 이와 함께 다음 리소스를 사용하여 .NET용 Aspose.Words에 대해 자세히 알아볼 수 있습니다.

무료로 .NET용 Aspose.Words 사용해 보기

임시 라이선스를 요청하여 .NET용 Aspose.Words를 무료로 사용해 볼 수 있습니다.

관련 기사