Word文档是一种编辑功能丰富文档格局,能够对其进行各种加工编辑。但Word文档的展现很多时候是一个比拟辣手的问题,如果在编辑器中展现往往比拟麻烦且成果不太好。如果将Word文档转换为内容不变的图片,就能够很好的解决展现问题。本文将介绍通过编写程序将Word文档转换为图片的具体操作。
此办法须要用到收费的Jar:Free Spire.Doc for Java,可通过如下路径引入Jar文件。

1. Maven

prom.xml代码:

<repositories>        <repository>            <id>com.e-iceblue</id>            <name>e-iceblue</name>         <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url></repository></repositories><dependencies>    <dependency>        <groupId>e-iceblue</groupId>        <artifactId>spire.doc.free</artifactId>        <version>5.2.0</version>    </dependency></dependencies>

2. 官网下载

在Spire.Doc for Java免费版官网下载免费版,解压后,在“Project Structure“中,找到”Modules“,而后在其中的“Dependencies”中,增加解压出的“lib”文件夹下的Spire.Doc.jar文件。

Word文档转图片

操作步骤解析:

  • 通过创立 Document 类的对象创立Word文档。
  • Document.loadFromFile() 办法从磁盘加载Word文档。
  • 在文档中循环将每一页用 Document.saveToImage() 办法转换为一个PNG文件。

Java

import com.spire.doc.Document;import com.spire.doc.FileFormat;import com.spire.doc.documents.ImageType;import javax.imageio.ImageIO;import java.awt.image.BufferedImage;import java.io.*;public class WordToPNG {    public static void main(String[] args) throws IOException {        Document document = new Document();        document.loadFromFile("C:/Samples/Sample.docx");        document.saveToFile("123.pdf", FileFormat.PDF);        for (int i =0; i < document.getPageCount(); i++) {            BufferedImage image = document.saveToImages(i, ImageType.Bitmap);            File file = new File("WordToPNG" + (i + 1) + ".png");            ImageIO.write(image, "PNG", file);        }    }}

如果想将指定页面转换为图片,无需循环,可间接用 Document.saveToImage() 在应用页面作为参数进行转换。

转换成果:

原文的:

后果文档:

本文援用均来自收费的Free Spire.Doc for Java。