今天有学生问如何把Base64的图片如何转为base64的PDF,项目中要用到,写了个小例子给他参考。
1 导入依赖
<dependency> <groupId>itext</groupId> <artifactId>itext</artifactId> <version>4.2.1</version> </dependency>
2 测试代码
@Test
public void testToBase64() {
try {
File file = new File("d:\\test.jpg"); // 替换为你的图片路径
byte[] imageBytes = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(imageBytes);
fis.close();
String imageBase64 = Base64.getEncoder().encodeToString(imageBytes);
byte[] imageBytes2 = Base64.getDecoder().decode(imageBase64);
try {
Files.write(Paths.get("output.jpg"), imageBytes2, StandardOpenOption.CREATE); // 将文件写入到你想要保存的位置,替换为你想要的文件名
} catch (IOException e) {
e.printStackTrace();
}
File imageFile = Paths.get("output.jpg").toFile();
// 创建PDF文档
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("output.pdf"));
document.open();
Image image = Image.getInstance(imageFile.getPath());
// 获取PDF页面的大小
float pageWidth = document.getPageSize().getWidth();
float pageHeight = document.getPageSize().getHeight();
// 计算适应PDF页面大小的图片尺寸
float imageWidth = image.getWidth();
float imageHeight = image.getHeight();
float scaledWidth = pageWidth / imageWidth * imageWidth;
float scaledHeight = pageHeight / imageHeight * imageHeight;
float scaledSize = Math.min(scaledWidth, scaledHeight);
// 调整图片大小并添加到PDF文档中
image.scaleToFit(scaledWidth, scaledHeight);
document.add(image);
document.close();
// 将PDF文件转换为Base64编码的字符串
byte[] pdfBytes = Files.readAllBytes(Paths.get("output.pdf"));
String base64PDFString = Base64.getEncoder().encodeToString(pdfBytes);
System.out.println(base64PDFString);
} catch (IOException e) {
e.printStackTrace();
} catch (BadElementException e) {
throw new RuntimeException(e);
} catch (DocumentException e) {
throw new RuntimeException(e);
}
}

0条评论
点击登录参与评论