java 图片base64 转 pdf

java 图片base64 转 pdf思路 base64 gt multipartFil gt pdfbase64 gt multipartFil 将图片 base64 gt MultipartFil parambase64 return publicstatic Stringbase64 try String baseStr base64 spli

思路:base64 -> multipartFile – > pdf

base64 -> multipartFile

/ * 将 图片base64 - > MultipartFile * @param base64 * @return */ public static MultipartFile base64MultipartFile(String base64) { 
    try { 
    String[] baseStr = base64.split(","); BASE64Decoder base64Decoder = new BASE64Decoder(); byte[] b; b = base64Decoder.decodeBuffer(baseStr[1]); for (int i = 0; i < b.length; ++i) { 
    if (b[i] < 0) { 
    b[i] += 256; } } return new BASE64DecodedMultipartFile(b, baseStr[0]); } catch (Exception e) { 
    e.printStackTrace(); return null; } } 

multipartFile – > pdf

/ * 将图片转换为PDF文件 * * @param file SpringMVC获取的图片文件 * @return PDF文件 * @throws IOException IO异常 * @throws DocumentException PDF文档异常 */ private static File generatePdfFile(MultipartFile file) throws IOException, DocumentException { 
    String fileName = file.getOriginalFilename(); String pdfFileName; if (fileName != null) { 
    pdfFileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".pdf"; } else { 
    return null; } Document doc = new Document(PageSize.A4, 100, 100, 20, 30); PdfWriter.getInstance(doc, new FileOutputStream(pdfFileName)); doc.open(); doc.newPage(); Image image = Image.getInstance(file.getBytes()); float height = image.getHeight(); float width = image.getWidth(); int percent = getPercent(height, width); image.setAlignment(Image.MIDDLE); image.scalePercent(percent); doc.add(image); doc.close(); return new File(pdfFileName); } / * 等比压缩,获取压缩百分比 * @param height 图片的高度 * @param weight 图片的宽度 * @return 压缩百分比 */ private static int getPercent(float height, float weight) { 
    float percent; if (height > weight) { 
    percent = PageSize.A4.getHeight() / height * 100; } else { 
    percent = PageSize.A4.getWidth() / weight * 100; } // -5 多缩放一点 不影响内容 percent -= 5; return Math.round(percent); } 

如果还需要转成multipartFile方便调用api上传的话

pdf file – > multipartFile

FileInputStream input = new FileInputStream(file); MultipartFile multipartFilePDF = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(input)); 

pom 依赖 itextpdf

 <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.10</version> </dependency> 
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/233742.html原文链接:https://javaforall.net

(0)
上一篇 2025年6月24日 下午8:01
下一篇 2025年6月24日 下午8:22


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号