我创建了一个应用程序,通过使用JSON在图表上绘制详细信息。然后将该图表另存为png / pdf。为此,我的代码是 -
function ExportPdfAndSaveChart(id, title, type, downLoadFile, selectedProject) {
var dateForFileName = getfileDateForName();
downLoadFile = downLoadFile + "_" + dateForFileName;
//code to convert image from svg to canvas
var html = d3.select(id).select("svg")
.attr("version", 1.1)
.attr("xmlns", "http://www.w3.org/2000/svg")
.node().parentNode.innerHTML;
var imgsrc = 'data:image/svg+xml;base64,' + btoa(html);
var img = '<img src="' + imgsrc + '">';
d3.select("#svgdataurl").html(img);
var iDiv = document.createElement('div');
iDiv.id = 'block';
document.getElementsByTagName('body')[0].appendChild(iDiv);
var innerDiv = document.createElement('canvas');
iDiv.appendChild(innerDiv);
var canvas = document.querySelector("canvas"),
context = canvas.getContext("2d");
canvas.width = 800;
canvas.height = 1130;
context.font = "30px Arial";
context.textAlign = 'center';
context.fillStyle = '#fff';
context.fillRect(0, 0, canvas.width, canvas.height);
var image = new Image();
image.crossOrigin = "Anonymous";
image.src = imgsrc;
image.onload = function () {
context.drawImage(image, 100, 200);
context.fillStyle = "Black";
context.rect(10, 10, 772, 1100);
context.stroke();
context.strokeStyle = 'blue';
context.lineWidth = 5;
context.fillText(title, 380, 50);
context.font = "20px Arial";
context.textAlign = 'center';
context.fillText(selectedProject, 380, 80);
var canvasdata = canvas.toDataURL("image/png");/*"image/png", 1, 0*/
//type=1 is for export pdf else for png
if (type == 1) {
pdf = new jsPDF('p', 'mm', [297, 210]);
pdf.setFontSize(40);
pdf.addImage(canvasdata, 'png', 0, 0);
pdf.save(downLoadFile + ".pdf");
} else {
var pngimg = '<img src="' + canvasdata + '">';
d3.select("#pngdataurl").html(pngimg);
var a = document.createElement("a");
document.body.appendChild(a);
a.download = downLoadFile + ".png";
a.href = canvasdata;
a.click();
}
};
}
这些代码与chrome / firefox完美运行。但是在IE中出现错误 - var canvasdata = canvas.toDataURL(“image / png”);错误是 SecurityError
为此,我设置了image.crossOrigin =“Anonymous”;也。但它仍然没有用。
答案 0 :(得分:0)
我偶然发现了类似的问题(在我的案例中有PDF文件),并解决了这个问题:
$http.get('/webclientes/api/policies/getPlanFile/OLAS&&CG247S2501.pdf', {
$http.get('/webclientes/api/policies/getPlanFile/'+datos, {
responseType: 'blob'
})
.success(function(data, response) {
vm.errorNoExistePDF = true;
var file = new Blob([data], {
type: 'application/pdf'
});
var fileURL = URL.createObjectURL(file);
if ($window.navigator && $window.navigator.msSaveOrOpenBlob) {
$window.navigator.msSaveOrOpenBlob(file);
}else
$window.open(fileURL);
})
.error (function(data){
console.log("ERROR");
vm.errorNoExistePDF = true;
});
});
注意这一点:
if ($window.navigator && $window.navigator.msSaveOrOpenBlob) {
$window.navigator.msSaveOrOpenBlob(file);