JAVA读取doc,docx转PDF通过vue展示
后端代码:
@GetMapping("/getContentAsPdf/{guid}")
public void getContentAsPdf(@PathVariable String guid, HttpServletResponse response) {
String contentUrl = ""; // 假设这个方法返回文档的URL
List<BsResource> byGuid = bsResourceService.findByGuid(guid);
if (!CollectionUtils.isEmpty(byGuid)) {
contentUrl = byGuid.get(0).getAbsolutePath();
}
// 设置响应的内容类型为PDF
response.setContentType("application/pdf");
try (InputStream is = new URL(contentUrl).openStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
if (contentUrl.endsWith(".doc")) {
// 处理.doc文件
HWPFDocument hwpfDocument = new HWPFDocument(is);
Range range = hwpfDocument.getRange();
StringBuilder textBuilder = new StringBuilder();
for (int i = 0; i < range.numParagraphs(); i++) {
textBuilder.append(range.getParagraph(i).text()).append("\n");
}
// 将文本内容转换为PDF
convertTextToPdf(textBuilder.toString(), baos);
} else if (contentUrl.endsWith(".docx")) {
// 处理.docx文件
try (XWPFDocument docxDocument = new XWPFDocument(is)) {
PdfWriter writer = new PdfWriter(baos);
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf);
for (XWPFParagraph paragraph : docxDocument.getParagraphs()) {
document.add(new Paragraph(paragraph.getText()));
}
document.close();
}
}
// 将PDF写入响应流
try (OutputStream os = response.getOutputStream()) {
baos.writeTo(os);
}
} catch (MalformedURLException ex) {
throw new RuntimeException(ex);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
private void convertTextToPdf(String text, ByteArrayOutputStream baos) throws IOException {
PdfWriter writer = new PdfWriter(baos);
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf);
document.add(new Paragraph(text));
document.close();
}
前端VUE调用(可以用iframe嵌套):
async handleTitleClick(row) {
try {
// 显示PDF
this.pdfUrl = `${baseURL}/bs/doc/getContentAsPdf/${row.guid}`;
this.dialogVisible = true;
} catch (error) {
console.error('获取PDF文件失败:', error);
this.$message.error('获取PDF文件失败');
}
},