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文件失败');
      }
    },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值