我能够使用docx4j从docx文件生成pdf。但是我需要将包括图像和表格在内的doc文件转换为pdf。有没有办法在Java中将doc转换为docx或者pdf?
我能够使用docx4j从docx文件生成pdf。但是我需要将包括图像和表格在内的doc文件转换为pdf。有没有办法在Java中将doc转换为docx或者pdf?
docx4j包含org.docx4j.convert.in.Doc,它使用POI来读取.doc文件,但它只是一个概念验证,不是生产就绪代码。截至我最后一次检查,POI对二进制.doc的HWPF解析存在限制。
除了mqchen的评论之外,你可以使用LibreOffice或OpenOffice将doc转换为docx。但如果你要使用LibreOffice或OpenOffice,你也可以直接将.doc和.docx转换为PDF。请搜索“jodconverter”。
参考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);
}
}
我希望这可以为您指明正确的方向,如果不能完全解决问题,也能帮助您。
https://github.com/guptachunky/Conversion-Work 这个 Github 链接可能对此有所帮助。
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);
}
}
您可以使用 jWordConvert 进行此操作。
jWordConvert 是一个 Java 库,可以本地读取和呈现 Word 文档,以转换为 PDF、转换为图像或自动打印文档。
详细信息请参见以下链接 http://www.qoppa.com/wordconvert/