Is it possible to force file downloads in browsers with angularjs? - angularjs

I'm have developed a SPA (Single Page Application) with AngularJS and I'm trying to force a pdf file download with AngularJS.
By the moment I only can open de pdf file in a new tab with the next code.
HTML view:
<a ng-click="download()"></a>
Controller:
$scope.download = function(){
$window.open('/cv.pdf', '_blank');
};
Is there any way to force the pdf download in the browser?
You can see this example in the following URLs:
www.juanmanuellopezpazos.es/curriculum (HTML View)
www.juanmanuellopezpazos.es/Curriculum.pdf (pdf file whose download I want to force)

I am done this in MVC.NET WITH ANGULAR JS.
It works fine with firefox also(Tested in version:50.0)
Write down following code in your function:
//in mvc view
<a ng-href="#" title="{{attachments.FileName}} " ng-click="download(attachment.FilePath,attachment.FileName)">{{attachments.FileName}} </a>
// in .js file
$scope.download = function download(pathoffile, filename) {
$http.get(pathoffile, {
responseType: "arraybuffer"
}).then(function (response) {
$scope.filedata = response.data;
var headers = response.headers();
headers['Content-Disposition'] = "attachment";
var blob = new Blob([response.data], { type: "octet/stream" });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
}

This previous question should provide quite a lot of information on this.
(HTML) Download a PDF file instead of opening them in browser when clicked
In you're case I'd recommend just direct linking to the PDF and using the download attribute (http://www.w3schools.com/tags/att_a_download.asp).

Finally I got the solution with #kierandotco answer. The best way is something like this:
The download HTML5 attribute and target attribute with _self value do the trick.

Related

How to show pdf file in react.js

i just try to sample application for ios, android and web using react-native-web. Here i have to download a pdf file from server and while click the showpdf button the downloaded file need to open in both android application as well as windows browser also. for browser download i have used the following code
fetch('http://www.pdf995.com/samples/pdf.pdf',{
method: 'GET',
mode: 'no-cors',
responseType: 'blob', // important
headers: {
'Content-Type': 'application/json',
},})
.then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', item.pdfFileName);
document.body.appendChild(link);
link.click();
this.setState({
pdf_url:url
});
after download i need to open this pdf file. please help if anyone know this. thanks.
You could use <iframe> to preview the PDF directly in your page, setting the src attribute to pdf_url. window.open(pdf_url) is also an option as mentioned above, but it'll require the user to have adblocker/pop-up blocker turned off.
In your render():
{pdf_url && <iframe src={pdf_url} />}
See MDN for multiple ways to display files
I suggest you to look at https://www.npmjs.com/package/react-pdf library, using which you can simply display pdfs just like images
Here is online demo http://projects.wojtekmaj.pl/react-pdf/

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);
});

What data attribute to use when returning application/pdf?

I am returning an array of bytes from a web api method that sets content-type as 'application/octet-stream. This array of bytes is for a pdf file. I am using angularjs.
Question : What will be the data value for href in code below for this case? I have set its as attachment/pdf which is not working.
return reportsDataService.getMyData()
.then(function (data) {
var element = angular.element('<a/>');
element.attr({
href: 'data:attachment/pdf,' + url,
target: '_blank',
download: 'myreport.pdf'
})[0].click();
});
Per Blob documentation, you can code as below
var blob = new Blob([typedArray], {type: 'application/octet-binary'});
$scope.url= URL.createObjectURL(blob);
Then in your view
<a download="content.txt" ng-href="{{ url }}">download</a>
Last but not least, you should configure the compileProvider to enable the url
app.config(['$compileProvider',
function ($compileProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|file|blob):/);
}]);

Open a PDF in a new window of the browser with 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);

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"

Resources