printing the html response back on the html page - javascript

I am using angularjs and springmvc in the application. My requirement is to hit the webpage(URL) and whatever response it returns(basically it returns html content of the webpage accessed through URL) i need to show on the html page.
Below is my code:
one.html
<div class="myDiv">
<table style="width:100%;height:100%;">
<tr>
<td ng-controller="getHTMLController">
<h1>HIT the URL and get the response</h1>
</td>
</tr>
</table>
{{htmlResponsedata}}
</div>
JavaScript
myApp
.controller("getHtmlDataController", [
"$scope", 'MyService',
function ($scope, MyService) {
MyService.fetch().then(function (response) {
$scope.htmlResponsedata = response;
}, function (errResponse) {
$scope.cancelModal();
$rootScope.showError(500, "Internal error");
});
_myServiceFactory.fetch = function () {
var deferred = $q.defer();
var repUrl = myAppURL + '/percentValues/' + '/getHtmlData.form';
$http.get(repUrl).then(function (response) {
console.log("response");
derred.resolve(response.data);
},
function (errResponse) {
console.error('Error while fetching data');
deferred.reject(errResponse);
}
);
return deferred.promise;
}
}
]);
Java
#RequestMapping(value = "/getHtmlData", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody String getHtmlData() throws Exception {
URL url = new URL("https://xyz/abc.com/values/reports");
HttpsURLConnection connection = ((HttpsURLConnection) url.openConnection());
connection.addRequestProperty("User-Agent", "Mozilla/4.0");
InputStream input;
input = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String msg;
while ((msg = reader.readLine()) != null)
System.out.println("--------------------"+msg);
return msg; //html code of the URL
}
}
Above is my entire code written using angularjs and springMVC. How to print the data returned by msg from java code on the oe.html page.I have used {{htmlResponsedata}} but the response is not printed. htmlResponsedata is the response i got and which i have set $scope.htmlResponsedata = response in the js code as shown above. Any suggestions as how to print the html response back on the screen?

Related

Excel file not being downloaded when function is called via ajax method

Situation
I am working on an application where I can have a grid with X items, and each item has a print button. Clicking this print button allows me to call an ajax function which passes the ID of the grid item to a controller. I retrieve the relevant data based on that ID and then download it in an excel file. (The retrieving of the specific item is not yet done)
What I have so far
So far, I have the basic code that downloads an excel file, along with my grid .
Problem
The problem I am facing is, if I click the "Print" button...nothing happens, even with a breakpoint in my exporttoexcel functions shows me that the function is entered and I can step thru it and despite no errors, nothing occurs. However, I added random button that called the same function and when i clicked that button, the excel file was downloaded. As a result, I believe the issue has something to do with aJax.
Code
<input type="button" value="Test" onclick="location.href='#Url.Action("ExportToExcel", "Profile")'" />
This is the code which downloads the file. It was a simple button I added.
function ExportToExcel(id) {
$.ajax({
type: "POST",
url: "#Url.Action("ExportToExcel", "Profile")",
data: { "id": id },
dataType: "json"
});
}
This is the function that I want to work, but it does not work and I cannot see what i've got wrong.
Export to Excel Code
public void ExportToExcelx()
{
var products = new System.Data.DataTable("teste");
products.Columns.Add("col1", typeof(int));
products.Columns.Add("col2", typeof(string));
products.Rows.Add(1, "product 1");
products.Rows.Add(2, "product 2");
products.Rows.Add(3, "product 3");
products.Rows.Add(4, "product 4");
products.Rows.Add(5, "product 5");
products.Rows.Add(6, "product 6");
products.Rows.Add(7, "product 7");
var grid = new GridView();
grid.DataSource = products;
grid.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
//Response.Output.Write(sw.ToString());
//Response.Flush();
//Response.End();
// =============
//Open a memory stream that you can use to write back to the response
byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
MemoryStream s = new MemoryStream(byteArray);
StreamReader sr = new StreamReader(s, Encoding.ASCII);
//Write the stream back to the response
Response.Write(sr.ReadToEnd());
Response.End();
// return View("MyView");
}
Theory
I believe the error is somehow tied in to aJax, I am also creating the button in the controller like this.
"<button type='button' class='btn btn-warning' onclick='ExportToExcel(" + c.id + ");'>Print</button>",
Since location.href='#Url.Action works, I was wondering if attempting to redo my dynamic button would solve my issue.
Appreciate any insight that could be offered.
Yes you are right you have problem with ajax, Basically you have to call the controller action again from you ajax call when your first ajax call return success. Add below code snippet to your ajax call.
success: function () {
window.location = '#Url.Action("ExportExcel", "Profile")?id='+id;
}
And you have to change your controller method to return the file, as below
public FileResult ExportToExcelx()
{
...............
byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
return File(byteArray, System.Net.Mime.MediaTypeNames.Application.Octet, "FileName.xlsx");
}
File cannot be downloaded until full post back is triggered. Here is how you can do it:
Your ExportToExcelx function will hold file in TempData object as following:
TempData["fileHandle"] = s.ToArray();
Rather than returning view return temp data identifier "fileHandle" and file name as shown below:
return Json(new { fileHandle = "fileHandle", FileName = "file.xls" }, JsonRequestBehavior.AllowGet);
So your modified function will be like this:
public JsonResult ExportToExcelx()
{
var products = new System.Data.DataTable("teste");
products.Columns.Add("col1", typeof(int));
products.Columns.Add("col2", typeof(string));
products.Rows.Add(1, "product 1");
products.Rows.Add(2, "product 2");
products.Rows.Add(3, "product 3");
products.Rows.Add(4, "product 4");
products.Rows.Add(5, "product 5");
products.Rows.Add(6, "product 6");
products.Rows.Add(7, "product 7");
var grid = new GridView();
grid.DataSource = products;
grid.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
//Response.Output.Write(sw.ToString());
//Response.Flush();
//Response.End();
// =============
//Open a memory stream that you can use to write back to the response
byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
MemoryStream s = new MemoryStream(byteArray);
TempData["fileHandle"] = s.ToArray();
//StreamReader sr = new StreamReader(s, Encoding.ASCII);
//Write the stream back to the response
Response.Write(sr.ReadToEnd());
Response.End();
return Json(new { fileHandle = "fileHandle", FileName = "file.xls" }, JsonRequestBehavior.AllowGet);
// return View("MyView");
}
Now you need another function in your controller to download file like following:
[HttpGet]
public virtual ActionResult Download(string fileHandle, string fileName)
{
if (TempData[fileHandle] != null)
{
byte[] data = TempData[fileHandle] as byte[];
return File(data, "application/vnd.ms-excel", fileName);
}
else
{
return new EmptyResult();
}
}
On successful call to ExportToExcelx function your ajax call will call download function as following:
$.ajax({
type: 'GET',
cache: false,
url: '/url',
success: function (data) {
window.location = '/url/Download?fileHandle=' + data.fileHandle
+ '&filename=' + data.FileName; //call download function
},
error: function (e) {
//handle error
}
Download function then will return the file.
Hope this helps.
I've had a similar problem here, and it did solve with a dynamic button as well. I just had to include a responseType:'blob' in my request.
And get the response to the button:
var link = document.createElement('a');
link.href = window.URL.createObjectURL(response.data);
link.download='filename.xlsx';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
And my Controller writes to a output stream and produces a "application/xls"
response.setContentType("application/xls");
response.setHeader("Content-disposition", "attachment;");
response.getOutputStream().write(content);
First of all, I would not use GridView to generate excel. Despite being "easy", it won't generate an actual excel file, but rather a html file with xls extension:
<div>
<table cellspacing="0" rules="all" border="1" style="border-collapse:collapse;">
<tr>
<th scope="col">col1</th><th scope="col">col2</th>
</tr><tr>
<td>1</td><td>product 1</td>
</tr><tr>
<td>2</td><td>product 2</td>
</tr><tr>
<td>3</td><td>product 3</td>
</tr><tr>
<td>4</td><td>product 4</td>
</tr><tr>
<td>5</td><td>product 5</td>
</tr><tr>
<td>6</td><td>product 6</td>
</tr><tr>
<td>7</td><td>product 7</td>
</tr>
</table>
</div>
This results in a file that when opened will cause this:
that is pretty annoying (and unprofessional).
If you're not bounded to old excel version - xls - but can use most recent file format xlsx, I'd rather use DocumentFormat.OpenXml nuget package or other packages/libraries for excel generation.
Honestly, DocumentFormat.OpenXml is powerful but a little boring to use, when you have many columns and you just have a flat list of objects to report.
If you are using .NET Framework (not Dotnet Core), you can try
CsvHelper.Excel nuget package. Usage is pretty straight forward. Your ExportToExcel method will become something like:
public ActionResult ExportToExcel(string id)
{
// TODO: Replace with correct products retrieving logic using id input
var products = new [] {
{ col1 = 1, col2 = "product 1" },
{ col1 = 2, col2 = "product 2" },
{ col1 = 3, col2 = "product 3" },
{ col1 = 4, col2 = "product 4" },
{ col1 = 5, col2 = "product 5" },
{ col1 = 6, col2 = "product 6" },
{ col1 = 7, col2 = "product 7" },
{ col1 = 1, col2 = "product 1" },
{ col1 = 1, col2 = "product 1" },
};
var ms = new MemoryStream();
var workbook = new XLWorkbook();
using (var writer = new CsvWriter(new ExcelSerializer(workbook)))
{
writer.WriteRecords(products);
}
workbook.SaveAs(ms);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
return File(ms, MimeMapping.GetMimeMapping("file.xlsx"), $"MyExcelFile.xlsx");
}
Another package pretty powerful is EPPlus, that allows you to load a DataTable (see this: https://stackoverflow.com/a/53957999/582792).
Coming to the AJAX part, well... I do not think you need it at all: once you set the location to the new ExportToExcel action, it should just download the file.
Assuming you are using Bootstrap 3, for each of your item in the collection you can just:
<a href="#Url.Action("ExportToExcel", "Profile", new {id=item.Id})" class="btn btn-info">
<i class="glyphicon glyphicon-download-alt" />
</a>
There are multiple solutions to this problem:
Solution 1
Let's imagine you have a Product model like this:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
In you controller:
[HttpPost]
public JsonResult ReportExcel(string id)
{
// Your Logic Here: <DB operation> on input id
// or whatsoever ...
List<Product> list = new List<Product>() {
new Product{ Id = 1, Name = "A"},
new Product{ Id = 2, Name = "B"},
new Product{ Id = 3, Name = "C"},
};
return Json(new { records = list }, JsonRequestBehavior.AllowGet);
}
Then inside your View (.cshtml), use the JSONToCSVConvertor as a utility function and just Don't touch it as it converts the array of json objects received into Excel and prompts for download.
#{
ViewBag.Title = "View export to Excel";
}
<h2>....</h2>
#* All Your View Content goes here *#
#* This is a sample form *#
<form>
<div class="form-group">
<label>Product ID</label>
<div class="col-md-10">
<input id="productID" name="productID" class="form-control"/>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input id="submit" type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</form>
#section scripts{
<script>
$('#submit').click(function (e) {
e.preventDefault();
var ID = $('#productID').val();
$.ajax({
cache: false,
type: 'POST',
url: '/YourControllerName/ReportExcel',
data: {id: ID},
success: function (data) {
console.log(data);
JSONToCSVConvertor(data.records, "Sample Report", true);
}
})
});
function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = 'sep=,' + '\r\n\n';
//This condition will generate the Label/Header
if (ShowLabel) {
var row = "";
//This loop will extract the label from 1st index of on array
for (var index in arrData[0]) {
//Now convert each value to string and comma-seprated
row += index + ',';
}
row = row.slice(0, -1);
//append Label row with line break
CSV += row + '\r\n';
}
//1st loop is to extract each row
for (var i = 0; i < arrData.length; i++) {
var row = "";
//2nd loop will extract each column and convert it in string comma-seprated
for (var index in arrData[i]) {
row += '"' + arrData[i][index] + '",';
}
row.slice(0, row.length - 1);
//add a line break after each row
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
//Generate a file name
var fileName = "MyReport_";
//this will remove the blank-spaces from the title and replace it with an underscore
fileName += ReportTitle.replace(/ /g, "_");
//Initialize file format you want csv or xls
var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
// Now the little tricky part.
// you can use either>> window.open(uri);
// but this will not work in some browsers
// or you will not get the correct file extension
//this trick will generate a temp <a /> tag
var link = document.createElement("a");
link.href = uri;
//set the visibility hidden so it will not effect on your web-layout
link.style = "visibility:hidden";
link.download = fileName + ".csv";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
</script>
}
I ran and built the above code successfully, so feel free to grab and tweak it as you wish.
Also here is the jsFiddle link, thanks to its developer: https://jsfiddle.net/1ecj1rtz/
Solution 2
Call this action method through $.ajax and get the file downloaded:
public FileResult Export(int id)
{
//......... create the physical file ....//
byte[] fileBytes = File.ReadAllBytes(filePath);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
Along with Solution 2, this thread gives you a good idea: https://stackoverflow.com/a/16670517/4687359
Hope this helped. :)
ANSWER:
You need to include success in your ajax call.
function ExportToExcel(id) {
$.ajax({
type: "POST",
url: "#Url.Action("ExportToExcel", "Profile")",
data: { "id": id },
dataType: "json"
success: function () {
window.location = '#Url.Action("ExportExcel", "Profile")?id='+id;
}
});
}
For Duplicate headers received from the server
Duplicate headers received from server
The data will be transformed to a query string on an AJAX GET request; just do that yourself using the jQuery param function:
$('#excel').on('click',function(){
var query = {
location: $('#location').val(),
area: $('#area').val(),
booth: $('#booth').val()
}
var url = "{{URL::to('downloadExcel_location_details')}}?" + $.param(query)
window.location = url;
});
Here is how I got this working for PDF. Excel download should be similar
$.ajax({
url: '<URL_TO_FILE>',
success: function(data) {
var blob=new Blob([data]);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="<FILENAME_TO_SAVE_WITH_EXTENSION>";
link.click();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
OR using download.js
$.ajax({
url: '<URL_TO_FILE>',
success: download.bind(true, "<FILENAME_TO_SAVE_WITH_EXTENSION>", "<FILE_MIME_TYPE>")
});

How to update the displayed content of a file on an HTML page with AJAX?

I'm trying to continuously display the contents of a file on my HTML page
(at every 'X' times). In other words, I want to make a logger and visualize it as if it were in a terminal. I'm new to AJAX and I'm not exactly sure how to set up the ajax call in the javascript, more specifically, what URL goes by parameter.
I'm passing a model through my controller to a form in thymeleaf:
<form id="formTest" class="form-inline" action="#" th:action="#{'log/'}" th:object="${log}" method="post">
...
</form>
This way I can create an object and then print its contents. The contents of the object originate from a file*.log*, which is located in a remote directory.
<p th:utext="${log.content}">Log content</p>
The file path is mapped in the controller
#RequestMapping(value = "/log", method = RequestMethod.POST)
public String logContent_post(#Valid Log log, BindingResult bindingResult, Map<String, Object> model) {
if (log.getInitLine() == 0 && log.getFinalLine() == 0) {
try {
fileNumberLines(log);
// lineOccurrence, firstLine, lastLine, logPath
log.setContent(getLogContentByRange(0, log.getInitLine(), log.getFinalLine(), logsDir + "/" + log.getFilename()));
} catch (IOException e) {
logger.error(e.getMessage());
}
} else {
log.setContent(
getLogContentByRange(0, log.getInitLine(), log.getFinalLine(), logsDir + "/" + log.getFilename()));
}
model.put("path", logsDir);
model.put("log", log);
model.put("currentPage", "logs");
model.put("root", root);
return "log";
}
My Ajax function
function att(){
$.ajax({
type : 'POST',
url : '',
cache: false,
success : function(data) {
console.log("Content:" + data);
},
complete : function() {
}
});
}
setInterval(function() {
if (window.location.pathname == '/log/') {
att();
}
}, 5000);
I've tried to pass several "url's" through AJAX, but either I get 404 () or null as a return. So my question: What Url should I pass by parameter?

Javascript alert in code behind

I need to call Javascript alert function in c# method if web service is not available. I am using as.net core and webapi for webservice.
Here is the code
public List<EmployeeModel> GetEmployeeByEmpNo(string empNo)
{
try
{
string Baseurl = sys_ser.getApiURL();
EmployeeModel EmpInfo = new EmployeeModel();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage Res = client.GetAsync("api/Values/GetEmployeeByEmpNo/" + empNo).Result;
if (Res.IsSuccessStatusCode)
{
var EmpResponse = Res.Content.ReadAsStringAsync().Result;
var empobjList = JsonConvert.DeserializeObject<List<EmployeeModel>>(EmpResponse);
//var EmpObj = empobjList[0];
if (empobjList != null)
{
return empobjList;
}
}
}
}
catch(Exception ex)
{
//<Srcript> alert('WebService is not available' + ex.message)</>
}
return null;
}
If AJAX isn't an option, you can pass a flag to tell the client to create the window:
Controller:
return View("Index", (object)errorDetails);
View:
#model string
<!--Your HTML-->
#if (!string.IsNullOrEmpty(Model)
{
<script type="text/javascript">
alert(Model);
</script>
}

unable to hit the spring controller when tested in IE11

I have a trouble with IE when ng-click is used in the button.
I want to reload the data from spring controller whenever user click on the button which is working fine in chrome but not in IE11.
Issue is when page is loaded data is displayed on the webpage, when Refresh Data button is clicked, it will reload the data by hitting to the spring controller which is not working in IE. In IE, when user click on a button, it is hitting the angular controller as well as service method also but not hitting the spring controller.But when developer tools is opened it is hitting the spring controller.
Example below:
html code:
<div ng-controller="loadingSampleCtrl">
<button class="btn btn-primary" type="button" ng-click="loadOrRefreshData()">Reload</button>
{{myData.empName}} /* This is printed in chrome as well as in IE with developer tools opened*/
</div>
js code:
myApp.controller('loadingSampleCtrl', function ($scope, MyService) {
$scope.loadData = function () {
$scope.loading = true;
MyService.testData().then(
function (response) {
alert("response back from spring controllerf");
if(window.navigator.msSaveOrOpenBlob){
$scope.IEBrowser = true;
$scope.myData = response;
/* $timeout(function() {
$scope.pdfName = response;
}, 0);*/
} else {
$scope.IEBrowser = false;
$scope.myData = response;
}
},
function (errResponse) {
$rootScope.showError("Internal error" + errResponse);
});
}
$scope.testData();
});
//service call
_myService.testData = function(){
alert("service call");//this alert is visible in IE
var deferred = $q.defer();
var repUrl = myAppURL+'/myDataToRead/getData.form';
$http.get(repUrl).then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
deferred.reject(errResponse);
}
);
return deferred.promise;
}
spring controller:
#RequestMapping(value = "/getData", method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody
List<String> getMyData(HttpServletRequest request) throws Exception {
System.out.println("In MyDataController"); //not printed in IE when tested without developer tools
//logic here
//return statement
}
Any suggestions would be helpful.
i check you url var repUrl = yAppURL+'/myDataToRead/getData.form';, and i this the issue is you are not map controller with the path. you are only map your method with /getData. you need to use #RequestMapping annotation into your controller. you can refer below code :
#RestController
#RequestMapping("/myDataToRead")

unable to dynamically get the filename from spring controller to the html page to load the newly created file

I want to load the PDF file dynamically and show on browser. PDF file is created on the fly when user clicks on button and the filename has timestamp in it. So i cannot give the PDF filename in the html code as shown below as it changes based on the timestamp(PDF file name is given along with the timestamp when it was created as shown in below spring controller).
Below is the code.
html code:
<div ng-controller="generatePDFController">
<button ng-click="generatePDF()">Re-Generate PDF</button>
<object data="C:/allFiles/PDFFiles/spreadDetails.pdf" type="application/pdf" width="100%" height="100%">
<iframe src="C:/allFiles/PDFFiles/spreadDetails.pdf" width="100%" height="100%" style="border: none;">
This browser does not support PDFs.
Download PDF
</iframe>
</object>
</div>
js code:
app.controller('generatePDFController', function($scope, MyService) {
$scope.generatePDF = function() {
MyService.createPDF().then(
function(response) {
$scope.pdf = response;
},
function(errResponse) {
});
}
});
//service call
_myService.createPDF = function() {
var deferred = $q.defer();
var repUrl = sURL + '/allDataGeneration/generatePDF.form';
$http.get(repUrl)
.then(
function(response) {
deferred.resolve(response.data);
},
function(errResponse) {});
return deferred.promise;
}
spring controller:
#RequestMapping(value = "/generatePDF", method = RequestMethod.GET)
public# ResponseBody List < MyDTO > generatePDF() {
List < MyDTO > response = service.getAllData();
//create PDF and write the response in it
createPDFFile(response);
return response;
}
void createPDFFile(List < MyDTO > res) {
String FILE_PATH = "C:\\allFiles\\PDFFiles\\spreadDetails";
String FILE_EXTENSION = "pdf";
DateFormat df = new SimpleDateFormat("MM-dd-yyyy hh-mm-ssa");
String filename = null;
try {
filename = FILE_PATH + df.format(new Date()) + "." + FILE_EXTENSION;
} catch (Exception e) {
e.printStackTrace();
}
File file = new File(filename);
System.out.println("-----filename------------ " + filename); //PDF file is created successfully
//spreadDetails07-13-2017 02-59-51PM ,when user clicks on GeneratePDF in UI, it hits this controller and generates the PDF
//logic to write the data inside PDF file
}
The above shown code is the complete flow of my sample application. Now when user clicks on Re-Generate PDF button, it comes to above mentioned spring controller creates a file with timestamp and writes the data in it.How to pass the newly created pdf filename to the html code <object data="C:/allFiles/PDFFiles/spreadDetails.pdf" .. so that when pdf file is created it dynamically loads and show on UI.
---EDITED---
Please see the above edited code. createPDF(List<MyDTO>) is a new method in which i'm creating a pdf file and writing the content. I will be reusing this method.
Try to follow these steps :
Change the signature of the Java method generatePDF() in order to return a String representing the name of your file. This gives you the possibility to pass the name of the file to your JavaScript ;
In your controller, do $scope.pdfName = response. This way the name of the file is store the variable $scope.pdfName ;
Last step, replace <object data="C:/allFiles/PDFFiles/spreadDetails.pdf" ...> by <object data="{$scope.pdfName}" ...>
This should work.
Marine
EDIT given your own edit :
Your method generatePdf() is incorrect : you wrote that it must return a List<MyDto> but the keyword return is nowhere.
Do you really need to return he object List<MyDto> ? In any case, you need to return the name of the file to be able to use it in your JavaScript. So, you have two solutions : either this method only returns a String representing the name of the PDF, or it returns an object with two fields, one String and one List<MyDto>. In this second cas, you will need to do
$scope.pdfName = response.fieldContainingTheNameOfTheFile.

Categories