如何将字符串响应转换为ArrayBuffer?

时间:2016-08-18 10:32:52

标签: javascript python django pdf pdfkit

从服务器我得到pdf响应为字符串格式,现在在客户端,我想将其转换为ArrayBuffer,以便我们可以在pdf中再次更改。

我正在将其转换为pdf,如下所示,但不是pdf正在被破坏。

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

我从stackover flow获得的上述功能,我将Uint16Array更改为Uint8Array,pdfkit使用utf-8 uncode formate ..

service.getAddress(reqData).then(function(response){
                if(response.data.error ===1){
                    toastr.error(response.data.message ,"Unsuccessful");
                }else{



                    var uintStr = str2ab(response.data);
                    var file = new Blob([uintStr], {
                        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();
                }
            });

使用pdf工具包将其转换为字符串格式。

add_str = render_to_string(address_template_path , {"address_dict": address_dict})
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.
response['Content-Disposition'] = 'inline;filename= %s' % envelope_id

0 个答案:

没有答案