Create and Render PDF through Webapi controller and manage it with Angular JS

2

(In order to Enlarge images Please Right Click and Open images in New Tab)

Let us see how to how to Create and Render PDF through Webapi controller and manage it with Angular JS.

if any error occurs how to manage it Let us  see

1)In controller.js

xx1

xx2

2)service.js

Remember ,

responseType: ‘arraybuffer’

for pdf or byte array rendering

xx3

3)WEBAPI controler

xx4

1

1)In controller.js

$scope.print = function () {

var promisePost = reportService.PrintInterfaceTasks();
promisePost.then(function (response) {
$scope.flag = “”;
var pdfData = response;
var str = arrayBufferTostr(response);
if (str.indexOf(‘@’) == -1 || str.indexOf(‘#’) == -1 || str.indexOf(‘$’) == -1 || str.indexOf(‘%’) == -1 || str.indexOf(‘^’) == -1 || str.indexOf(‘&’) == -1 || str.indexOf(‘*’) == -1 || str.indexOf(‘(‘) == -1 || str.indexOf(‘)’) == -1 || str.indexOf(‘_’) == -1 || str.indexOf(‘\”) == -1 || str.indexOf(‘\”‘) == -1 || str.indexOf(‘\\’) == -1 || str.indexOf(‘|’) == -1 || str.indexOf(‘?’) == -1 || str.indexOf(‘/’) == -1 || str.indexOf(‘:’) == -1 || str.indexOf(‘;’) == -1 || str.indexOf(‘!’) == -1 || str.indexOf(‘~’) == -1 || str.indexOf(‘`’) == -1 || str.indexOf(‘,’) == -1 || str.indexOf(‘<‘) == -1 || str.indexOf(‘>’) == -1 || str.indexOf(‘{‘) == -1 || str.indexOf(‘}’) == -1 || str.indexOf(‘[‘) == -1 || str.indexOf(‘]’) == -1 || str.indexOf(‘+’) == -1 || str.indexOf(‘=’) == -1) {
$scope.flag = “”;
}
else {
$scope.flag = “Invalid”;
}
if ($scope.flag == “”) {
$scope.reportMessage(str);
}
else {
var ieEDGE = navigator.userAgent.match(/Edge/g);
var ie = navigator.userAgent.match(/.NET/g); // IE 11+
var oldIE = navigator.userAgent.match(/MSIE/g);
var name = “InterfaceListReport”;
var blob = new window.Blob([response], { type: ‘application/pdf’ });
if (ie || oldIE || ieEDGE) {
var fileName = name + ‘.pdf’;
window.navigator.msSaveBlob(blob, fileName);
}
else {
var file = new Blob([response], { type: ‘application/pdf’ });
var fileURL = URL.createObjectURL(file);
var a = document.createElement(‘a’);
a.href = fileURL;
a.target = ‘_blank’;
a.download = name + ‘.pdf’;
document.body.appendChild(a);
a.click();
}
}
}, function (err) {
});
}

function arrayBufferTostr(buf) {
var binaryString = ”,
bytes = new Uint8Array(buf),
length = bytes.length;
for (var i = 0; i < length; i++) {
binaryString += String.fromCharCode(bytes[i]);
}
return binaryString;
}

2)service.js

reportService.Print = function () {
var def = $q.defer();
var request = $http({
url: apiConstants.API_URL + “api/Reports/Print” ,
dataType: ‘json’,
method: ‘POST’,
responseType: ‘arraybuffer’
}).success(function (data, status, headers, config) {
if (data !== null) {
def.resolve(data);
}
}).error(function (response, status, headers, config) {
});
return def.promise;
}

3)WEBAPI controler

[HttpPost]
[Route(“Print”)]
public HttpResponseMessage Print()
{
HttpResponseMessage resp;
byte[] getBytes = null;
string strResponse = string.Empty;
ReportDTO Reportlist = new ReportDTO();
ReportService reportService = new ReportService();
Reportlist = reportService.GetReport();
if (Reportlist .Error != null)
{
strResponse = Reportlist.Error.Message;
}
else
{
CrystalDecisions.CrystalReports.Engine.ReportDocument rpt = CrystalReportsHelper.CreateReport (System.Web.Hosting.HostingEnvironment.MapPath(@”~/Reports/Crystal/Report.rpt”));
rpt.SetDataSource(Reportlist);
System.IO.MemoryStream ms = (MemoryStream)rpt.ExportToStrem(ExportFormatType.PortableDocFormat);
getBytes = ms.ToArray();
}
if (!String.IsNullOrEmpty(strResponse))
{
resp = Request.CreateResponse(HttpStatusCode.OK, strResponse);
resp.Content.Headers.ContentType = new MediaTypeHeaderValue(“text/plain”);
resp.Content = new StringContent(strResponse);
}
else
{
resp = Request.CreateResponse(HttpStatusCode.OK, strResponse);
resp.Content = new ByteArrayContent(getBytes);
resp.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderVaue(“attachment”);
resp.Content.Headers.ContentDisposition.FileName = “filename” + “.pdf”;
}

return resp;
}

For EXCEL .xls format

Controller.js and   Service.js It is as it’s like above

 

$scope.downloadTemplate = function () {
var userData = authentication.getUser();
var userDTO = {
UserId: userData.UserId,
SelectedOrganizationId: userData.SelectedOrganizationId,
FacilityLocationId: 0,
};
var file = “ChargeEntryTemplate.xls”;

var promisePost = reportService.DownloadTemplate(JSON.stringify(userDTO), JSON.stringify(file));
promisePost.then(function (response) {
$scope.flag = “”;
var pdfData = response;
var str = arrayBufferTostr(response);
if (str.indexOf(‘@’) == -1 || str.indexOf(‘#’) == -1 || str.indexOf(‘$’) == -1 || str.indexOf(‘%’) == -1 || str.indexOf(‘^’) == -1 || str.indexOf(‘&’) == -1 || str.indexOf(‘*’) == -1 || str.indexOf(‘(‘) == -1 || str.indexOf(‘)’) == -1 || str.indexOf(‘_’) == -1 || str.indexOf(‘\”) == -1 || str.indexOf(‘\”‘) == -1 || str.indexOf(‘\\’) == -1 || str.indexOf(‘|’) == -1 || str.indexOf(‘?’) == -1 || str.indexOf(‘/’) == -1 || str.indexOf(‘:’) == -1 || str.indexOf(‘;’) == -1 || str.indexOf(‘!’) == -1 || str.indexOf(‘~’) == -1 || str.indexOf(‘`’) == -1 || str.indexOf(‘,’) == -1 || str.indexOf(‘<‘) == -1 || str.indexOf(‘>’) == -1 || str.indexOf(‘{‘) == -1 || str.indexOf(‘}’) == -1 || str.indexOf(‘[‘) == -1 || str.indexOf(‘]’) == -1 || str.indexOf(‘+’) == -1 || str.indexOf(‘=’) == -1) {
$scope.flag = “”;
}
else {
$scope.flag = “Invalid”;
}

if (str.indexOf(‘PDF’) != -1) {
$scope.flag = “Invalid”;
}

if ($scope.flag == “”) {
$scope.reportMessage(str);
}
else {
var ieEDGE = navigator.userAgent.match(/Edge/g);
var ie = navigator.userAgent.match(/.NET/g); // IE 11+
var oldIE = navigator.userAgent.match(/MSIE/g);
var name = “ChargeEntryTemplate”;
var blob = new window.Blob([response], {
type: ‘application/octet-stream
});
if (ie || oldIE || ieEDGE) {
var fileName = name + ‘.pdf’;
window.navigator.msSaveBlob(blob, fileName);
}
else {
var file = new Blob([response], {
type: ‘application/octet-stream’
});
var fileURL = URL.createObjectURL(file);
var a = document.createElement(‘a’);
a.href = fileURL;
a.target = ‘_blank’;
a.download = name + ‘.xls’;
document.body.appendChild(a);
a.click();
}
}
});
}

WebAPI Controller=>

[HttpPost, MultiParamPost]
[Route(“DownloadTemplate”)]
public HttpResponseMessage DownloadTemplate(string userData, string file)
{
HttpResponseMessage resp;
byte[] getBytes = null;
string strResponse = string.Empty;
resp = Request.CreateResponse(HttpStatusCode.OK);

string downloadFile = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(file);

if (downloadFile == “ChargeEntryTemplate.xls”)
{

Application oExcel = null;
oExcel = new Application();
if (oExcel == null)

strResponse = “Excel component missing, can not process this file.”;

oExcel.Application.DisplayAlerts = false;
string fpath = System.Web.Hosting.HostingEnvironment.MapPath(@”~/Charges/ChargeEntryTemplate.xls”);
Workbook oWorkBook = oExcel.Workbooks.Open(fpath, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing);
Worksheet oWorkSheet = oWorkBook.Worksheets.get_Item(1);
oWorkSheet.Unprotect(“global”);
Range oRange = oWorkSheet.UsedRange;
string headerBillProvider = (oRange.Cells[1, 11] as Range).Value.ToString();
string headerBillLastName = (oRange.Cells[1, 12] as Range).Value.ToString();
string headerBillFirstName = (oRange.Cells[1, 13] as Range).Value.ToString();
headerBillProvider = headerBillProvider.Replace(“Billing”, chargeOption.OptionValueString.Trim());
headerBillLastName = headerBillLastName.Replace(“Billing”, chargeOption.OptionValueString.Trim());
headerBillFirstName = headerBillFirstName.Replace(“Billing”, chargeOption.OptionValueString.Trim());
(oRange.Cells[1, 11] as Range).Value = headerBillProvider;
(oRange.Cells[1, 12] as Range).Value = headerBillLastName;
(oRange.Cells[1, 13] as Range).Value = headerBillFirstName;

string fpath = System.Web.Hosting.HostingEnvironment.MapPath(@”~/Charges/ChargeEntryTemplate.xls”);
getBytes = File.ReadAllBytes(fpath);
}
}

}
if (!String.IsNullOrEmpty(strResponse))
{
resp = Request.CreateResponse<string>(HttpStatusCode.OK, strResponse);
resp.Content.Headers.ContentType = new MediaTypeHeaderValue(“text/plain”);
resp.Content = new StringContent(strResponse);
}
else
{
resp = Request.CreateResponse<string>(HttpStatusCode.OK, strResponse);
resp.Content = new ByteArrayContent(getBytes);
resp.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue(“attachment”);
resp.Content.Headers.ContentDisposition.FileName = “ChargeTemplate” + “.xls”;
}
return resp;
}

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s