0

I am using pdfkit, to generate pdf from template. I want to sent it as http response, so that on client side we will able to download as pdf. But on client side it is getting corrupted. Please tell me why. I think is there any encoding problem, I think we have to send encode('utf-8') in server side code....

Server side code(django)

address_template_path = os.path.join(settings.BASE_DIR,'address_template.html')

# generate pdf
add_str = render_to_string(address_template_path)
pdfkit.from_string(add_str, file_location)

address_pdf = open(file_location)
response = HttpResponse(address_pdf.read(), 
content_type='application/pdf')  # Generates the response as pdf response.

client-side(javascript+angularjs)

$scope.downloadAddress = function(reqData){

        service.getAddress(reqData).then(function(response){
            if(response.data.error){
                toastr.error(response.data.message ,"Unsuccessful");
            }else{
                var file = new Blob([ str2ab(response.data) ], {
                    type : 'application/pdf'
                });
                //trick to download store a file having its URL
                var fileURL = URL.createObjectURL(file);
                var a         = document.createElement('a');
                a.href        = fileURL;
                a.target      = '_blank';
                a.download    = envelopeObj.customer_name+'_'+ 'envId_'+envelopeObj.envelope_id+'.pdf';
                document.body.appendChild(a);
                a.click();
            }
        });
    };

function str2ab(str) {
          var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
          var bufView = new Uint16Array(buf);
          for (var i=0, strLen=str.length; i < strLen; i++) {
            bufView[i] = str.charCodeAt(i);
          }
          return buf;
        }

I get above function str2ab from Converting between strings and ArrayBuffers

Community
  • 1
  • 1
Guest
  • 415
  • 8
  • 19

0 Answers0