Java Word转PDF出现乱码问题可能是因为编码问题导致的。可以尝试使用UTF-8编码来处理文本内容,确保在读取和写入文件时都使用相同的编码。

示例代码如下:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

public class WordToPdfConverter {
    public static void main(String[] args) {
        try {
            // 读取Word文档
            InputStream in = new FileInputStream('input.docx');
            XWPFDocument document = new XWPFDocument(in);
            
            // 设置PDF转换选项
            PdfOptions options = PdfOptions.create();
            
            // 设置输出文件路径
            OutputStream out = new FileOutputStream('output.pdf');
            
            // 将Word文档转换为PDF
            PdfConverter.getInstance().convert(document, out, options);
            
            // 关闭流
            out.close();
            in.close();
            
            System.out.println('转换成功!');
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

请注意,上述示例中使用的是Apache POI库来进行Word转PDF,确保已经添加了相关的依赖。


原文地址: https://www.cveoy.top/t/topic/pLqx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录