צופי המסמכים המקוונים הפכו פופולריים לאחר השימוש הגדל במסמכים דיגיטליים, במיוחד במערכות ניהול התוכן. הסיבה מאחורי הפופולריות הזו היא שאתה יכול להציג מגוון פורמטים של מסמכים מבלי לרכוש או להתקין תוכנות ייעודיות. בהתחשב בחשיבותם של צופים במסמכים, חשבתי לכתוב מאמר על איך ליצור מציג מסמכים אוניברסלי ב-ASP.NET MVC.

אנו עומדים ליצור יישום מציג מסמכים ASP.NET MVC שיכוון למסגרת .NET Core. עבור עיבוד המסמכים בקצה העורפי, נשתמש ב-GroupDocs.Viewer for .NET API - ממשק API רב עוצמה של מציג מסמכים התומך ביותר מ-140 סוגי מסמכים כולל PDF, Word, Excel, PowerPoint, Visio, CAD, Outlook , ופורמטים פופולריים רבים אחרים.

למה .NET Core?

NET Core היא תוספת חשובה למערכת האקולוגית של .NET של מיקרוסופט. היא מאפשרת לפתח אפליקציות חוצות פלטפורמות ללא כל מאמצים נוספים הנדרשים על ידי המפתחים. זו הסיבה שבחרתי ב-.NET Core להיות המסגרת הממוקדת.

שלבים ליצירת מציג מסמכים ב-ASP.NET Core

  1. פתח את Visual Studio והתחל פרויקט חדש.

  2. בחר .NET Core מבין סוגי הפרויקטים ו-ASP.NET Core Web Application מתוך תבניות.

  1. בחר יישום אינטרנט (Model-View-Controller) ולחץ על כפתור OK.
  1. התקן את GroupDocs.Viewer מ-NuGet.
  1. פתח את קובץ Views/Home/Index.cshtml והחלף את התוכן שלו בקובץ הבא:
@{
    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. פתחו את Controllers/HomeController.cs והחליפו את תוכן המחלקה בקוד הבא.
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)))
		{
      //קבל מידע על מסמך
			ViewInfo info = viewer.GetViewInfo(ViewInfoOptions.ForPngView(false));
			pageCount = info.Pages.Count;
      //הגדר אפשרויות ועיבוד מסמך
			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. הוסף את הסגנונות הבאים לקובץ 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. בנה את אפליקציית מציג המסמכים והפעל בדפדפן המועדף עליך.
מציג קבצי ליבה של ASP.NET

הורד את ASP.NET MVC Document Viewer

קוד המקור של מציג המסמכים של ASP.NET MVC הוא קוד פתוח וזמין עבור הורדה.