Hi lingers,
Refer below sample.
Appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"MyConn": "Data Source=.\\SQL2022;Initial Catalog=dbFiles;uid=sa;pwd=pass@123;TrustServerCertificate=true"
}
}
Model
public class File
{
[Key]
public int FileId { get; set; }
public string Name { get; set; }
public string Path { get; set; }
}
DBCtx
public class DBCtx : DbContext
{
public DBCtx(DbContextOptions<DBCtx> options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
// Read connection from appsettings.json.
optionsBuilder.UseSqlServer(WebApplication.CreateBuilder().Configuration.GetSection("ConnectionStrings")["MyConn"]);
}
base.OnConfiguring(optionsBuilder);
}
public DbSet<Models.File> Files { get; set; }
}
Program.cs
using Newtonsoft.Json.Serialization;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews()
.AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);
// Register the DBCtx service.
builder.Services.AddDbContext<DBCtx>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Controller
public class HomeController : Controller
{
private DBCtx Context { get; }
private IWebHostEnvironment Environment { get; }
public HomeController(DBCtx _context, IWebHostEnvironment environment)
{
this.Context = _context;
Environment = environment;
}
public IActionResult Index()
{
List<Models.File> files = (from file in this.Context.Files
where file.Path.EndsWith(".pdf")
select file).ToList();
return View(files);
}
public IActionResult ViewFile(string path)
{
string filePath = Uri.UnescapeDataString(Path.Combine(this.Environment.WebRootPath, path)).Replace(@"\", @"/");
byte[] pdfByteArray = System.IO.File.ReadAllBytes(filePath);
string base64EncodedPDF = Convert.ToBase64String(pdfByteArray);
TempData["JavaScriptFunction"] = string.Format("ViewFile('{0}');", base64EncodedPDF);
return View();
}
}
View
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>View File</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf_viewer.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="pdf_container"></div>
<script type="text/javascript">
function ViewFile(pdfByteArray) {
var bytes = Base64ToBytes(pdfByteArray);
LoadPdfFromBlob(bytes);
}
var pdfjsLib = window['pdfjs-dist/build/pdf'];
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.worker.min.js';
var pdfDoc = null;
var scale = 1; //Set Scale for zooming PDF.
var resolution = 1; //Set Resolution to Adjust PDF clarity.
function LoadPdfFromBlob(blob) {
//Read PDF from BLOB.
pdfjsLib.getDocument({ data: blob }).promise.then(function (pdfDoc_) {
pdfDoc = pdfDoc_;
//Reference the Container DIV.
var pdf_container = document.getElementById("pdf_container");
pdf_container.innerHTML = "";
pdf_container.style.display = "block";
//Loop and render all pages.
for (var i = 1; i <= pdfDoc.numPages; i++) {
RenderPage(pdf_container, i);
}
});
};
function RenderPage(pdf_container, num) {
pdfDoc.getPage(num).then(function (page) {
//Create Canvas element and append to the Container DIV.
var canvas = document.createElement('canvas');
canvas.id = 'pdf-' + num;
ctx = canvas.getContext('2d');
pdf_container.appendChild(canvas);
//Create and add empty DIV to add SPACE between pages.
var spacer = document.createElement("div");
spacer.style.height = "20px";
pdf_container.appendChild(spacer);
//Set the Canvas dimensions using ViewPort and Scale.
var viewport = page.getViewport({ scale: scale });
canvas.height = resolution * viewport.height;
canvas.width = resolution * viewport.width;
//Render the PDF page.
var renderContext = {
canvasContext: ctx,
viewport: viewport,
transform: [resolution, 0, 0, resolution, 0, 0]
};
page.render(renderContext);
});
};
function Base64ToBytes(base64) {
var s = window.atob(base64);
var bytes = new Uint8Array(s.length);
for (var i = 0; i < s.length; i++) {
bytes[i] = s.charCodeAt(i);
}
return bytes;
};
</script>
@if (TempData["JavaScriptFunction"] != null)
{
<script type="text/javascript">
@Html.Raw(TempData["JavaScriptFunction"])
</script>
}
</body>
</html>
Screenshot