前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >aspose-words word转图片

aspose-words word转图片

作者头像
崔笑颜
发布2020-06-08 16:08:39
3.6K0
发布2020-06-08 16:08:39
举报

这里所用到的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 "转换成功";
	}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-08-12,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档