docx文档转为pdf文件响应前端

发布于:2025-04-12 ⋅ 阅读:(35) ⋅ 点赞:(0)

1、转换文件(docx~pdf)

1.引入pom依赖

<dependency>
  	<groupId>com.aspose</groupId>
  	<artifactId>aspose-words</artifactId>
  	<version>20.12.0</version>
</dependency>

2.读取docx文档数据-转换

// 初始化pdf文件
String pdfPath = "testConvert.pdf";
// docx文件名
String fileName = "test.docx";

// 1. 加载 Word 文件
Document doc = new Document(fileName);
doc.save(pdfPath, SaveFormat.PDF);

3.读取pdf文档数据-响应

FIle pdfFile // 转换后的文件
FileInputStream fis = new FileInputStream(pdfFile);

// 设置响应头或类型
response.setCharacterEncoding("UTF-8");
response.setContentType("application/pdf; charset=UTF-8");
// 设置文件名
String disposition = "attachment; filename=" + URLEncoder.encode("fileName", "UTF-8");
response.setHeader("Content-Disposition", disposition);
response.setContentLength((int) pdfFile.length());
// try-with-resources 读取写入流
try (FileInputStream fileInputStream = new FileInputStream(pdfFile);
    OutputStream outputStream = response.getOutputStream()) {
    byte[] buffer = new byte[4096];
    int bytesRead;
    // 将文件流写入响应输出流
    while ((bytesRead = fileInputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
    }
}
// 可将临时生成的文件删除 .delete()


网站公告

今日签到

点亮在社区的每一天
去签到