前言
java将多个base64数据合并成一个pdf下载
一、Maven引入jar包
<dependency>
<groupId>cn.gtmap.ahcalib</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>
二、将base64转成byte[]
public static byte[] base64StringToByte(String base64String) {
BASE64Decoder decoder = new BASE64Decoder();
ByteArrayOutputStream baos = null;
try {
byte[] bytes = decoder.decodeBuffer(base64String);
baos = new ByteArrayOutputStream();
baos.write(bytes); //把byte写进输出流里
return baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (baos != null){
baos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return new byte[0];
}
三、合并pdf
private String getCombinePdf(String fileName, List<byte[]> byteList) {
String path = System.getProperty("catalina.home") + "/egov-home/bdc/data/temp/";
File folder = new File(path);
if (!folder.exists()) {
folder.mkdirs();
}
String filePath = path + fileName + ".pdf";
Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
try {
PdfWriter.getInstance(doc, new FileOutputStream(filePath));
doc.open();
Image image = null;
for (byte[] bs: byteList) {
image = Image.getInstance(bs);
float heigth = image.getHeight();
float width = image.getWidth();
int percent = getPercent2(heigth, width);
// 设置图片居中显示
image.setAlignment(Image.MIDDLE);
image.scalePercent(percent+3);// 表示是原来图像的比例;
//添加到PDF文档
doc.add(image);
//下一页,每张图片一页
doc.newPage();
}
doc.close();
} catch (DocumentException e) {
logger.info("DocumentException: " + e);
} catch (FileNotFoundException e) {
logger.info("FileNotFoundException: " + e);
} catch (MalformedURLException e) {
logger.info("MalformedURLException: " + e);
} catch (IOException e) {
logger.info("IOException: " + e);
}
return filePath;
}
public static int getPercent2(float h, float w) {
int p = 0;
float p2 = 0.0f;
p2 = 530 / w * 100;
p = Math.round(p2);
return p;
}
四、下载pdf
String filePath = getCombinePdf(fileName, byteList);
File file = new File(filePath);
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
byte[] bytes = new byte[fis.available()];
fis.read(bytes);
HttpHeaders headers = new HttpHeaders();
fileName = URLEncoder.encode(fileName,"UTF-8") + ".pdf";
headers.setContentDispositionFormData("attachment", fileName);//告知浏览器以下载方式打开
headers.add("Content-Disposition", "attachment;filename*=UTF-8''" + fileName);
headers.setContentType(MediaType.APPLICATION_PDF);
return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
更多推荐
java将多个base64数据合并成一个pdf下载
发布评论