/**
* BufferedImage转成 PDFbase64
*
* @param bufferedImage
* @return
* @throws IOException
*/
public static String getBufferedImageToPDFBase64(BufferedImage bufferedImage) throws IOException, BadElementException {
ByteArrayOutputStream baos = null;
//转base64 io流
baos = new ByteArrayOutputStream();
//io流
ByteArrayOutputStream pdfbaos = new ByteArrayOutputStream();
String base64Img = null;
// 写入流中
ImageIO.write(bufferedImage, "png", baos);
baos.flush();
Image image = Image.getInstance(baos.toByteArray());
Document document = new Document();
//设置文档页边距
document.setMargins(0, 0, 0, 0);
try {
PdfWriter.getInstance(document, pdfbaos);
//打开文档
document.open();
//获取图片的宽高
float imageHeight = image.getScaledHeight();
float imageWidth = image.getScaledWidth();
//设置页面宽高与图片一致
Rectangle rectangle = new Rectangle(imageWidth, imageHeight);
document.setPageSize(rectangle);
//图片居中
image.setAlignment(Image.ALIGN_CENTER);
//新建一页添加图片
document.newPage();
document.add(image);
} catch (Exception ioe) {
System.out.println(ioe.getMessage());
} finally {
//关闭文档
document.close();
try {
base64Img = Base64Util.encode(pdfbaos.toByteArray());
pdfbaos.flush();
pdfbaos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return base64Img;
}
/**
* PDF base64编码 转换为 BufferedImage
*
* @param base64
* @return
*/
private static BufferedImage pdfBase64ToBufferedImage(String base64) throws IOException {
byte[] image = Base64Util.decode(base64);
ByteArrayInputStream stream = new ByteArrayInputStream(image);
PDDocument doc = null;
try {
doc = PDDocument.load(stream);
PDFRenderer renderer = new PDFRenderer(doc);
BufferedImage bufferedImage = renderer.renderImageWithDPI(0, 162.8f);
return bufferedImage;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
pom.xml引入
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.24</version>
</dependency>
版权声明:本文为weixin_44309161原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。