|
public byte[] GetDocument(string documentID)
{
// Provide the database connection string (Right click in visual Studio -> Properties -> connectionString)
string constr = @"Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = C:\\Users\\XYZ\\Documents\\PdfList.mdf; Integrated Security = True; Connect Timeout = 30";
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(constr);
//Query to get the PDF document from database using the document name.
var query = "select PdfDocData from DocList where PdfDocName = '" + documentID + "'";
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(query);
cmd.Connection = con;
con.Open();
System.Data.SqlClient.SqlDataReader read = cmd.ExecuteReader();
read.Read();
//Retrieve the document data as base64 string
string base64 = (string)read["PdfDocData"];
//Convert base64 string to byte array
byte[] byteArray = Convert.FromBase64String(base64);
return byteArray;
}
|
|
private IMemoryCache _cache;
public PdfViewerController(IHostingEnvironment hostingEnvironment, IMemoryCache cache)
{
_hostingEnvironment = hostingEnvironment;
_cache = cache;
}
public IActionResult Load([FromBody] Dictionary<string, string> jsonObject)
{
PdfRenderer pdfviewer = new PdfRenderer(_cache);
MemoryStream stream = new MemoryStream();
object jsonResult = new object();
if (jsonObject != null && jsonObject.ContainsKey("document"))
{
if (bool.Parse(jsonObject["isFileName"]))
{
//Get the PDF document from Database
byte[] docData = GetDocument(jsonObject["document"]);
stream = new MemoryStream(docData);
}
else
{
byte[] bytes = Convert.FromBase64String(jsonObject["document"]);
stream = new MemoryStream(bytes);
}
}
jsonResult = pdfviewer.Load(stream, jsonObject);
return Content(JsonConvert.SerializeObject(jsonResult));
}
|
|
public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
services.AddMvc().
AddJsonOptions(options =>
{
// JSON serialization not defaulting to default?
options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
});
}
|