java 富文本html 转 word(带图片处理

 
1.配置依赖
<dependency>
   <groupId>e-iceblue</groupId>
   <artifactId>spire.doc.free</artifactId>
   <version>3.9.0</version>
</dependency>
<dependency>
   <groupId>org.jsoup</groupId>
   <artifactId>jsoup</artifactId>
   <version>1.14.2</version>
</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.13</version>
		</dependency>
因e-iceblue在阿里云maven仓库中找不到,需配置特定仓库

<repository>
   <id>com.e-iceblue</id>
   <url>https://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
2.代码demo
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Base64;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class TestHtml2Doc {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        String str="";
        try {
			//富文本内容在本地文件中,根据具体情况改成从数据库或网络中获取资源
            FileInputStream in=new FileInputStream("D:\\oo.txt");
            // size 为字串的长度 ,这里一次性读完
            int size=in.available();
            byte[] buffer=new byte[size];
            in.read(buffer);
            in.close();
            str=new String(buffer,"utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        org.jsoup.nodes.Document document = Jsoup.parse(str);

        Element body = document.body();
        // 获取body里面的所有子元素
        Elements links = body.children();
        try {
            for (Element link : links) {
                Elements img = link.select("img");
                String src = img.attr("src");
                if(StringUtils.isNotBlank(src) ) {
                    // 处理图片 因有些图片资源带有防盗链,需加上Referer
                    Map map=new HashMap() ;
                    map.put("Referer","http://aa.com.cn");

                    String string=doGetHeader(src,map);
                    img.attr("src","data:image/png;base64,"+string);
                    System.out.println("src = " + src);
                    System.out.println("Basestring = " + string);

                }
            }
        } catch (Exception e) {
            System.out.println("转换url图片报错了:"+e.getMessage());
        }

        String html = document.html();
		//样式调整
        html=html.replace("class=\"ql-align-center\"","style=\"text-align:center\"").replace("<br></p>\n" +
                "  <p>","<br></p>\n" +
                "  <p>&emsp;&emsp;");
        //System.out.println("html = " + html);
        exportWord(html,"590");
        long end = System.currentTimeMillis();
        System.out.println("(end-start) = " + (end-start)/1000);
    }
    public static void exportWord( String content, String fileName) {

        try {
            HttpServletRequest request=null;
            HttpServletResponse response=null;
            //新建Document对象
            Document document = new Document();
            //添加section
            Section sec = document.addSection();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            //添加段落并写入HTML文本
            sec.addParagraph().appendHTML(content);
            document.saveToStream(os, FileFormat.Docx);

            InputStream input = new ByteArrayInputStream(os.toByteArray());

            //输出文件
            FileOutputStream no=new FileOutputStream("D:\\"+fileName+".docx");
            int len =-1;
            byte []by = new byte[1024];
            while((len = input.read(by))!=-1) {
                no.write(by,0,len);
            }
            no.flush();
            no.close();
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * @Description HTTP header GET请求图片地址 返回base64
     * @param url 地址
     * @param
     */
    public static String doGetHeader(String url, Map<String, String> headers) {

        CloseableHttpResponse response = null;
        try (CloseableHttpClient client = HttpClients.createDefault()){
            HttpGet httpGet = new HttpGet(url);
            Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
            //设置header信息
            while(iterator.hasNext()) {
                Map.Entry<String, String> entry = iterator.next();
                httpGet.setHeader(entry.getKey(), entry.getValue());
            }
            RequestConfig config = RequestConfig.custom().setConnectTimeout(60000)
                    .setConnectionRequestTimeout(60000)
                    .setSocketTimeout(60000)
                    .build();
            httpGet.setConfig(config);
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            entity.writeTo(out);
            // ByteArrayOutputStream编码成base64字符串
            String result = new String(Base64.getEncoder().encode(out.toByteArray()));
            return result;
        }catch(Exception e) {
            System.out.println("httpClient请求图片url报错 " + e.getMessage());;
            return null;
        }finally {
            try {
                if(response != null) {
                    response.close();
                }
            }catch(Exception e) {
                System.out.println("关闭响应流报错:"+e.getMessage());
            }
        }
    }
}

  • 6
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java中可以通过Apache POI库来操作Word文档,通过读取Word文档中的内容,可以将其换为富文本格式并携图片。 具体步骤如下: 1. 使用Apache POI读取Word文档,获取文档中的内容。 2. 使用Java的Rich Text Format (RTF)类库将Word文档内容换为RTF格式。 3. 在RTF文本中插入图片,可以使用图片的Base64编码将图片插入到文本中。 4. 将得到的RTF文本保存为文件或者直接将其返回给调用者。 下面是一个简单的示例代码,用于将Word文档换为RTF格式并插入图片: ```java import java.io.*; import org.apache.poi.xwpf.usermodel.*; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import javax.imageio.stream.ImageInputStream; import java.io.ByteArrayOutputStream; public class WordToRTFConverter { public static void main(String[] args) throws Exception { // 读取Word文档内容 XWPFDocument docx = new XWPFDocument(new FileInputStream("example.docx")); XWPFWordExtractor ex = new XWPFWordExtractor(docx); String text = ex.getText(); // 将Word文档内容换为RTF格式 RTFEditorKit rtf = new RTFEditorKit(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); rtf.write(baos, docx, 0, docx.getNumberOfParagraphs()); // 在RTF文本中插入图片 BufferedImage image = ImageIO.read(new File("example.png")); ByteArrayOutputStream imageOutput = new ByteArrayOutputStream(); ImageIO.write(image, "png", imageOutput); String imageData = new String(Base64.getEncoder().encode(imageOutput.toByteArray())); String rtfText = new String(baos.toByteArray(), "UTF-8"); rtfText = rtfText.replace("}", "{\\pict\\pngblip\\picw" + image.getWidth() + "\\pich" + image.getHeight() + "\\picwgoal" + (image.getWidth() * 15) + "\\pichgoal" + (image.getHeight() * 15) + "\n" + imageData + "}"); // 保存为RTF文件 FileOutputStream out = new FileOutputStream("example.rtf"); out.write(rtfText.getBytes()); out.close(); } } ``` 请注意,上述示例代码只是一个简单的示例,实际应用中可能会有更多的细节需要处理。例如,需要处理Word文档中的表格、段落样式等内容,以确保换结果符合预期。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

softwareDragon

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值