如何在Java程序中将doc、docx文件转换为pdf

3

我能够使用docx4j从docx文件生成pdf。但是我需要将包括图像和表格在内的doc文件转换为pdf。有没有办法在Java中将doc转换为docx或者pdf


1
你可以从终端运行OpenOffice(http://dag.wieers.com/home-made/unoconv/)来使用它进行文件转换。这可能不是最佳解决方案,但它是一个相当简单的解决方案。 - mqchen
我也需要解决方案,请问你找到了吗?如果找到了,请分享代码。 - Second View
4个回答

3

docx4j包含org.docx4j.convert.in.Doc,它使用POI来读取.doc文件,但它只是一个概念验证,不是生产就绪代码。截至我最后一次检查,POI对二进制.doc的HWPF解析存在限制。

除了mqchen的评论之外,你可以使用LibreOffice或OpenOffice将doc转换为docx。但如果你要使用LibreOffice或OpenOffice,你也可以直接将.doc和.docx转换为PDF。请搜索“jodconverter”。


2

参考POI单元测试的内容,我编写了以下代码来提取Word文档中的文本:

public String getText(String document) {
    try {
        ZipInputStream is = new ZipInputStream(new FileInputStream(document));
        try {
            is.getNextEntry();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                IOUtils.copy(is, baos);
            } finally {
                baos.close();
            }

            byte[] byteArray = baos.toByteArray();
            ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
            HWPFDocument doc = new HWPFDocument(bais);
            extractor = new WordExtractor(doc);
            extractor.getText();
        } finally {
            is.close();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

我希望这可以为您指明正确的方向,如果不能完全解决问题,也能帮助您。


1
谢谢,我需要一个包含图片和表格的doc文件转换成docx格式。 - user2211381

0

https://github.com/guptachunky/Conversion-Work 这个 Github 链接可能对此有所帮助。

https://github.com/guptachunky/Conversion-Work/blob/main/src/main/java/com/conversion/Conversion/Service/ConversionService.java

public void docToPdf(FileDetail fileDetail, HttpServletResponse response) {
    InputStream doc;
    try {
        File docFile = converterToFile(fileDetail.getFile());
        doc = new FileInputStream(docFile);
        XWPFDocument document = new XWPFDocument(doc);
        PdfOptions options = PdfOptions.create();
        File file = File.createTempFile("output", ".pdf");
        OutputStream out = new FileOutputStream(file);
        PdfConverter.getInstance().convert(document, out, options);
        getClaimFiles(file, response);
    } catch (IOException e) {
        response.setStatus(AppConstant.SOMETHING_WENT_WRONG);
    }
}

public void getClaimFiles(File file, HttpServletResponse response) {
    try {
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition",
                "attachment; filename=dummy.pdf");
        response.getOutputStream().write(Files.readAllBytes(file.toPath()));
    } catch (Exception e) {
        response.setStatus(AppConstant.SOMETHING_WENT_WRONG);
    }
}

0

您可以使用 jWordConvert 进行此操作。

jWordConvert 是一个 Java 库,可以本地读取和呈现 Word 文档,以转换为 PDF、转换为图像或自动打印文档。

详细信息请参见以下链接 http://www.qoppa.com/wordconvert/


OP说他想要使用docx4j来完成这个任务。 - hd1
谢谢,但我需要免费的源代码。 - user2211381

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接