Java将富文本转化为word
2023-12-28 12:17:18
第一种(目前已经实现)
依赖
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.14.3</version>
</dependency>
wordUtils
package com.sunseagear.wind.modules.task.abc;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
/**
* poi操作word工具类
* @author lei
* @version 1.0
* @date 2022/11/14 10:23
*/
public class WordUtil {
/**
* 导出富文本内容到word
* @param request
* @param response
* @param content 输出内容
* @param fileName 导出文件名称
* @throws Exception
*/
public static void exportHtmlToWord(HttpServletRequest request, HttpServletResponse response, String content, String fileName) throws Exception {
//图片转为base64方法
//String imagebase64 = getImageStr(imagePath);
// 拼接html格式内容
StringBuffer sbf = new StringBuffer();
// 这里拼接一下html标签,便于word文档能够识别
sbf.append("<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\"" + //将版式从web版式改成页面试图
">");
sbf.append("<head>" +
"<!--[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>");
sbf.append("<body>");
// 富文本内容
sbf.append(content);
sbf.append("</body></html>");
// 必须要设置编码,避免中文就会乱码
byte[] b = sbf.toString().getBytes("GBK");
// 将字节数组包装到流中
ByteArrayInputStream bais = new ByteArrayInputStream(b);
POIFSFileSystem poifs = new POIFSFileSystem();
DirectoryEntry directory = poifs.getRoot();
// 这代码不能省略,否则导出乱码。
DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
//输出文件
request.setCharacterEncoding("utf-8");
// 导出word格式
response.setContentType("application/msword");
response.addHeader("Content-Disposition", "attachment;filename=" +
new String(fileName.getBytes("GB2312"),"iso8859-1") + ".doc");
ServletOutputStream ostream = response.getOutputStream();
poifs.writeFilesystem(ostream);
bais.close();
ostream.close();
}
/**
* 富文本内容到word(本地)
* @param content 输出内容
* @param fileName 导出文件名称
* @throws Exception
*/
public static void exportHtmlToWord(String filepath, String content, String fileName) throws Exception {
// 拼接html格式内容
StringBuffer sbf = new StringBuffer();
// 这里拼接一下html标签,便于word文档能够识别
sbf.append("<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\"" + //将版式从web版式改成页面试图
">");
sbf.append("<head>" +
"<!--[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>");
sbf.append("<body>");
// 富文本内容
sbf.append(content);
sbf.append("</body></html>");
// 必须要设置编码,避免中文就会乱码
byte[] b = sbf.toString().getBytes("GBK");
// 将字节数组包装到流中
ByteArrayInputStream bais = new ByteArrayInputStream(b);
POIFSFileSystem poifs = new POIFSFileSystem();
DirectoryEntry directory = poifs.getRoot();
// 这代码不能省略,否则导出乱码。
DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
FileOutputStream out = new FileOutputStream(new File(filepath+fileName));
poifs.writeFilesystem(out);
bais.close();
out.close();
}
}
ImageUtils
package com.sunseagear.wind.modules.task.abc;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;
import javax.imageio.ImageIO;
/**
* 图片处理工具类
* @author lei
* @date 2022/11/14 10:20
* @version 1.0
*/
public class ImageUtils {
/**
* 通过BufferedImage图片流调整图片大小
*/
public static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) throws IOException {
Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_AREA_AVERAGING);
BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
outputImage.getGraphics().drawImage(resultingImage, 0, 0, null);
return outputImage;
}
/**
* 返回base64图片
* @param data
* @return
*/
public static String imageToBase64(byte[] data) {
return Base64.getEncoder().encodeToString(data);
}
/**
* base64转换成byte数组
* @param base64
* @return
* @throws IOException
*/
public static byte[] base64ToByte(String base64) throws IOException {
return Base64.getDecoder().decode(base64);
}
/**
* BufferedImage图片流转byte[]数组
*/
public static byte[] imageToBytes(BufferedImage bImage) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(bImage, "png", out);
return out.toByteArray();
}
/**
* byte[]数组转BufferedImage图片流
*/
public static BufferedImage bytesToBufferedImage(byte[] ImageByte) throws IOException {
ByteArrayInputStream in = new ByteArrayInputStream(ImageByte);
return ImageIO.read(in);
}
//图片转化成base64字符串
public static String getImageStr(String imgPath) throws IOException {
File file = new File(imgPath);
if (!file.exists()) {
文章来源:https://blog.csdn.net/weixin_45816407/article/details/135250672
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!