前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >aspose-words java word 转换 服务器乱码解决 - 崔笑颜的博客

aspose-words java word 转换 服务器乱码解决 - 崔笑颜的博客

作者头像
崔笑颜
发布2021-02-02 18:03:46
3.6K0
发布2021-02-02 18:03:46
举报

在本机测试是好的 但是到服务器就乱码 想到pdf是一种为打印设计的文档格式,可能跟字体相关。而且转出来的pdf中文都是空心方框,不是单纯的乱码,很有可能是缺少字体渲染不出来造成的。 服务器上用fc-list命令查看字体,果然没有中文字体 接下来将本机Windows的字体上传到CentOS服务器上。 具体操作: 也可以直接使用我的字体 经测试没问题 有的系统版本的原因 也会导致乱码 链接: https://pan.baidu.com/s/1Fj6pqfNDi__sdBJthdFCFg 提取码: k35v 将Windows上字体文件 C:\Windows\Fonts目录,复制到CentOS的/usr/share/fonts目录 重启服务器

如果你转换的文档中有 公式系列的话 那么还需要再导入一种公式字体 这里已经准备好啦 链接: https://pan.baidu.com/s/1c8WYZMcqVeRHc23vVe3xrQ 提取码: c329

同样需要重启服务器

已知问题 着重号无法转换 官网也为给出解决方案

aspose-words word转图片

这里所用到的jar包 和这里所用的的一样 jar包下载 和谐文件 将word转换为单张图片

代码语言:javascript
复制
 
	// 将word 转化为图片一张
	public static String parseFileToBase64_PNG(String wordfile) throws Exception {
 
		//文件流
		InputStream inputStream = new FileInputStream(wordfile);
		//文件 获取文件名字
		File file = new File(wordfile);
		String name = file.getName();
		//截取不带后缀名的字段
		String fileName = name.substring(0, name.lastIndexOf("."));
 
		//文件上传路径
		String parent = file.getParent();
 
		List<BufferedImage> bufferedImages = new ArrayList<BufferedImage>();
		BufferedImage image = null;
			bufferedImages = wordToImg(inputStream);
			image = MergeImage.mergeImage(false, bufferedImages);
 
		boolean png = ImageIO.write(image, "png", new File(parent + "/" + fileName + ".png"));// 写入流中
 
 
		if(png == false){
			return "转换失败";
		}
 
		//关闭流
		inputStream.close();
		return "转换成功";
	}
 
/**
	 * @Description: word和txt文件转换图片
	 */
	private static List<BufferedImage> wordToImg(InputStream inputStream) throws Exception {
		if (!isWordLicense()) {
			return null;
		}
 
		try {
 
			Document doc = new Document(inputStream);
			ImageSaveOptions options = new ImageSaveOptions(SaveFormat.PNG);
			options.setPrettyFormat(true);
			options.setUseAntiAliasing(true);
			options.setUseHighQualityRendering(true);
			int pageCount = doc.getPageCount();
 
			List<BufferedImage> imageList = new ArrayList<BufferedImage>();
			for (int i = 0; i < pageCount; i++) {
				OutputStream output = new ByteArrayOutputStream();
				options.setPageIndex(i);
 
				doc.save(output, options);
				ImageInputStream imageInputStream = ImageIO.createImageInputStream(parse(output));
				imageList.add(ImageIO.read(imageInputStream));
			}
			return imageList;
 
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}
 
/**
	 * @Description: 验证aspose.word组件是否授权:无授权的文件有水印和试用标记
	 */
	public static boolean isWordLicense() {
		boolean result = false;
		try {
			// InputStream inputStream = new
			// FileInputStream("D:\\Workspaces\\TestFilters\\lib\\license.xml");
			// 避免文件遗漏
			String licensexml = "<License>\n" + "<Data>\n" + "<Products>\n"
					+ "<Product>Aspose.Total for Java</Product>\n" + "<Product>Aspose.Words for Java</Product>\n"
					+ "</Products>\n" + "<EditionType>Enterprise</EditionType>\n"
					+ "<SubscriptionExpiry>20991231</SubscriptionExpiry>\n"
					+ "<LicenseExpiry>20991231</LicenseExpiry>\n"
					+ "<SerialNumber>23dcc79f-44ec-4a23-be3a-03c1632404e9</SerialNumber>\n" + "</Data>\n"
					+ "<Signature>\n"
					+ "sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=\n"
					+ "</Signature>\n" + "</License>";
			InputStream inputStream = new ByteArrayInputStream(licensexml.getBytes());
			com.aspose.words.License license = new com.aspose.words.License();
			license.setLicense(inputStream);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
 
// outputStream转inputStream
	public static ByteArrayInputStream parse(OutputStream out) throws Exception {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		baos = (ByteArrayOutputStream) out;
		ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
		return swapStream;
	}
 

新建一个工具类

代码语言:javascript
复制
package util;
 
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
 
/**
 * @program: transformation
 * @description: 多张图片合成
 * @author: cuixy
 * @create: 2019-07-26 17:10
 **/
public class MergeImage {
 
    /**
     * 合并任数量的图片成一张图片
     *
     * @param isHorizontal
     *            true代表水平合并,fasle代表垂直合并
     * @param imgs
     *            待合并的图片数组
     * @return
     * @throws IOException
     */
    public static BufferedImage mergeImage(boolean isHorizontal, List<BufferedImage> imgs) throws IOException {
        // 生成新图片
        BufferedImage destImage = null;
        // 计算新图片的长和高
        int allw = 0, allh = 0, allwMax = 0, allhMax = 0;
        // 获取总长、总宽、最长、最宽
        for (int i = 0; i < imgs.size(); i++) {
            BufferedImage img = imgs.get(i);
            allw += img.getWidth();
 
            if (imgs.size() != i + 1) {
                allh += img.getHeight() + 2;
            } else {
                allh += img.getHeight();
            }
 
            if (img.getWidth() > allwMax) {
                allwMax = img.getWidth();
            }
 
            if (img.getHeight() > allhMax) {
                allhMax = img.getHeight();
            }
        }
 
        // 创建新图片
        if (isHorizontal) {
            destImage = new BufferedImage(allw, allhMax, BufferedImage.TYPE_INT_RGB);
        } else {
            destImage = new BufferedImage(allwMax, allh, BufferedImage.TYPE_INT_RGB);
        }
 
        // 注释,分隔线从灰色变成纯黑
        // Graphics2D g2 = (Graphics2D) destImage.getGraphics();
        // g2.setBackground(Color.LIGHT_GRAY);
        // g2.clearRect(0, 0, allw, allh);
        // g2.setPaint(Color.RED);
 
        // 合并所有子图片到新图片
        int wx = 0, wy = 0;
        for (int i = 0; i < imgs.size(); i++) {
            BufferedImage img = imgs.get(i);
            int w1 = img.getWidth();
            int h1 = img.getHeight();
            // 从图片中读取RGB
            int[] ImageArrayOne = new int[w1 * h1];
            ImageArrayOne = img.getRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 逐行扫描图像中各个像素的RGB到数组中
            if (isHorizontal) { // 水平方向合并
                destImage.setRGB(wx, 0, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
            } else { // 垂直方向合并
                destImage.setRGB(0, wy, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
            }
 
            wx += w1;
            wy += h1 + 2;
        }
        return destImage;
    }
 
 
 
}

将word转换为单页 每页为一张图片

代码语言:javascript
复制
/**
	 * word 转每页pdf
	 * @param wordfile
	 * @return
	 * @throws Exception
	 */
	public static String parseFileToBase64_PNG1(String wordfile) throws Exception {
 
		if (!isWordLicense()) {
			return null;
		}
 
		// 声明一个
		InputStream inputStream = new FileInputStream(wordfile);
 
 
 
		//文件 获取文件名字
		File file = new File(wordfile);
		String name = file.getName();
		//截取不带后缀名的字段
		String fileName = name.substring(0, name.lastIndexOf("."));
		//文件上传路径
		String parent = file.getParent();
 
		//创建同名文件夹
		new File(parent+"/"+ fileName).mkdir();
 
		List<BufferedImage> bufferedImages = wordToImg1(inputStream);
 
		for (int i = 0; i < bufferedImages.size(); i++){
			ImageIO.write(bufferedImages.get(i), "png", new File(parent +"/"+ fileName +"/"+ "第"+ i +"页" + fileName + ".png"));
		}
 
 
		
 
		//关闭流
		inputStream.close();
 
 
		return "转换成功";
	}

图片转换为base64 前台预览

业务需求 word转换成在线预览 结合这里是word转图片 也可以直接转换为在线预览

代码语言:javascript
复制
public static String parseFileToBase64_PNG1(InputStream inputStream, int pageNum) throws Exception {
		// String png_base64 = "";
		List<BufferedImage> bufferedImages = new ArrayList<BufferedImage>();
		BufferedImage image = null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();// io流
		bufferedImages = wordToImg1(inputStream, pageNum);
		image = mergeImage(false, bufferedImages);
		ImageIO.write(image, "png", baos);// 写入流中
 
		byte[] bytes = baos.toByteArray();// 转换成字节
		BASE64Encoder encoder = new BASE64Encoder();
		String png_base64 = encoder.encodeBuffer(bytes).trim();// 转换成base64串
		png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");// 删除
		
		return png_base64;
	}

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021年1月16日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • aspose-words word转图片
  • 图片转换为base64 前台预览
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档