iText 5.5.13.3,创建pdf传输到前端,前端在浏览器中打开

@PostMapping(value = "/ShowPdf")  
public void exportExcel(HttpServletResponse response ) throws IOException { 
	RespondResultPojo respondResultPojo=new RespondResultPojo();
	ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    Document document = new Document(PageSize.A4.rotate());   
    try {  
        // 创建一个 PdfWriter 实例  
        PdfWriter.getInstance(document, baos);  
          
        // 打开文档  
        document.open();  
          
        // 添加内容到文档  
        Paragraph paragraph = new Paragraph("Hello, this is a PDF generated with iText!");  
        paragraph.setAlignment(Element.ALIGN_CENTER);  
        document.add(paragraph);  
          
        // 关闭文档  
    } catch (DocumentException e) {  
        e.printStackTrace();  
    } finally {  
        if (document.isOpen()) {  
            document.close();  
        }  
    }  
      
    // 获取 PDF 字节数组  
    byte[] pdfBytes = baos.toByteArray();  
      
    // 设置 HTTP 响应头  
    response.setContentType("application/pdf");  
    response.setHeader("Content-Disposition", "inline; filename=example.pdf");  
      
    // 获取 ServletOutputStream  
    ServletOutputStream outputStream = response.getOutputStream();  
      
    // 将 PDF 字节数组写入输出流  
    outputStream.write(pdfBytes);  
      
    // 刷新并关闭输出流  
    outputStream.flush();  
    outputStream.close();   
	}

前端代码

handleClick () {
      axios({
        method: 'post',
        url: '/CheckStore/ShowPdf',
        responseType: 'blob'
      })
        .then((response) => {
          const blobUrl = window.URL.createObjectURL(new Blob([response.data], { type: 'application/pdf' }))
          window.open(blobUrl, '_blank')
          const link = document.createElement('a')
          link.href = blobUrl
          link.setAttribute('download', 'example.pdf')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          setTimeout(() => {
            window.URL.revokeObjectURL(blobUrl)
          }, 100)
        })
        .catch((error) => {
          if (error === 'NotLogin') {
            this.router.push('/')
            ElMessage({
              message: ' 请登录',
              type: 'error'
            })
          } else {
            ElMessage({
              message: error,
              type: 'error'
            })
          }
        })
    }

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值