使用java将word文档docx,doc(包含图形,文本框,图片等)完美转换成所有格式图片(pdf,png,gif,jpeg等等)下文中附带代码,效果图等

  • 思路
    • 使用到的包
    • 实现代码
    • 效果图:

思路

使用jacob将docx转换成doc,用openoffice将doc转成pdf,最后是用pdfbox将pdf转成任意格式图片

使用到的包

https://download.csdn.net/download/weixin_44396516/11393966

实现代码

把上面的包下载并导入,代码中有些内容自行修改,有问题请留言,看到会回复。

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.tools.imageio.ImageIOUtil;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.model.PAPX;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.converter.core.BasicURIResolver;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.w3c.dom.Document;import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;public class POIWordToPng {/*** 使用jacob进行Word文档格式互转(例:doc2docx、docx2doc)* * @author Harley Hong* @created 2017 /08/09 16:09:32*//*** doc格式*/private static final int DOC_FMT = 0;/*** docx格式*/private static final int DOCX_FMT = 12;static String picp=null;static String docn="/"+new Date().getTime()+".doc";public static String getSystemFileCharset(){Properties pro = System.getProperties();return pro.getProperty("file.encoding");}public static void main(String[] args) throws IOException {String sourcePath="D:\\软件\\Tomcat\\Tomcat7.075\\webapps\\jhwx\\file\\2019-07-22\\8_20190722111135.docx";String picturesPath="D:\\软件\\Tomcat\\Tomcat7.075\\webapps\\jhwx\\file\\2019-07-22\\image";try {convertDocFmt(sourcePath, picturesPath+docn, DOC_FMT);} catch (Exception e) {e.printStackTrace();}convert(new File(picturesPath+docn), picturesPath);String str=picturesPath+"\\"+picp.substring(6);pdf2Gif(str);}/*** 将doc文档转换成pdf文档* * @param docFile*                需要转换的word文档* @param filepath*                转换之后html的存放路径* @return 转换之后的html文件*/   public static File convert(File docFile, String filepath) throws IOException {// 创建保存html的文件String allpath=filepath + "/" + new Date().getTime() + ".pdf";File htmlFile = new File(allpath);picp=allpath.substring(54);// 启动OpenofficeString OpenOffice_HOME = "C:\\Program Files (x86)\\OpenOffice 4";if (OpenOffice_HOME.charAt(OpenOffice_HOME.length() - 1) != '\\') {OpenOffice_HOME += "\\";}String command = OpenOffice_HOME+ "program\\soffice -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\" -nofirststartwizard";Process pro = Runtime.getRuntime().exec(command);// 创建Openoffice连接OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);connection.connect();// 创建转换器
//      DocumentConverter converter = new OpenOfficeDocumentConverter(connection);DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);// 转换文档converter.convert(docFile, htmlFile);// 关闭openoffice连接connection.disconnect();// 关闭OpenOffice服务的进程pro.destroy();return htmlFile;}/*** 根据docx类型转换doc文件* * @param srcPaththe doc path 源文件* @param descPath   the docx path 目标文件* @param fmtthe     fmt 所转格式* @return the file* @throws Exception the exception*/public static File convertDocFmt(String srcPath, String descPath, int fmt) throws Exception {// 实例化ComThread线程与ActiveXComponentComThread.InitSTA();ActiveXComponent app = new ActiveXComponent("Word.Application");try {
// 文档隐藏时进行应用操作 app.setProperty("Visible", new Variant(false));
// 实例化模板Document对象 Dispatch document = app.getProperty("Documents").toDispatch();
// 打开Document进行另存为操作 Dispatch doc = Dispatch.invoke(document, "Open", Dispatch.Method,new Object[] { srcPath, new Variant(true), new Variant(true) }, new int[1]).toDispatch();Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] { descPath, new Variant(fmt) }, new int[1]);Dispatch.call(doc, "Close", new Variant(false));return new File(descPath);} catch (Exception e) {throw e;} finally {
// 释放线程与ActiveXComponent app.invoke("Quit", new Variant[] {});ComThread.Release();}}/*** pdf转png* @param pdfFilename* @throws InvalidPasswordException* @throws IOException*/public static void pdf2Gif(String pdfFilename ) throws InvalidPasswordException, IOException {//合成一张图片PDDocument document = PDDocument.load(new File(pdfFilename));PDFRenderer pdfRenderer = new PDFRenderer(document);List<BufferedImage> images = new ArrayList();int pageCounter = 0;for (PDPage page : document.getPages()) {// note that the page number parameter is zero basedBufferedImage bim = pdfRenderer.renderImageWithDPI(pageCounter++, 100, ImageType.RGB);images.add(bim);}BufferedImage result = mergeImage(false,images.toArray(new BufferedImage[0]));ImageIOUtil.writeImage(result, pdfFilename + "-" + (pageCounter++) + ".gif", 100);document.close();//不合成一张
//      PDDocument document = PDDocument.load(new File(pdfFilename));
//      PDFRenderer pdfRenderer = new PDFRenderer(document);
//      int pageCounter = 0;
//      int pages = document.getNumberOfPages();
//      pngp=new String[pages];
//      for (PDPage page : document.getPages()) {
//          // note that the page number parameter is zero based
//          BufferedImage bim = pdfRenderer.renderImageWithDPI(pageCounter++, 200, ImageType.RGB);
//          ImageIOUtil.writeImage(bim, pdfFilename + "-" + pageCounter + ".gif", 72);
//          pngp[pageCounter-1]=pdfFilename.substring(54)+ "-" + pageCounter + ".gif";
//
//      }
//      document.close();}/*** 合并任数量的图片成一张图片* * @param isHorizontal*            true代表水平合并,fasle代表垂直合并* @param imgs*            欲合并的图片数组* @return* @throws IOException*/public static BufferedImage mergeImage(boolean isHorizontal, BufferedImage... imgs) throws IOException {// 生成新图片BufferedImage destImage = null;// 计算新图片的长和高int allw = 0, allh = 0, allwMax = 0, allhMax = 0;for (BufferedImage img : imgs) {allw += img.getWidth();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);}// 合并所有子图片到新图片int wx = 0, wy = 0;for (int i = 0; i < imgs.length; i++) {BufferedImage img = imgs[i];int w1 = img.getWidth();int h1 = img.getHeight();// 从图片中读取RGBint[] 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;}return destImage;}
}

效果图:

转换前的docx文档(包含图形,文本框)


效果图:转换后的png文件

使用java将word文档docx,doc(包含图形,文本框)完美转换成所有格式图片(pdf,png,gif,jpeg等等)相关推荐

  1. Word处理控件Aspose.Words功能演示:在 C# 中的 Word 文档 (DOCX/DOC) 中添加或删除水印

    Aspose.Words 是一种高级Word文档处理API,用于执行各种文档管理和操作任务.API支持生成,修改,转换,呈现和打印文档,而无需在跨平台应用程序中直接使用Microsoft Word.此 ...

  2. java读取word文档里面的内容(包括doc和docx格式)

    java读取word文档里面的内容(包括doc和docx格式) java读取word文档里面的内容(包括doc和docx格式),使用POI架包 使用的POI架包如下 poi-3.16.jar poi- ...

  3. Java操作word文档将docx转换为pdf格式

    Java操作word文档将docx转换为pdf格式 一.整体说明 在上传 Office 课件时,格式有:doc,docx,xls,xlsx,ppt,pptx,程序需要将其 转换成 pdf 格式, 才能 ...

  4. java doc转图片_使用Java实现word文档转图片 在线预览

    [Java] 纯文本查看 复制代码/** * licence 验证 * @return * @throws Exception */ public static boolean getLicense( ...

  5. java 界面艺术字,Java 在Word文档中添加艺术字

    与普通文字相比,艺术字更加美观有趣也更具有辨识度,常见于一些设计精美的杂志或宣传海报中.我们在日常工作中编辑Word文档时,也可以通过添加艺术字体来凸显文章的重点,美化页面排版.这篇文章将介绍如何使用 ...

  6. Java将Word文档转换为PDF的完美工具

    引用至:https://mp.weixin.qq.com/s/JIgo3f98HufGJx23mgtvag Java 将 Word 文档转换为 PDF 的完美工具 在日常工作中,PDF格式良好的视觉阅 ...

  7. Word处理控件Aspose.Words功能演示:用Java从Word文档中提取文本

    Aspose.Words For .NET是一种高级Word文档处理API,用于执行各种文档管理和操作任务.API支持生成,修改,转换,呈现和打印文档,而无需在跨平台应用程序中直接使用Microsof ...

  8. Java解析word文档,将word文档题库选择题导入

    学习目标: Java解析word文档,将word文档题库导入 学会word文档的解析,以及各种题型的导入 学习内容: 解析word文档 获取正文文件内容 doc和docx两种解析 解析word文档 p ...

  9. Word处理控件Aspose.Words功能演示:使用 Java 将 Word 文档转换为 Markdown

    大多数智能设备,如智能手机.平板电脑.笔记本电脑等,都支持EPUB格式来查看或阅读文档.它是电子书或电子出版物的常用格式.另一方面,MS Word 格式,如DOCX.DOC等,是数字世界中广泛使用的文 ...

最新文章

  1. 将您的窗口最前端显示
  2. Microsoft Hyper-V Server 2008 R2和SCVMM2012部署XenDesktop 5.6桌面虚拟化系列之三准备XenDesktop服务器...
  3. [gic]-ARM gicv3/gicv2的总结和介绍-PPT
  4. 线性规划之单纯形法(2)
  5. S5P4418/S5P6818核心板EMMC已由原来的4.5版本升级到5.1版本
  6. faceswap深度学习AI实现视频换脸详解
  7. ## 7.3 奇异值分解的几何意义
  8. 吉他谱----see you again
  9. [Unity][ShaderGraph][FlowCanvas] SetFloat 无效:通过脚本控制 shader 的动态参数时需要使用参数的引用名
  10. 什么才是年轻人需要的手机?看完OPPO R11就有了答案!
  11. django–url
  12. spring 常用注解以分类
  13. 【图像分割】基于matlab随机游走算法图像分割【含Matlab源码 149期】
  14. 测试网络机顶盒的软件,新买的网络机顶盒安装什么软件好 几款热门装机必备软件分享...
  15. 19年6月英语六级第二套听力单词
  16. HDU 5478 Can you find it (卡常数)2015 ACM/ICPC Asia Regional Shanghai Online
  17. 【CPU】理解CPU
  18. 程序猿12个“人艰不拆”的真相
  19. iis mysql安装包下载_配置Windows Server2008+iis+php+mysql所需下载安装包
  20. es6模块循环引用的问题

热门文章

  1. 阿里实名认证Java版(详细教程)
  2. JavaScript获取浏览器可视区域的宽高
  3. unit自动驾驶怎么使用_自动驾驶与驾驶辅助系统 正确使用驾驶辅助系统
  4. android直播sdk+美颜,直播中有没有美颜SDK有何区别?
  5. 基于python实现的双月模型
  6. @RunWith的作用
  7. SpringBoot单元测试RunWith注解无法解析
  8. 再谈BOM和DOM(1):BOM与DOM概述
  9. uni-app:基于Vue的跨端框架(闪电演讲内容整理) | 掘金开发者大会
  10. 数据结构-树的进阶-串联各科知识