Trình xem tài liệu trực tuyến đã trở nên phổ biến sau khi việc sử dụng tài liệu kỹ thuật số ngày càng tăng, đặc biệt là trong các hệ thống quản lý nội dung. Lý do đằng sau sự phổ biến này là bạn có thể xem nhiều định dạng tài liệu mà không cần mua hoặc cài đặt các chương trình phần mềm chuyên dụng. Xem xét tầm quan trọng của trình xem tài liệu, tôi nghĩ sẽ viết một bài viết về cách tạo trình xem tài liệu chung trong ASP.NET MVC.

Chúng tôi sẽ tạo một ứng dụng xem tài liệu ASP.NET MVC sẽ nhắm mục tiêu [.NET Core](https://en.wikipedia. org/wiki/.NETCore). Để hiển thị tài liệu ở phần phụ trợ, chúng tôi sẽ sử dụng API GroupDocs.Viewer for .NET - API trình xem tài liệu mạnh mẽ hỗ trợ hơn 140 loại tài liệu bao gồm cả PDF , Word, Excel, PowerPoint, Visio, CAD, Outlook và nhiều định dạng phổ biến khác.

Tại sao lại là .NET Core?

.NET Core là một bổ sung có giá trị cho hệ sinh thái .NET của Microsoft. Nó cho phép phát triển các ứng dụng đa nền tảng mà không cần bất kỳ nỗ lực bổ sung nào theo yêu cầu của các nhà phát triển. Đây là lý do tại sao tôi đã chọn .NET Core làm khung được nhắm mục tiêu.

Các bước để tạo Trình xem tài liệu trong ASP.NET Core

  1. Mở Visual Studio và bắt đầu một dự án mới.

  2. Chọn .NET Core từ các loại dự án và Ứng dụng web ASP.NET Core từ các mẫu.

  1. Chọn Ứng dụng web (Model-View-Controller) và nhấp vào nút Ok.
  1. Cài đặt GroupDocs.Viewer từ NuGet.
  1. Mở tệp Views/Home/Index.cshtml và thay thế nội dung của nó bằng nội dung sau:
@{
    ViewData["Title"] = "Home Page";
}
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script>
    function ViewDocument(file) {
        $("#loader").fadeIn();
        var data = { FileName: file };
        $.ajax({
            type: "POST",
            url: '/Home/OnPost',
            data: data,
            dataType: "text"
        }).done(function (data) {
            var folderName = file.replace(".", "_");
            $("#content").empty();
            for (var i = 1; i <= data; i++) {
                $("#content").append("<img src='Content/" + folderName + "/page-" + i + ".png'/>");
            }
            $("#loader").fadeOut();
        })
    }
</script>
<script type="text/javascript">
    $(window).load(function() {
        $("#loader").fadeOut(1000);
    });
</script>
<div class="row">
    <div class="col-md-3">
        <div class="sidenav">
            <div id="loader"></div>
            <h2 style="padding-left:15px">Files</h2>
            @if (ViewBag.lstFiles != null)
            {
                @foreach (string file in ViewBag.lstFiles)
                {
                    <a href="#" onclick="ViewDocument('@file')">@file</a>
                }
            }
        </div>
    </div>
    <div class="col-md-9">
        <h2>Preview</h2>
        <div id="content"></div>
    </div>
</div>
  1. Mở Controllers/HomeController.cs và thay thế nội dung của lớp bằng đoạn mã sau.
public class HomeController : Controller
{
	private readonly IHostingEnvironment _hostingEnvironment;
	private string projectRootPath;
	private string outputPath;
	private string storagePath;
	List<string> lstFiles; 

	public HomeController(IHostingEnvironment hostingEnvironment)
	{
		_hostingEnvironment = hostingEnvironment;
		projectRootPath = _hostingEnvironment.ContentRootPath;
		outputPath = Path.Combine(projectRootPath, "wwwroot/Content");
		storagePath = Path.Combine(projectRootPath, "storage");
		lstFiles = new List<string>(); 
	}

	public IActionResult Index()
	{
		var files = Directory.GetFiles(storagePath);
		foreach (var file in files)
		{
			lstFiles.Add(Path.GetFileName(file));
		}
		ViewBag.lstFiles = lstFiles; 
		return View();
	}
	[HttpPost]
	public IActionResult OnPost(string FileName)
	{
		int pageCount = 0;
		string imageFilesFolder = Path.Combine(outputPath, Path.GetFileName(FileName).Replace(".", "_"));
		if (!Directory.Exists(imageFilesFolder))
		{
			Directory.CreateDirectory(imageFilesFolder);
		}
		string imageFilesPath = Path.Combine(imageFilesFolder, "page-{0}.png");
		using (Viewer viewer = new Viewer(Path.Combine(storagePath, FileName)))
		{
      //Nhận thông tin tài liệu
			ViewInfo info = viewer.GetViewInfo(ViewInfoOptions.ForPngView(false));
			pageCount = info.Pages.Count;
      //Đặt tùy chọn và hiển thị tài liệu
			PngViewOptions options = new PngViewOptions(imageFilesPath);
			viewer.View(options);
		} 
		return new JsonResult(pageCount);
	} 

	[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
	public IActionResult Error()
	{
		return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
	}
}
  1. Nối các kiểu sau vào tệp wwwroot/css/site.css.
.sidenav {
    width: 300px;
    position: fixed;
    z-index: 1;
    left: 0px;
    background: #eee;
    overflow-x: hidden;
    padding: 8px 0;
}
.sidenav a {
    padding: 6px 8px 6px 16px;
    text-decoration: none;
    font-size: 15px;
    color: #2196F3;
    display: block;
}
.sidenav a:hover {
        color: #064579;
    }
.main {
    margin-left: 140px; /* Same width as the sidebar + left position in px */
    font-size: 15px; /* Increased text to enable scrolling */
    padding: 0px 10px;
}
@media screen and (max-height: 450px) {
    .sidenav {
        padding-top: 15px;
    }
        .sidenav a {
            font-size: 20px;
        }
}
#loader {
    position: fixed;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
    z-index: 9999;
    background: url('../../images/Loading.gif') 50% 50% no-repeat rgb(249,249,249);
}
  1. Xây dựng ứng dụng xem tài liệu và chạy trên trình duyệt yêu thích của bạn.
Trình xem tệp ASP.NET Core

Tải xuống Trình xem tài liệu ASP.NET MVC

Mã nguồn của trình xem tài liệu ASP.NET MVC là mã nguồn mở và có sẵn để tải xuống.