1

Image

I am unable to save this content as proper PDF using FileSaver.js


this is Angular code

$http(
  { url:root.api_root+'/appointments/generatePDF/'+$route‌​Params.id,
    method:'GE‌​T'
}).then(function(r‌​es){ // 
    $log.log(res.data); 
    var blob = new Blob([res.data], { type: 'application/pdf' });
    window.open(res.data); 
    // saveAs(blob, 'file.pdf');
});

this is TCPDF Backend code

$pdf->Output("php://output", 'F'); 
echo file_get_contents("php://output");
7
  • For information on how to ask a question well, please see our How to Ask guide. Commented May 1, 2017 at 7:21
  • the content being set to the PDF document is Either [object Object] or this format using JSON.stringify() {"0":"%","1":"P","2":"D","3":"F","4":"-","5":"1","6":".","7":"7","8":"\n",. I am unable to get the proper render able pdf Commented May 1, 2017 at 8:46
  • Please include the code that you are using to download the PDF file. It looks like the file has been corrupted by erroneously using UTF-8 decoding. Commented May 1, 2017 at 9:36
  • this issue has been partly fixed, @georgeawg you are right as you can see in the image due to character encoding the pdf is not rendering. Commented May 1, 2017 at 10:00
  • When asking a question about a problem caused by your code, you will get much better answers if you provide code people can use to reproduce the problem. Provide all parts needed to reproduce the problem in the question itself. See How to create a Minimal, Complete, and Verifiable example. Commented May 1, 2017 at 10:07

3 Answers 3

6

When downloading binary data such as PDF files, it is important to set the responseType property:

$http(
  { url:root.api_root+'/appointments/generatePDF/'+$route‌​Params.id,
    method:'GE‌​T',
    //IMPORTANT
    responseType: 'blob'
}).then(function(r‌​es){ // 
    $log.log(res.data);
    //var blob = new Blob([res.data], { type: 'application/pdf' });
    //window.open(res.data);
    var blob = res.data; 
    saveAs(blob, 'file.pdf');
});

If the responseType property is omitted, the XHR API defaults to processing the data as UTF-8 text. The process of decoding the data as UTF-8 text will corrupt binary files such as PDF or images.

For more information, see MDN Web API Reference - XHR ResponseType

Sign up to request clarification or add additional context in comments.

Comments

2

Dependencies

Installation

Using bower: bower install angular-file-saver

Using npm: npm install angular-file-saver

Basic usage

  • Include ngFileSaver module into your project;
  • Pass both FileSaver and Blob services as dependencies;
  • Create a Blob object by passing an array with data as the first argument and an object with set of options as the second one: new Blob(['text'], { type: 'text/plain;charset=utf-8' });
  • Invoke FileSaver.saveAs with the following arguments:
    • data Blob: a Blob instance;
    • filename String: a custom filename (an extension is optional);
    • disableAutoBOM Boolean: (optional) Disable automatically provided Unicode text encoding hints.

You can do so by injecting FileSaver and Blob into the controller and then using the syntax as shown below:

angular.module('sample',['ngFileSaver'])
.controller('ConsultationDetailsController', ['$scope', 'FileSaver', 'Blob', function($scope, FileSaver, Blob){
      $scope.download = function (fileName) {
                $scope.isLoading = true;

                downloadHttpService.getDocument(fileName)
                 .then(function (response) {
                    var data = response.data;
                    var status = response.status;
                    var header = response.headers();
                    var fileType = header['content-type']; 
                    var blob = new Blob([data], { type: fileType });
                    FileSaver.saveAs(blob, originalFileName);
                })
                    .catch(function (resp) {
                      // show error
                    })
                    .finally(function (data) {
                       // execute finally block.
                    });
            };
}]);

if you want only the pdf type then you can hard coded define fileType as 'application/pdf' like this var fileType= 'application/pdf';

Hope this solves your problem :)

10 Comments

I didn't downvote, but answering a low-quality question usually attracts downvotes on the answers as well. Now to my comment - You're injecting FileSaver and Blob to the controller - Don't you need to inject the relevant dependencies to to your app module as well?
Yes, you have to inject 'ngFileSaver' to your main app module.
So edit and include it in the answer (Add it in the actual code) and i'll upvote, since then it should be a complete answers (At least to me)
I have added the installation , dependencies and basic usage . Now you can refer to this. And let me know if it helps or not.
Now that's a great answer! Hope it will help the OP
|
0

Its work for me. Just try it.

$http(
  { url:root.api_root+'/appointments/generatePDF/'+$route‌​Params.id,
    method:'GE‌​T'
}).then(function(r‌​es){
    $log.log(res.data);     
    saveAs('data:application/pdf;base64,' + res.data, 'file.pdf');
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.