Çevrimiçi belge görüntüleyiciler, özellikle içerik yönetim sistemlerinde dijital belgelerin artan kullanımından sonra popüler hale geldi. Bu popülerliğin arkasındaki sebep, özel yazılım programları satın almadan veya kurmadan çeşitli belge formatlarını görüntüleyebilmenizdir. Belge görüntüleyicilerin önemini göz önünde bulundurarak, ASP.NET MVC’de evrensel bir belge görüntüleyicinin nasıl oluşturulacağı hakkında bir makale yazmayı düşündüm.

[.NET Çekirdeği](https://en.wikipedia. org/wiki/.NETCore) çerçevesi. Arka uçta belge işleme için, PDF dahil 140’tan fazla belge türünü destekleyen güçlü bir belge görüntüleyici API’si olan GroupDocs.Viewer for .NET API’sini kullanacağız. , Word, Excel, PowerPoint, Visio, CAD, Outlook ve diğer birçok popüler biçim.

Neden .NET Çekirdeği?

.NET Core, Microsoft tarafından .NET ekosistemine eklenen değerli bir eklentidir. Geliştiricilerin ihtiyaç duyduğu herhangi bir ek çaba olmadan platformlar arası uygulamalar geliştirmeyi mümkün kılar. Bu nedenle, hedeflenen çerçeve olarak .NET Core’u seçtim.

ASP.NET Core’da Belge Görüntüleyici Oluşturma Adımları

  1. Visual Studio’yu açın ve yeni bir proje başlatın.

  2. Proje türlerinden .NET Core’u ve şablonlardan ASP.NET Core Web Uygulamasını seçin.

  1. Web Uygulaması’nı (Model-View-Controller) seçin ve Tamam düğmesini tıklayın.
  1. GroupDocs.Viewer’ı NuGet’ten yükleyin.
  1. Views/Home/Index.cshtml dosyasını açın ve içeriğini aşağıdakiyle değiştirin:
@{
    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 dosyasını açın ve sınıfın içeriğini aşağıdaki kodla değiştirin.
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)))
		{
      //Belge bilgilerini al
			ViewInfo info = viewer.GetViewInfo(ViewInfoOptions.ForPngView(false));
			pageCount = info.Pages.Count;
      //Seçenekleri ayarlayın ve belgeyi oluşturun
			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. Aşağıdaki stilleri wwwroot/css/site.css dosyasına ekleyin.
.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. Belge görüntüleyici uygulamasını oluşturun ve favori tarayıcınızda çalıştırın.
ASP.NET Çekirdek Dosya Görüntüleyicisi

ASP.NET MVC Document Viewer’ı İndirin

ASP.NET MVC belge görüntüleyicisinin kaynak kodu açık kaynaktır ve indirilebilir.