本帖最后由 Fiooona 于 2020-9-3 18:36 编辑
如何在SpreadJS中实现打印预览、将某sheet页的指定区域的内容以图片的形式进行下载?不少客户存在这样的需求,SpreadJS在V12.2中暴露了BeforePrint接口,通过这个接口可以轻松实现打印预览、下载图片。
保存图片
监听BeforePrint事件,获取打印图片,核心代码如下:
- $("#saveImage").click(function () {
- if (isPrinting) {
- return;
- }
- spread.bind(GC.Spread.Sheets.Events.BeforePrint, function (s, e) {
- var sheet = spread.getSheet(1);
- console.log(sheet.printInfo())
- var iframe = e.iframe;
- var images = iframe.contentWindow.document.getElementsByTagName("img");
- for (var i = 0; i < images.length; i++) {
- var img = images[i];
- console.log(img)
- var canvas = document.createElement("canvas");
- canvas.height = img.naturalHeight;
- canvas.width = img.naturalWidth;
- var ctx = canvas.getContext('2d');
- ctx.fillStyle = "#FFF";
- ctx.fillRect(0, 0, canvas.width, canvas.height);
- ctx.drawImage(img, 0, 0) //, img.width, img.height);
- canvas.toBlob(function (blob) {
- saveAs(blob, "print.jpeg");
- }, "image/jpeg", 1);
- }
- e.cancel = true;
- setTimeout(function () {
- isPrinting = false;
- spread.unbind(GC.Spread.Sheets.Events.BeforePrint)
- }, 10)
- });
- isPrinting = true;
- spread.print();
- })
复制代码 打印预览:- $("#printPreview").click(function () {
- var json = spread.toJSON();
- var jsonStr = JSON.stringify(json);
- var newSpread = new GC.Spread.Sheets.Workbook();
- newSpread.fromJSON(JSON.parse(jsonStr));
- newSpread.bind(GC.Spread.Sheets.Events.BeforePrint, function (s, e) {
- var iframe = e.iframe;
- $("#previewFrame").html(iframe.contentWindow.document.body.innerHTML)
- //把得到的img存到list
- //list.push(iframe.contentWindow.document.getElementsByTagName("img")[0].src)
- e.cancel = true;
- setTimeout(function () {
- isPrinting = false;
- newSpread.unbind(GC.Spread.Sheets.Events.BeforePrint)
- }, 100)
- });
- $("#previewFrame").html("加载中!")
- $("#previewContent").show()
- isPrinting = true;
- //设置sheet的打印规则
- printSetting();
- setTimeout(function(){
- newSpread.print()
- },100)
- });
复制代码 完整Demo在附件当中,欢迎下载。
|
|