自学内容网 自学内容网

页面上的内容的生成图片后,保存为word,并下载

页面上的内容的生成图片后,保存为word,并下载 juqery

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Download Page Screenshot as Word</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.3.2/html2canvas.min.js"></script>
</head>
<body>
    <div id="content-to-capture">
        <!-- This is the content you want to capture -->
        <h1>Hello, World!</h1>
        <p>This is an example paragraph.</p>
    </div>
    <button id="downloadWord">Download Word</button>
    <script>
        $(document).ready(function() {
            $('#downloadWord').click(function() {
                html2canvas(document.getElementById('content-to-capture')).then(function(canvas) {
                    // Convert canvas to data URL
                    const dataUrl = canvas.toDataURL('image/png');

                    // Create a Blob from the data URL
                    const byteString = atob(dataUrl.split(',')[1]);
                    const mimeString = dataUrl.split(',')[0].split(':')[1].split(';')[0];
                    const ab = new ArrayBuffer(byteString.length);
                    const ia = new Uint8Array(ab);
                    for (let i = 0; i < byteString.length; i++) {
                        ia[i] = byteString.charCodeAt(i);
                    }
                    const blob = new Blob([ab], {type: mimeString});

                    // Generate a simple .doc file content
                    const content = `
                        <html xmlns:o='urn:schemas-microsoft-com:office:office' 
                              xmlns:w='urn:schemas-microsoft-com:office:word' 
                              xmlns='http://www.w3.org/TR/REC-html40'>
                        <head><meta charset='utf-8'><title>Export HTML to Word Document with JavaScript</title></head>
                        <body>
                            <img src='${dataUrl}' />
                        </body>
                        </html>
                    `;

                    // Create a Blob for the .doc file
                    const docBlob = new Blob(['\ufeff', content], {type: 'application/msword'});

                    // Save the Blob as a file
                    saveAs(docBlob, 'document.doc');
                });
            });
        });
    </script>
</body>
</html>


原文地址:https://blog.csdn.net/weixin_40597855/article/details/143507341

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!