我正在使用 pdfkit ,从模板生成pdf。我想将其作为http响应发送,以便在客户端我们能够以pdf格式下载。 但在客户端,它已被破坏。请告诉我原因。我认为有任何编码问题,我认为我们必须在服务器端代码中发送encode('utf-8')
....
服务器端代码(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.
客户端(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;
}
我从Converting between strings and ArrayBuffers
获得上述功能str2ab