JS截取网页转PDF,导出为Word.

1.导出PDF

引入JS

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/html2canvas/0.5.0-beta4/html2canvas.js"></script>

定义截取的div

<div class="layuimini-container" id="echartsCavans" ref="echartsCavans"></div>

点击截取

 <button type="button" hidden onclick="ExportPDF('echartsCavans')" id="button1" >导出</button>

截取的JS

function OverPDF(id) {
        // api.openLoad();
        layer.open({ type: 3, icon: 6 });
        html2canvas($("#" + id), {
            allowTaint: true,//允许跨域
            height: $("#" + id).scrollHeight,//
            width: $("#" + id).scrollWidth,//为了使横向滚动条的内容全部展示,这里必须指定
            background: "#FFFFFF",//如果指定的div没有设置背景色会默认成黑色,这里是个坑
            onrendered: function (canvas) {
                var contentWidth = canvas.width;
                var contentHeight = canvas.height;

                //一页pdf显示html页面生成的canvas高度;
                var pageHeight = contentWidth / 595.28 * 841.89;
                //未生成pdf的html页面高度
                var leftHeight = contentHeight;
                //pdf页面偏移
                var position = 0;
                //a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
                var imgWidth = 555.28;
                var imgHeight = 555.28 / contentWidth * contentHeight;

                var pageData = canvas.toDataURL('image/jpeg', 1.0);
                console.log("生成图片");

                var pdf = new jsPDF('', 'pt', 'a4');
                //有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
                //当内容未超过pdf一页显示的范围,无需分页
                if (leftHeight < pageHeight) {
                    pdf.addImage(pageData, 'JPEG', 20, 0, imgWidth, imgHeight);
                } else {
                    while (leftHeight > 0) {
                        pdf.addImage(pageData, 'JPEG', 20, position, imgWidth, imgHeight)
                        leftHeight -= pageHeight;
                        position -= 841.89;
                        //避免添加空白页
                        if (leftHeight > 0) {
                            pdf.addPage();
                        }
                    }
                }
                // api.closeLoad();
                layer.close(layer.index);//关闭遮罩层
                var names = $("#titles-zc").text();
                pdf.save(`${names}.pdf`);
            }
        })

    }

原文地址: https://blog.csdn.net/qq_39280563/article/details/121604227

2.导出Word

先创建两个JS:
1.FileSaver.min.js

(function (a, b) { if ("function" == typeof define && define.amd) define([], b); else if ("undefined" != typeof exports) b(); else { b(), a.FileSaver = { exports: {} }.exports } })(this, function () { "use strict"; function b(a, b) { return "undefined" == typeof b ? b = { autoBom: !1 } : "object" != typeof b && (console.warn("Deprecated: Expected third argument to be a object"), b = { autoBom: !b }), b.autoBom && /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(a.type) ? new Blob(["\uFEFF", a], { type: a.type }) : a } function c(a, b, c) { var d = new XMLHttpRequest; d.open("GET", a), d.responseType = "blob", d.onload = function () { g(d.response, b, c) }, d.onerror = function () { console.error("could not download file") }, d.send() } function d(a) { var b = new XMLHttpRequest; b.open("HEAD", a, !1); try { b.send() } catch (a) { } return 200 <= b.status && 299 >= b.status } function e(a) { try { a.dispatchEvent(new MouseEvent("click")) } catch (c) { var b = document.createEvent("MouseEvents"); b.initMouseEvent("click", !0, !0, window, 0, 0, 0, 80, 20, !1, !1, !1, !1, 0, null), a.dispatchEvent(b) } } var f = "object" == typeof window && window.window === window ? window : "object" == typeof self && self.self === self ? self : "object" == typeof global && global.global === global ? global : void 0, a = f.navigator && /Macintosh/.test(navigator.userAgent) && /AppleWebKit/.test(navigator.userAgent) && !/Safari/.test(navigator.userAgent), g = f.saveAs || ("object" != typeof window || window !== f ? function () { } : "download" in HTMLAnchorElement.prototype && !a ? function (b, g, h) { var i = f.URL || f.webkitURL, j = document.createElement("a"); g = g || b.name || "download", j.download = g, j.rel = "noopener", "string" == typeof b ? (j.href = b, j.origin === location.origin ? e(j) : d(j.href) ? c(b, g, h) : e(j, j.target = "_blank")) : (j.href = i.createObjectURL(b), setTimeout(function () { i.revokeObjectURL(j.href) }, 4E4), setTimeout(function () { e(j) }, 0)) } : "msSaveOrOpenBlob" in navigator ? function (f, g, h) { if (g = g || f.name || "download", "string" != typeof f) navigator.msSaveOrOpenBlob(b(f, h), g); else if (d(f)) c(f, g, h); else { var i = document.createElement("a"); i.href = f, i.target = "_blank", setTimeout(function () { e(i) }) } } : function (b, d, e, g) { if (g = g || open("", "_blank"), g && (g.document.title = g.document.body.innerText = "downloading..."), "string" == typeof b) return c(b, d, e); var h = "application/octet-stream" === b.type, i = /constructor/i.test(f.HTMLElement) || f.safari, j = /CriOS\/[\d]+/.test(navigator.userAgent); if ((j || h && i || a) && "undefined" != typeof FileReader) { var k = new FileReader; k.onloadend = function () { var a = k.result; a = j ? a : a.replace(/^data:[^;]*;/, "data:attachment/file;"), g ? g.location.href = a : location = a, g = null }, k.readAsDataURL(b) } else { var l = f.URL || f.webkitURL, m = l.createObjectURL(b); g ? g.location = m : location.href = m, g = null, setTimeout(function () { l.revokeObjectURL(m) }, 4E4) } }); f.saveAs = g.saveAs = g, "undefined" != typeof module && (module.exports = g) });

//# sourceMappingURL=FileSaver.min.js.map

2.jquery.wordexport.js

if (typeof jQuery !== 'undefined' && typeof saveAs !== 'undefined') {
    ; (function ($) {
        $.fn.wordExport = function (fileName) {
            fileName =
                typeof fileName !== 'undefined' ? fileName : 'jQuery-Word-Export'
            var static = {
                // mhtml: {
                //   top:
                //     'Mime-Version: 1.0\nContent-Base: ' +
                //     location.href +
                //     '\nContent-Type: Multipart/related; boundary="NEXT.ITEM-BOUNDARY";type="text/html"\n\n--NEXT.ITEM-BOUNDARY\nContent-Type: text/html; charset="utf-8"\nContent-Location: ' +
                //     location.href +
                //     '\n\n<!DOCTYPE html>\n<html>\n_html_</html>',
                //   head:
                //     '<head>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n<style>\n_styles_\n</style>\n</head>\n',
                //   body: '<body>_body_</body>'
                // }
                mhtml: {
                    top:
                        'Mime-Version: 1.0\nContent-Base: ' +
                        location.href +
                        '\nContent-Type: Multipart/related; boundary="NEXT.ITEM-BOUNDARY";type="text/html"\n\n--NEXT.ITEM-BOUNDARY\nContent-Type: text/html; charset="utf-8"\nContent-Location: ' +
                        location.href +
                        '\n\n<!DOCTYPE html>\n' +
                        '<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" xmlns="http://www.w3.org/TR/REC-html40">\n_html_</html>',
                    head:
                        '<head>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n<style>\n_styles_\n</style>\n<!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:TrackMoves>false</w:TrackMoves><w:TrackFormatting/><w:ValidateAgainstSchemas/><w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid><w:IgnoreMixedContent>false</w:IgnoreMixedContent><w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText><w:DoNotPromoteQF/><w:LidThemeOther>EN-US</w:LidThemeOther><w:LidThemeAsian>ZH-CN</w:LidThemeAsian><w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript><w:Compatibility><w:BreakWrappedTables/><w:SnapToGridInCell/><w:WrapTextWithPunct/><w:UseAsianBreakRules/><w:DontGrowAutofit/><w:SplitPgBreakAndParaMark/><w:DontVertAlignCellWithSp/><w:DontBreakConstrainedForcedTables/><w:DontVertAlignInTxbx/><w:Word11KerningPairs/><w:CachedColBalance/><w:UseFELayout/></w:Compatibility><w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel><m:mathPr><m:mathFont m:val="Cambria Math"/><m:brkBin m:val="before"/><m:brkBinSub m:val="--"/><m:smallFrac m:val="off"/><m:dispDef/><m:lMargin m:val="0"/> <m:rMargin m:val="0"/><m:defJc m:val="centerGroup"/><m:wrapIndent m:val="1440"/><m:intLim m:val="subSup"/><m:naryLim m:val="undOvr"/></m:mathPr></w:WordDocument></xml><![endif]--></head>\n',
                    body: '<body>_body_</body>'
                }
            }
            var options = {
                maxWidth: 624
            }
            // Clone selected element before manipulating it
            var markup = $(this).clone()

            // Remove hidden elements from the output
            markup.each(function () {
                var self = $(this)
                if (self.is(':hidden')) self.remove()
            })

            // Embed all images using Data URLs
            var images = Array()
            var img = markup.find('img')
            for (var i = 0; i < img.length; i++) {
                // Calculate dimensions of output image
                var w = Math.min(img[i].width, options.maxWidth)
                var h = img[i].height * (w / img[i].width)
                // var w = '200'
                // var h = '100'
                // Create canvas for converting image to data URL
                var canvas = document.createElement('CANVAS')
                canvas.width = w
                canvas.height = h
                // Draw image to canvas
                var context = canvas.getContext('2d')
                context.drawImage(img[i], 0, 0, w, h)
                // Get data URL encoding of image
                var uri = canvas.toDataURL('image/png')
                $(img[i]).attr('src', img[i].src)
                img[i].width = w
                img[i].height = h
                // Save encoded image to array
                images[i] = {
                    type: uri.substring(uri.indexOf(':') + 1, uri.indexOf(';')),
                    encoding: uri.substring(uri.indexOf(';') + 1, uri.indexOf(',')),
                    location: $(img[i]).attr('src'),
                    data: uri.substring(uri.indexOf(',') + 1)
                }
            }

            // Prepare bottom of mhtml file with image data
            var mhtmlBottom = '\n'
            for (var i = 0; i < images.length; i++) {
                mhtmlBottom += '--NEXT.ITEM-BOUNDARY\n'
                mhtmlBottom += 'Content-Location: ' + images[i].location + '\n'
                mhtmlBottom += 'Content-Type: ' + images[i].type + '\n'
                mhtmlBottom +=
                    'Content-Transfer-Encoding: ' + images[i].encoding + '\n\n'
                mhtmlBottom += images[i].data + '\n\n'
            }
            mhtmlBottom += '--NEXT.ITEM-BOUNDARY--'

            //TODO: load css from included stylesheet
            var styles = ''

            // Aggregate parts of the file together
            var fileContent =
                static.mhtml.top.replace(
                    '_html_',
                    static.mhtml.head.replace('_styles_', styles) +
                    static.mhtml.body.replace('_body_', markup.html())
                ) + mhtmlBottom

            // Create a Blob with the file contents
            var blob = new Blob([fileContent], {
                type: 'application/msword;charset=utf-8'
            })
            saveAs(blob, fileName + '.doc')
        }
    })(jQuery)
} else {
    if (typeof jQuery === 'undefined') {
        console.error('jQuery Word Export: missing dependency (jQuery)')
    }
    if (typeof saveAs === 'undefined') {
        console.error('jQuery Word Export: missing dependency (FileSaver.js)')
    }
}

引入到上述代码中后,在上述代码中加入一个按钮。按钮引入事件:

 function Word()
    {
        var dt = $("#echartsCavans").html();

        $(dt).wordExport('word名称');
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值