Generating PDf /Excel files using .Net without any third party pdf generators.

Praveen Sambu
2 min readJul 15, 2020

--

I have successfully generated pdf files and got them downloaded on browser.

I am using an MVC application to do this, I was struggling a lot to get pdf file downloaded and was returning errors in ajax calls. And here is how I resolved them.

When you use the Ajax call in ASP.NET MVC, you can just return a JSON object but not a file. If you want to do that, you need to create and save the file in server and return its path to Ajax.

The following controller code will allow to download the created file from a single ajax call

public async Task<JsonResult> CardStatusReportExport(ReportFilterInputModel cardStatusReportInputModel, string type, string sortOrder)
{
cardStatusReportInputModel.ReportType = Reprot_Type_Const.CardStatus;
cardStatusReportInputModel.ReportFormat = type;

var CardStatusReport = await _reportDocGeneration.DocGeneartion(cardStatusReportInputModel);
string result = Path.GetTempPath();
string fileName = "CardStatusReport" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
if (type.Equals(Constants.FILE_TYPE_PDF))
{
fileName = fileName + Constants.FILE_EXTENSION_PDF;
System.IO.File.WriteAllBytes(result + fileName, CardStatusReport);
}
else
{
fileName = fileName + Constants.FILE_EXTENSION_EXCEL;
System.IO.File.WriteAllBytes(result + fileName, CardStatusReport);
}
return Json(new { fileName = fileName});
}

And Here is the Http call

[HttpGet]    
public async Task<ActionResult> Download(string file)
{
var path = Path.Combine(Path.GetTempPath(),file);
var memory = new MemoryStream();
try
{
using (var stream = new FileStream(path, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
}
catch (Exception e)
{
ModelState.AddModelError("FileNotFoundError", e.Message);
return Content(e.Message);
}
memory.Position = 0;
return File(memory, GetContentType(path), Path.GetFileName(path));
}

private string GetContentType(string path)
{
var types = MediaType.GetMimeTypes();
var ext = Path.GetExtension(path).ToLowerInvariant();
return types[ext];
}

GetContentType for pdf is "application/pdf"

Ajax Call

$('#print').click(function ()
{
$.ajax({
method: 'POST',
data: { type: val, cardStatusReportInputModel: payload, sortOrder : sortOrder},
url: '@Url.Action("CardStatusReportExport", "Reports")'
}).done(function (data, statusText, xhdr) {
try {
if (data.fileName != "") {
window.location.href = "@Url.RouteUrl(new { Controller = "Reports", Action = "Download"})/?file=" + data.fileName;
ShowMessageAlert('@Html.Raw(Localizer["Report has been exported successfully"].Value.ToString())');
}
$("#divLoader").hide();
}
catch (e) {
$("#divLoader").hide();
}
}).fail(function (xhdr, statusText, errorText) {
alert('error');
$("#divLoader").hide();
});
});

When you have an hyper link or a button your click event needs to call the above ajax method.

Hope fully this would get you a pdf straight forward.

--

--

Praveen Sambu
Praveen Sambu

Written by Praveen Sambu

Software Engineer |AWS Community Builder |Technical Blogger | Trainer . Founder of Cloud In Detail (https://cloudindetail.com/) still working on building blog…

Responses (1)