记一次文件从Word转为PDF(documents4j和aspose)

本文探讨了使用documents4j和aspose进行Word转PDF的方法。documents4j依赖MSOffice,适用于本地但不支持Linux;aspose虽收费但在解决中文乱码问题上更优,通过设置字体路径和使用License认证,实现了跨平台的文档转换。

前言:

两种方法:documents4jaspose
最开始是用documents4j,在本地使用很方便,但是部署到LINUX上面之后,抛出异常,就看了下官方文档,documents4j是使用本地的MS Office应用做的文件格式转换,Linux没有对应的MS Office应用,所以直接就废除.后来改用aspose,在本地也是测试完成,没有问题,但是服务器上就是各种中文乱码(中文小方格),跟之前使用openoffice的乱码虽然不一样,但是还是乱码.不过最终解决了问题.

一、documents4j实现格式转换

需要MS Office,官方并没有说documents4j不支持Linux下运行,但是LINUX确实没安装MS应用,我也没费工夫去研究安装MS,如果谁好了,麻烦告知一下.

依赖
<dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-local</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-transformer-msoffice-word</artifactId>
            <version>1.1.1</version>
        </dependency>
代码
package com.qingyu.transform.utils;

import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import org.junit.jupiter.api.Test;

import java.io.*;

/**
 * @ProjectName: transform
 * @Package: com.qingyu.transform.utils
 * @ClassName: WordToPdf
 * @Author: qingyu
 * @Description:
 * @Date: 2020/3/19 13:46
 * @Version: 1.0
 */
class WordToPdf {
    /**
     * 将之前对应的word文件转换成pdf,然后预览pdf文件
     */

    public static String  wordToPdf( String suffix ){
        // 转换之后的pdf文件
        File inputWord = new File("C:/Users/Administrator/Desktop/测试.docx");
        File outputFile = new File("C:/Users/Administrator/Desktop/测试.pdf");
        try  {
            InputStream docxInputStream = new FileInputStream(inputWord);
            OutputStream outputStream = new FileOutputStream(outputFile);
            IConverter converter = LocalConverter.builder().build();
            if(suffix.equals("doc")){
                converter.convert(docxInputStream).as(DocumentType.DOC).to(outputStream).as(DocumentType.PDF).execute();
            } else if(suffix.equals("docx")){
                converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
            } else if(suffix.equals("txt")){
                converter.convert(docxInputStream).as(DocumentType.TEXT).to(outputStream).as(DocumentType.PDF).execute();
            }
            outputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) {
        wordToPdf("docx");
    }

}

二、aspose实现文件转换

依赖

首先aspose是收费软件,pom依赖无法直接下载(反正我是没下载下来),我是通过下载别人分享的链接拿到的jar包。通过Project StraStructure引用进来的,在项目中直接放在lib包下面.
下面的依赖是根据jar包的pom文件写的,不是正确的,不过你可以自己上传到自己的repository中,构建一个pom,然后作为依赖加到项目中

		<dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-words</artifactId>
            <version>16.8.0</version>
        </dependency>
代码

/**
 * @ProjectName: transform
 * @Package: com.qingyu.transform.utils
 * @ClassName: Word2PdfUtil
 * @Author: qingyu
 * @Description:
 * @Date: 2020/3/20 10:47
 * @Version: 1.0
 */
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public class Word2PdfUtil {

    /**
     * The constant LOG.
     *
     */
    private static final Logger LOG = LoggerFactory.getLogger(Word2PdfUtil.class);

    /**
     * 获取license
     *
     * @return
     */
    private static boolean getLicense() {
        boolean result = false;
        try {
            // 凭证
            String licenseStr =
                    "<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>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" +
                            "  </Data>\n" +
                            "  <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +
                            "</License>";
            InputStream license = new ByteArrayInputStream(licenseStr.getBytes("UTF-8"));
            License asposeLic = new License();
            asposeLic.setLicense(license);
            result = true;
        } catch (Exception e) {
            LOG.error("error:", e);
        }
        return result;
    }

    /**
     * Word 2 pdf.
     *
     * @param pdfFilePath   the pdf file path
     */
    public static void word2Pdf( String pdfFilePath) {
        FileOutputStream fileOS = null;
        // 验证License
        if (!getLicense()) {
            LOG.error("验证License失败!");
            return;
        }
        File inputWord = new File("C:/Users/Administrator/Desktop/测试.docx");
        try {
         	//此处处理乱码和小方块
            //如果在本地运行,此处报错,请注释这个这是字体,主要是为了解决linux环境下面运行jar时找不到中文字体的问题
            FontSettings.getDefaultInstance().setFontsFolders(
                    new String[] {"/usr/share/fonts", "/usr/share/fonts/chinese"}
                    , true);
            Document doc = new Document(new FileInputStream(inputWord));
            fileOS = new FileOutputStream(new File(pdfFilePath));
            // 保存转换的pdf文件
            doc.save(fileOS, SaveFormat.PDF);
        } catch (Exception e) {
            LOG.error("error:", e);
        } finally {
            try {
                if(fileOS != null){
                    fileOS.close();
                }
            } catch (IOException e) {
                LOG.error("error:", e);
            }
        }
    }

    public static void main(String[] args) {
        word2Pdf("C:/Users/Administrator/Desktop/测试.pdf");
    }
}
问题
  1. 本地测试正常,Linux还是乱码
    原因:
    (1)Linux服务器上没有安装对应的中文字体,参考
    (2)字体并不是被所有用户通用的
    (3)没有构建字体索引,没有刷新字体路径缓存
    解决:
    百度Linux安装中文字体,之后,运行命令看看是否能看到中文字体

  2. 安装了中文字体还是乱码
    原因:在Linux上运行Jar无法找到中文字体,可以在代码里面添加路径指向中文字体文件夹

在这里插入图片描述

结束

感谢这些博客:1-2-3-4-5-6
特别感谢第六篇亓亓亓亓凌的博客

<think>好的,我需要帮助用户找到将WordExcel文件直接转换为PDF的方法或工具,包括编程现有工具两种方式。首先,我得考虑用户可能的需求:他们可能希望自动化处理大量文件,或者需要集成到现有系统中,所以编程方法可能更适合;另一方面,如果用户只是偶尔需要转换,使用现成工具会更方便。 接下来,我得回忆一下常见的工具库。对于编程方法,Python有几个常用的库,比如python-docx处理Word,openpyxl或xlrd处理Excel,但转换PDF可能需要其他库,比如docx2pdfcomtypes,或者使用PyWin32操作Microsoft Office的API。另外,LibreOffice也有命令行工具,可以通过编程调用。对于现有工具,用户可能熟悉Microsoft Office自带的另存为PDF功能,还有一些在线转换工具如Smallpdf、Adobe Acrobat等,以及MarkItDown这个工具,根据引用[2]提到的,它支持将WordExcel转成Markdown,但不确定是否支持PDF,可能需要进一步确认,不过用户的问题明确要求PDF转换,所以可能还是以其他工具为主。 然后,我需要组织这些信息,分步骤说明。编程方法部分需要给出具体的代码示例,比如使用Python的docx2pdf库,或者通过COM接口调用WordExcel的应用进行保存为PDF。同时,要提到跨平台的问题,比如comtypes可能只适用于Windows,而LibreOffice可以在Linux/macOS上使用命令行。对于工具部分,要列举几个常用且可靠的工具,包括桌面软件在线服务,确保用户有多个选择。 还要注意引用用户提供的参考内容,引用[1]提到PDF转换的需求在办公中很常见,引用[2]提到MarkItDown支持多种格式转换到Markdown,但用户需要的是PDF,所以可能不需要深入讨论MarkItDown,除非它也能转PDF,但根据描述似乎不行,所以可能不提及。 需要检查是否有遗漏的方法,例如使用VBA脚本在Office中自动转换,或者PowerShell脚本,但可能用户更倾向于Python或其他常见编程语言。此外,确保提到的工具库都是当前流行且维护良好的,避免推荐过时的资源。 最后,生成相关问题,可能涉及转换中的常见问题、批量处理、格式保留等,确保覆盖用户可能进一步想知道的内容。同时,保持回答结构清晰,分点说明,代码示例正确,并注意使用中文,符合用户的要求。</think>### 分步解决方案:Word/Excel转PDF的方法与工具 --- #### **一、编程实现方法** 1. **Python自动化方案(Windows环境)** - **依赖库**:`pywin32` 或 `comtypes`(通过COM接口控制Office软件) - **代码示例(WordPDF)**: ```python import win32com.client def word_to_pdf(input_path, output_path): word = win32com.client.Dispatch("Word.Application") doc = word.Documents.Open(input_path) doc.SaveAs(output_path, FileFormat=17) # 17为PDF格式代码 doc.Close() word.Quit() ``` - **代码示例(Excel转PDF)**: ```python def excel_to_pdf(input_path, output_path): excel = win32com.client.Dispatch("Excel.Application") workbook = excel.Workbooks.Open(input_path) workbook.ExportAsFixedFormat(0, output_path) # 0表示PDF格式 workbook.Close() excel.Quit() ``` - **注意**:需安装Microsoft Office并启用宏权限[^1]。 2. **跨平台方案(LibreOffice命令行)** - **安装LibreOffice**:支持Windows/macOS/Linux - **终端命令**: ```bash libreoffice --headless --convert-to pdf 文件路径.docx ``` 3. **Python专用库(无需Office环境)** - **`docx2pdf`库**(仅限Word): ```python from docx2pdf import convert convert("input.docx", "output.pdf") ``` - **`Aspose`库**(支持Word/Excel,需商业授权): ```python import aspose.words as aw doc = aw.Document("input.docx") doc.save("output.pdf") ``` --- #### **二、现成工具推荐** 1. **桌面软件** - **Microsoft Office内置功能**: - Word/Excel中点击「文件 > 另存为 > PDF格式」 - **Adobe Acrobat Pro**:支持批量转换格式优化 - **WPS Office**:免费版本支持基础转换 2. **在线转换工具** - **Smallpdf**:https://smallpdf.com(支持加密批量处理) - **ILovePDF**:https://www.ilovepdf.com(含OCR识别功能) - **Zamzar**:https://zamzar.com(支持编程API调用) 3. **企业级解决方案** - **Nitro Cloud**:https://cloud.gonitro.com(支持API集成) - **PDFelement**:https://pdf.wondershare.com(自动化工作流设计) --- #### **三、关键问题与优化** 1. **格式保留**:复杂表格/公式转换后易错位,建议使用Adobe或Aspose工具[^1]。 2. **批量处理**: - Python遍历文件夹: ```python import os for file in os.listdir("word_folder"): if file.endswith(".docx"): convert(os.path.join("word_folder", file)) ``` - 使用PowerShell脚本调用LibreOffice: ```powershell Get-ChildItem -Filter *.xlsx | ForEach-Object {libreoffice --convert-to pdf $_.FullName} ``` 3. **安全与加密**: - 在线工具需注意隐私风险,敏感文件建议本地处理 - 使用Python加密PDF: ```python from PyPDF2 import PdfFileWriter, PdfFileReader writer = PdfFileWriter() writer.encrypt("password") ``` ---
评论 22
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贝多芬也爱敲代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值