1.首先pom文件添加依赖,操作pdf文件工具类
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.21</version>
</dependency>
2.pdf合并操作
public ResponseEntity<byte[]> mergePdf(MultipartFile[] files) {
PDFMergerUtility mergePdf = new PDFMergerUtility();
String filename = "d:/"+new Date().getTime()+".pdf";
for (MultipartFile multipartFile : files) {
try {
byte[] bytes = multipartFile.getBytes();
InputStream in = new ByteArrayInputStream(bytes);
mergePdf.addSource(in);
} catch (IOException e) {
throw new BaseException("Error merging pdf files- " + filename, e);
}
}
try {
mergePdf.setDestinationFileName(filename);
mergePdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
} catch (IOException e) {
e.printStackTrace();
}
return exportFile(new File(filename), filename);
}
注意:在feign之间传输二进制流时,返回值必须为 ResponseEntity 类型,所以封装了个私有方法,如下:
private ResponseEntity<byte[]> exportFile(File file, String filename) {
HttpHeaders headers = new HttpHeaders();
ResponseEntity<byte[]> entity = null;
InputStream in=null;
try {
in=new FileInputStream(file);
byte[] bytes = new byte[in.available()];
filename = URLEncoder.encode(filename, "utf-8");
in.read(bytes);
headers.add("Content-Disposition", "attachment;filename="+filename);
entity = new ResponseEntity<>(bytes, headers, HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
}finally {
if(in!=null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return entity;
}
注意:feign层代码接收类型 必须为 feign.Response
Response mergePdf(@RequestPart("file") MultipartFile[] file);
3.消费层 controller代码:
public void mergePdf(@RequestPart("file") MultipartFile[] file, HttpServletResponse response){
InputStream inputStream = null;
OutputStream outputStream = null;
try {
Response responseEntity = orderService.mergePdf(file);
Response.Body body = responseEntity.body();
inputStream = body.asInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
response.setContentType("multipart.form-data");
response.setHeader("Content-Disposition", responseEntity.headers().get("Content-Disposition").toString().replace("[","").replace("]",""));
outputStream = new BufferedOutputStream(response.getOutputStream());
int length = 0;
byte[] temp = new byte[1024 * 10];
while ((length = bufferedInputStream.read(temp)) != -1) {
outputStream.write(temp, 0, length);
}
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
最后调用接口,可以发现浏览器响应一个 blob 协议地址,最终由前端处理为二进制文件
|