我目前正在将退货流程开发为电子商务应用程序。 我一直坚持让PDFLayer API与我的体系结构一起使用。我需要将简单的HTML发票转换为可工作的PDF。我通过AJAX将我的URL发布到PDFLayer并检索了我无法处理的响应。我尝试了StackOverflow上发现的许多方法,但没有一种方法对我有用。我最好的结果是渲染的PDF文件损坏或有错误。有人可以向我解释我做错了吗,或者有人可以向我解释如何将Base64编码的PDF流式传输到Blob,以便我可以创建URL并在新窗口中下载它?
到目前为止,这是我最好的代码(我正在使用类似于jquery和bootstrap 4的node的express.js的云架构):
'use strict';
var url;
var labelFunctions = {
init: function () {
var pdfDownloadDiv = $('.pdf-download');
if (pdfDownloadDiv.length > 0) {
$('.print-pdf', pdfDownloadDiv).on('click',(this.downloadPdf));
}
},
downloadPdf: function () {
console.log('downloadPdf:execute')
var element = $(this);
url = element.data('serviceurl')
+ '?access_key='
+ element.data('access_key')
+ '&document_url='
+ element.data('renderurl')
+ '?returnID='
+ element.data('id')
+ '&document_name='
+ element.data('name')
+ '&test=1'
+ '&page_size=A4'
//+ '&inline=1'
+ '&grayscale=1'
+ '&no_backgrounds=1'
+ '&use_print_media=1';
$.ajax({
url: url,
crossDomain:true,
type: 'post',
encoding: null,
success: function(data){
alert('DONE');
console.log(data);
var PDFString = data;
var myBase64string = b64EncodeUnicode(PDFString);
var myBlob = b64toBlob(myBase64string, 'application/octet-stream', 512)
console.log(myBase64string);
console.log(myBlob);
var blobUrl = URL.createObjectURL(myBlob);
var win = window.open("",'PDF');
win.location = blobUrl;
},
error: function(err){
console.log(err);
console.log('error');
}
});
}
}
function b64EncodeUnicode(str) {
// first we use encodeURIComponent to get percent-encoded UTF-8,
// then we convert the percent encodings into raw bytes which
// can be fed into btoa.
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
function toSolidBytes(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
function b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, {type: contentType});
return blob;
}
labelFunctions.init();
预先感谢