后端代码:
@GetMapping("/getContentAsPdf/{guid}")public void getContentAsPdf(@PathVariable String guid, HttpServletResponse response) {String contentUrl = ""; // 假设这个方法返回文档的URLList<BsResource> byGuid = bsResourceService.findByGuid(guid);if (!CollectionUtils.isEmpty(byGuid)) {contentUrl = byGuid.get(0).getAbsolutePath();}// 设置响应的内容类型为PDFresponse.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");}// 将文本内容转换为PDFconvertTextToPdf(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 {// 显示PDFthis.pdfUrl = `${baseURL}/bs/doc/getContentAsPdf/${row.guid}`;this.dialogVisible = true;} catch (error) {console.error('获取PDF文件失败:', error);this.$message.error('获取PDF文件失败');}},