HTML转word_怎么把docx转换成word

HTML转word_怎么把docx转换成word在做项目时,要将富文本编辑器,或是html内容导出为word。先引入文件保存js<scriptsrc=”FileSaver.js”></script>导出为Docxdocx体积更小,而且word2007也可以打开1.引用插件html-docx.js<scriptsrc=”html-docx.js”></script>2.构建完整的html内容文档varcontent='<!DOCTYPEhtml&gt

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

在做项目时,要将富文本编辑器,或是html内容 导出为word。

先引入文件保存js

<script src="FileSaver.js"></script>

方法一

使用 html-docx.js、FileSaver.js 文件

导出为Docx
docx体积更小,而且word2007也可以打开

1.引用插件html-docx.js

<script src="html-docx.js"></script>

2.构建完整的html内容文档

var content = '<!DOCTYPE html><html><head><meta charset="UTF-8"></head>'+ 要导出的html信息 +'</html>

content要导出的html信息,建议在服务端自己拼接完成。

若是想从页面抓取html信息,可以用下面的方法(不建议,客户端消耗高)

html:

<div id="content">
    要导出的html信息
    <img src="xxx">
</div>
 
function convertImagesToBase64 (content) {
      var regularImages = content.querySelectorAll("img");
      var canvas = document.createElement('canvas');
      var ctx = canvas.getContext('2d');
      [].forEach.call(regularImages, function (imgElement) {
        // preparing canvas for drawing
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        canvas.width = imgElement.width;
        canvas.height = imgElement.height;
 
        ctx.drawImage(imgElement, 0, 0);
        // by default toDataURL() produces png image, but you can also export to jpeg
        // checkout function's documentation for more details
        var dataURL = canvas.toDataURL();
        imgElement.setAttribute('src', dataURL);
      })
      canvas.remove();
    }
var content = document.getElementById('#content');
convertImagesToBase64(content);//转换图片为base64
 
content = '<!DOCTYPE html><html><head><meta charset="UTF-8"></head>'+ content +'</html>'

3.利用脚本导出word

 var converted = htmlDocx.asBlob(content);
 saveAs(converted, 'test.docx');// 用 FielSaver.js里的保存方法 进行输出

方法二

导出为Doc

使用 html-docx.js、FileSaver.js 、wordexport文件

1.引入jquery和wordexport

<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script src="wordexport.js"></script>

2.使用导出

$(元素).wordExport(文件名,isBase64)

isBase64 用于标识 元素中的图片是否都处理为了base64,默认为false,内置处理方法,可以去看看

注意

无论是html-docx.js还是 wordexport.js 都需要将html中的图片转为base64形式

而且,图片的宽度高,最好自己设置下,否则下载的图片会以图片原始大小下载,就会出现以下,图片在文档超出情况

HTML转word_怎么把docx转换成word

处理图片的宽高,可以采用 正则替换,这里给出两种替换参考(平时不太写正则,所以有点挫)

C#:

string reg = "<img.*? src=[\"'](.*?)['\"].*?>";
MatchCollection collections = Regex.Matches(description, reg);
if (collections.Count > 0)
{
    foreach (Match match in collections)
    {
        Regex regWidth = new Regex("width\\s*=\\s*\\S+ ");
        if (!regWidth.IsMatch(img))//img 中不存在width 
        {
            //获取其他属性进行替换
            Regex reg1 = new Regex(@"style\s*=(['""\s]?)[^'""]*?\1"); ;
            img = reg1.Replace(img, "width=\"350\" height=\"216\" ");//按黄金比例替换
        }
        else
        {
            Match mathWidth = regWidth.Match(img);
            if (mathWidth.Success)
            {
                string widh = mathWidth.Value.Substring(7).Substring(0, mathWidth.Value.Substring(7).Length - 2);//width
                if (int.Parse(widh) > 400) {//原宽超出400
                    Regex regHeight = new Regex(@"height\s*=(['""\s]?)[^'""]*?\1");
                    Match mathHeight = regHeight.Match(img);
                    if (mathHeight.Success)
                    {
                        string height = mathHeight.Value.Substring(8).Substring(0, mathHeight.Value.Substring(8).Length - 1);
                        img = regHeight.Replace(img, "height=\" " + 350 * int.Parse(height) / int.Parse(widh) + "\"");//按比例替换 高
                    }
                    img = regWidth.Replace(img, "width=\"350\"");
                }
            }
        }
    }
}

若是二进制流存储的图片数据,可以通过Bitmp来读取原始大小 ,然后按照原始比例再进行缩放


//通过二进制流 获取图片原始宽高
private int[] GetScaleImgSizeByByte(byte[] image)
{
    MemoryStream stream = new MemoryStream(image);//内存流写入
    Bitmap bmp = new Bitmap(stream);
    int width = 600;//先指定一个固定大小 和word页面边距最大宽差不多
    int height = 600;
    if (bmp.Width > 600)
    {
        height = (int)(width * ((double)bmp.Height / (double)bmp.Width));
    }
    if (height > 600 || bmp.Height > 600)
    {//调完宽后判断高 
        height = 600;
        width = (int)(height / ((double)bmp.Height / (double)bmp.Width));
    }
    return new int[] { width, height };
}

js正则替换:

 var str = htmlText.replace(/(<img[^>]*)(\/?>)/gi, function (match, capture) {
     if(match.match(/width\s*?=\s*?([‘"])[\s\S]*?\1/ig)==null)
     match = match.replace(/(<img[^>]*)(\/?>)/gi,"$1 width='350' $2")//没有宽就增加宽
     return match.replace(/style\s*?=\s*?([‘"])[\s\S]*?\1/ig, '').replace(/width\s*?=\s*?([‘"])[\s\S]*?\1/ig ,"width='350'");
});

方式三   使用poi 

经过调研使用各种方式之后发现这种方法应该是对样式复杂的报告是最切合的
提供poi封装脚手架函数 Poi-tl Documentation

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/182859.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • RPC是什么? (学习笔记)

    RPC是什么? (学习笔记)什么是RPC?RPC全称RemoteProcedureCall,即远程过程调用,就是要像调用本地的函数一样去调远程函数,屏蔽远程调用的复杂性。为什么需要RPC?微服务、分布式应用的开发越来越

    2022年8月3日
    10
  • Linux 解压zip命令「建议收藏」

    Linux 解压zip命令「建议收藏」linux自带的unzip命令可以解压windows下的zip格式的压缩文件。unzip命令  语法:unzip[选项]压缩文件名.zip  各选项的含义分别为:  -x文件列表解压缩文件,但不包括指定的file文件。  -v查看压缩文件目录,但不解压。  -t测试文件有无损坏,但不解压。  -d目录把压缩文件解到指定目录下。  -z只显示压缩文件

    2022年5月23日
    44
  • spring ioc源码解析_spring事务源码深度解析

    spring ioc源码解析_spring事务源码深度解析SpringApplication源码解析运行SpringApplication的方式在创建SpringBoot应用,我们经常看到SpringApplication.run(ApplicationConfiguration.class,args);那有没有其他方式可以运行SpringApplication,答案是有的。我们可以通过自定义SpringApplication来实现Sprin…

    2022年9月9日
    4
  • awvs扫描器原理_条形码扫描器现在无法使用

    awvs扫描器原理_条形码扫描器现在无法使用AWVSAWVS(WebVulnerabilityScanner)是一个自动化的Web应用程序安全测试工具,它可以扫描任何可通过Web浏览器访问的和遵循HTTP/HTTPS规则的Web站点和Web应用程序。适用于任何中小型和大型企业的内联网、外延网和面向客户、雇员、厂商和其它人员的Web网站。WVS可以通过检查SQL注入攻击漏洞、XSS跨站脚本攻击漏洞等漏洞来审核Web应用程序的安全性。AWVS功能介绍WebScanner:核心功能,web安全漏洞扫描(深度,宽度,限制20个)Site

    2022年9月22日
    3
  • intellij idea 怎么查看方法在哪里被调用_进入接口

    intellij idea 怎么查看方法在哪里被调用_进入接口在接口的左边有个向下的小箭头,点击小箭头就能看到接口的实现类和方法的实现:在实现类的左边有个向上的小箭头,可以查看被实现的接口和被覆盖重写的方法:

    2022年8月15日
    13
  • URAL 1018 Binary Apple Tree

    URAL 1018 Binary Apple Tree

    2021年8月18日
    93

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号