使用Aspose.Words

使用引入该jar包的方式,进行word转PDF。

需要注意的是该jar包功能是受限制的需要购买,所以我们的使用手动注入 License.xml 进行破解,可以做到无水印无页数限制。

并且全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,EPUB, XPS, SWF 相互转换。

导入jar包

下载该jar包后,可以放入本地仓库后依赖,也可以直接将该jar包导入项目中。

  • 将jar包引入到项目中

  • pom.xml 中添加信息

<dependency>
	<groupId>com.aspose</groupId>
    <artifactId>aspose-words</artifactId>
    <version>15.8.0</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/lib/aspose-words-15.8.0-jdk16.jar</systemPath>
</dependency>           

创建License.xml

首先,需要在 resources 中新建一个 License.xml 文件。并填入下面的内容。

<?xml version="1.0" encoding="UTF-8" ?>
<License>
    <Data>
        <Products>
            <Product>Aspose.Total for Java</Product>
            <Product>Aspose.Words for Java</Product>
        </Products>
        <EditionType>Enterprise</EditionType>
        <SubscriptionExpiry>20991231</SubscriptionExpiry>
        <LicenseExpiry>20991231</LicenseExpiry>
        <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
    </Data>
    <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>

工具类代码

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Author: zhs
 * @Date: 08/12/2023 12:05
 * @Version: 1.0
 * @Description:
 */
public class Word2PdfAsposeUtil {

    public static boolean getLicense() {
        boolean result = false;
        InputStream is = null;
        try {
            Resource resource = new ClassPathResource("License.xml");
            is = resource.getInputStream();
            //InputStream is = Word2PdfAsposeUtil.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public static boolean doc2pdf(String inPath, String outPath) {
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return false;
        }
        FileOutputStream os = null;
        try {
            long old = System.currentTimeMillis();
            File file = new File(outPath); // 新建一个空白pdf文档
            os = new FileOutputStream(file);
            Document doc = new Document(inPath); // Address是将要被转化的word文档
            doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
            // EPUB, XPS, SWF 相互转换
            long now = System.currentTimeMillis();
            System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }finally {
            if (os != null) {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

}

使用

public class Test {
    public static void main(String[] args) {
		//会在指定目录下生成xxx.pdf
        Word2PdfAsposeUtil.doc2pdf("C:\\Users\\新建文件夹\\111.docx", "xxx.pdf");
    }
}

注意事项

打包时的问题

当使用<scope>system</scope>引入依赖时,打包的时候要多注意,要加上如下配置,不然 springboot 是不会这种方式引入的 jar 进行打包的。所以修改修改 pom.xml

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <!-- 打包时会将本地jar一起打包 -->
            <configuration>
                <includeSystemScope>true</includeSystemScope>
            </configuration>     
        </plugin>
    </plugins>
</build>

乱码问题

如上代码在window下不会出现乱码,在Linux系统中会出现乱码,原因为Linux系统中缺少相应的字体。解决方案如下:

获取window字体C:\Windows\Fonts目录下字体复制到 Linux /usr/share/fonts/win,具体步骤如下:

# 1. 把字体上传到ninux服务器。这里上传到 /home 目录。

# 2.把刚刚上传的字体解压:
unzip Fonts.zip -d Fonts

# 3.创建字体目录:
mkdir /usr/share/fonts/win

# 4.把解压后的字体复制到创建的字体目录中:
cp /home/Fonts/Fonts/* /usr/share/fonts/win

# 5.安装字体
cd /usr/share/fonts
sudo mkfontscale
sudo mkfontdir 
sudo fc-cache -fv

# 6.执行命令让字体生效
source /etc/profile

# 7.如果安装失败,可以考虑修改字体权限
chmod 755 *.ttf

# 8.重启服务器就可以正常切换了

以上方法不行的话,可以使用第二种方法:

# 1.linux服务器字体文件是在/usr/share/fonts文件夹下的,在fonts文件夹下新建一个文件夹chinese,然后把window环境中的字体上传到服务器中 
cd /usr/share/fonts
mkdir chinese

# 2.执行命令,让字体生效
cd /usr/share/fonts 
sudo fc-cache -fv

# 3.修改代码代码贴到下面
import cn.hutool.system.SystemUtil;
import com.aspose.words.Document;
import com.aspose.words.FontSettings;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Author: zhs
 * @Date: 08/12/2023 12:05
 * @Version: 1.0
 * @Description:
 */
public class Word2PdfAsposeUtil {

    public static boolean getLicense() {
        boolean result = false;
        InputStream is = null;
        try {
            Resource resource = new ClassPathResource("License.xml");
            is = resource.getInputStream();
            //InputStream is = Word2PdfAsposeUtil.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }


    public static boolean doc2pdf(String inPath, String outPath) {
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return false;
        }

        //判断运行平台是不是Linux
        if(SystemUtil.getOsInfo().isLinux()){
            //切换字体库
            FontSettings.setFontsFolder("/usr/share/fonts/chinese/Fonts", true);
        }

        FileOutputStream os = null;
        try {
            long old = System.currentTimeMillis();
            File file = new File(outPath); // 新建一个空白pdf文档
            os = new FileOutputStream(file);
            Document doc = new Document(inPath); // Address是将要被转化的word文档
            doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
            // EPUB, XPS, SWF 相互转换
            long now = System.currentTimeMillis();
            System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }finally {
            if (os != null) {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

}

附件

aspose-words-15.8.0-jdk16.jar