Open a PDF in a new window of the browser with angularjs - angularjs

I'm new to angular js and I wish to open a PDF document in a new window of the browser after pressing a button.
I make a GET request with $http.get() at front end, at backend there is a Java rest service that respond to the GET and generates a PDF. I wish to open this PDF on the browser.
If is not possible to open the PDF in this way then at least open any PDF with AngularJs, how could I do this?
#GET
#Path("/printPdf")
public Response printService(){
//generates the pdf
File reportFile = new File(filePath);
String name = reportName + "." + "pdf";
ResponseBuilder response = Response.ok(new TemporaryFileInputStream(reportFile));
response.header("Content-Disposition", "attachment; filename=" + name);
response.header("Content-Type", "application/pdf");
response.header("Access-Control-Expose-Headers", "x-filename");
response.header("x-filename", name);
return response.build();
}
this is what there is at backend to generate the response in the rest service.

If you had something like this:
var myPdfUrl = 'something'
$http.get(myPdfUrl);
Do this instead:
var myPdfUrl = 'something'
$window.open(myPdfUrl);
If instead you have something like this:
$http
.get(generatePdfUrl)
.then(function(data){
//data is link to pdf
});
Do this:
$http
.get(generatePdfUrl)
.then(function(data){
//data is link to pdf
$window.open(data);
});

Maybe this can help,in the case of you have something like this :
$http.get('generatePdfUrl')
.then(function (data) { // data is your url
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
});
Then use your service in controller and do
$window.open(fileURL);

Related

How to get PDF downloaded in $resource put service angularjs1

I want to download a PDF from server depending on the input request sent from UI . I am getting a pop-up with [object objcet] written on it .
Can somebody help me out in this .
P.S. : I have to use $resource only , not the $http one , thanks :)
This is my Service call to WEB API , Service name is "GetInvoice"-->
function ($resource) {
return $resource('app/rest/invoice/:id', null, {
'update': { method:'PUT'}
},{ headers: {'Content-Type': 'application/pdf'},
transformRequest: []});
}
This is my service call from controller -->
GetInvoice.update({id:'1'},angular.toJson(invoiceJSON)).$promise.then(function (data) {
var file = new Blob([data]);
var fileURL = ($window.URL || $window.webkitURL).createObjectURL(file);
$window.open(fileURL, '_blank', 'download');});
Change the line
var file = new Blob([data]);
to
var file = new Blob([data.data]);
and check out.
If this doesn't work out,
dynamically create a anchor tag and invoke the click event which will open a popup / new tab with the content. Refer here

How to Open a pdf file in angularjs

i am trying to open a pdf file in angularjs.actually i created a pdf file with database content and stored in the server location now i need to open a pdf file in the browser.I tried the bellow code.but not worked.
controller.js
$http.get(urlBase+'/generatePdfUrl')
.success(function (data) { // data is your url
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$window.open(fileURL);
}).error(function(data){
alert(data);
});
I am getting my file URL correctly in data.but new tab open in the browser shows the below URL in browser address bar
blob:http://localhost:8080/c87ffb9f-b2cb-8741-a2d2-3c8af5609359
can any one help me to do this
$http.get(urlBase+'/generatePdfUrl').then(function(data){
$window.open(data);
});

AngularJS Web Api HttpHandler Image Downloader

My AngularJS application is interacting with ASP.NET Web API to full fill the request which is working fine. it has an use case that allows user to download user specific secure PDF document. I have implemented this functionality as below
AngularJS:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
$scope.DownloadHandler = function (id, downloadURL) {
FileStreamManager.getPdf(id, downloadURL)
.then(function (result) {
// success
window.open(downloadURL + id, '_self', '');
},
function (result) {
$scope.errors = result.data;
});
};
Note : downloadURL is the Controller call like \ImageRepo\Get
Web Api Controller I have this implementation:
HttpResponseMessage response = new HttpResponseMessage();
// DB call to to build the URL
string fileName = "myLocation\Image\doc.pdf";
if (!fileProvider.Exists(fileName))
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
FileStream fileStream = fileProvider.Open(fileName);
response.Content = new StreamContent(fileStream);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentLength = fileProvider.GetLength(fileName);
return response;
Which is working fine. Due to the security issue, i was asked to implement this by using HttpHanlder which is pretty new to me. I have some question on the same.
Should my AngularJS ng-click calls to my .ashx handler directly instead of a Controller URL? Or Should this call route through Controller? How?
I have DB calls to build the image URL and update some the status. Can this be done in Handler itself?
How would i make sure my documents are secured while downloading?
Please help.

Outputting a PDF (created with FPDF) in AngularJS

I am using FPDF to create a PDF on a Laravel backend that serves Angular. I have created it in the normal FPDF way and I am unsure how to send the file response back to Angular.
I read here about generall how to go about it by configuring my $http request as below:
return $http({url: '/api/print/class-list', method: "POST", data: {data: data}, headers: {'Accept':'application/pdf'}, responseType: 'arrayBuffer'})
.then(function(response)
{
console.log(response.data);
var file = new Blob([response.data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
var content = $sce.trustAsResourceUrl(fileURL);
return content;
}
I have injected $sce in the service and i am outputting the content in an embed tag. The tag just shows an empty PDF. I am wondering what the problem could be. Also, on the Laravel side, once I am done creating the PDF by writing $pdf->Output("page","D"), is there a way i should write return something so that it can be returned to Angular?
Also, when i console response, it kindof returns blob or some pdf stuff, and a number of errors after that like:
"Warning: Unsupported feature "unknown"

Failed to load PDF document - Angular JS - BLOB

I am trying to get PDF document from Web API, and want to show in Angular App. Getting "Failed to load PDF document error".
I have followed
"AngularJS: Display blob (.pdf) in an angular app" post.
Whereas, i can download the same file successfully by following "Download file from an ASP.NET Web API method using AngularJS" post.
Looks like i am getting the file as "Chunked Transfer Encoded". Somehow this is not getting decoded when trying to show in angular app. Please advise.
Web API Code:
HttpResponseMessage result = null;
var localFilePath = #"C:\Test.pdf";
if (!File.Exists(localFilePath))
{
result = Request.CreateResponse(HttpStatusCode.Gone);
}
else
{// serve the file to the client
result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
result.Content.Headers.ContentDisposition.FileName = "Test.pdf";
result.Content.Headers.Add("x-filename", "Test.pdf");
}
return result;
Angular Controller:
myModule.controller("pdfviewerController", function ($scope, $http, $log, $sce) {
$http.post('/api/Sample/GetTestFile', {responseType:'arraybuffer'})
.success(function (response) {
var file = new Blob([response], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
$scope.content = $sce.trustAsResourceUrl(fileURL);
});
});
HTML Template:
<embed ng-src="{{content}}" style="width:200px;height:200px;"></embed>
problem is there in controller.
{responseType:'arraybuffer'} is verymuch required.
For $http.get - It should be second parameter.
For $http.post - It should be third parameter.
In above case, i am using $http.post and i have passed {responseType:'arraybuffer'} as second parameter.
$http.post('/api/Sample/GetTestFile', {responseType:'arraybuffer'})
Corrected code
$http.post('/api/Sample/GetTestFile','', {responseType:'arraybuffer'})

Resources