从API Rest获取图像并用Javascript打印



我有下一个从APi:获取图像的代码

var settings = {
"url": "https://api.labelary.com/v1/printers/8dpmm/labels/4x6/0/",
"method": "POST",
"timeout": 0,
"headers": {
"Accept": "image/png",
"Content-Type": "application/x-www-form-urlencoded"
},
"data": "commands ZPL",
};
$.ajax(settings).done(function (response) {
console.log(response);
var image = new Image();
image.src = response;   
var win = window.open('');
win.document.write(image);
win.focus();
});

它在Postman中使用了api(可以看到图片(,但在javascript中不起作用。widnow打印示例

有人帮忙。

win.document.write(image);写入文本(即win.document.write('<h1>Hello</h1>');(

相反,您希望使用document.append()API来插入节点。为此,您需要在DOM中找到元素来插入节点。

您可以搜索body标记,也可以使用document-write编写带有ID的body标记并搜索该标记。

$.ajax(settings).done(function (response) {
var image = new Image();
image.src = response;   
var win = window.open('');
win.document.write("<html><body id='root'></body></html>");
win.document.getElementById("root").appendChild(image);
win.focus();
});

最新更新