Przeglądarki dokumentów online stały się popularne po wzroście wykorzystania dokumentów cyfrowych, zwłaszcza w systemach zarządzania treścią. Powodem tej popularności jest możliwość przeglądania różnych formatów dokumentów bez kupowania lub instalowania dedykowanego oprogramowania. Biorąc pod uwagę znaczenie przeglądarek dokumentów, pomyślałem o napisaniu artykułu o tym, jak stworzyć uniwersalną przeglądarkę dokumentów w ASP.NET MVC.

Zamierzamy utworzyć aplikację przeglądarki dokumentów ASP.NET MVC, która będzie kierowana na platformę .NET Core. Do renderowania dokumentów na zapleczu użyjemy GroupDocs.Viewer for .NET API - potężnego interfejsu API przeglądarki dokumentów, który obsługuje ponad 140 typów dokumentów, w tym PDF, Word, Excel, PowerPoint, Visio, CAD, Outlook i wiele innych popularnych formatów.

Dlaczego .NET Core?

.NET Core to cenny dodatek do ekosystemu .NET firmy Microsoft. Umożliwia tworzenie aplikacji wieloplatformowych bez dodatkowych wysiłków ze strony programistów. Właśnie dlatego wybrałem platformę .NET Core jako platformę docelową.

Kroki tworzenia przeglądarki dokumentów w ASP.NET Core

  1. Otwórz Visual Studio i rozpocznij nowy projekt.

  2. Wybierz .NET Core z typów projektów i ASP.NET Core Web Application z szablonów.

  1. Wybierz aplikację internetową (Model-View-Controller) i kliknij przycisk OK.
  1. Zainstaluj GroupDocs.Viewer z NuGet.
  1. Otwórz plik Views/Home/Index.cshtml i zamień jego zawartość na następującą:
@{
    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. Otwórz Controllers/HomeController.cs i zastąp zawartość klasy następującym kodem.
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)))
		{
      //Uzyskaj informacje o dokumencie
			ViewInfo info = viewer.GetViewInfo(ViewInfoOptions.ForPngView(false));
			pageCount = info.Pages.Count;
      //Ustaw opcje i wyrenderuj dokument
			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. Dołącz następujące style w pliku 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. Zbuduj aplikację do przeglądania dokumentów i uruchom ją w swojej ulubionej przeglądarce.
Przeglądarka plików ASP.NET Core

Pobierz przeglądarkę dokumentów ASP.NET MVC

Kod źródłowy przeglądarki dokumentów ASP.NET MVC jest open source i jest dostępny do pobrania.