当前位置: 首页 > news >正文

java图片转pdf ,pdf 导出

pom引入jar

        <dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.0-RC2</version></dependency>

转pdf方法

/*** 使用pdfbox将jpg转成pdf** @throws IOException IOException*/public byte[] jpgToPdf(MultipartFile file) throws IOException {
//        long old = System.currentTimeMillis();
//        System.out.println(" -- 图片转PDF:" + simpleDateFormat.format(old) + " 开始处理 -- " + fileAbsolutePath);byte[] pdfBytes = new byte[0]; // PDF BytesInputStream jpgStream = file.getInputStream();PDDocument pdDocument = new PDDocument();BufferedImage image = ImageIO.read(jpgStream);PDPage pdPage = new PDPage(new PDRectangle(image.getWidth(), image.getHeight()));pdDocument.addPage(pdPage);PDImageXObject pdImageXObject = LosslessFactory.createFromImage(pdDocument, image);PDPageContentStream contentStream = new PDPageContentStream(pdDocument, pdPage);try {contentStream.drawImage(pdImageXObject, 0, 0, image.getWidth(), image.getHeight());contentStream.close();ByteArrayOutputStream baos = new ByteArrayOutputStream();PDAcroForm acroForm = pdDocument.getDocumentCatalog().getAcroForm();if (acroForm != null) {PDTextField field = (PDTextField) acroForm.getField("sampleField");field.setValue("Text Entry");}pdDocument.save(baos);pdfBytes = baos.toByteArray();
//        String newFilePath = fileAbsolutePath.substring(0, fileAbsolutePath.lastIndexOf(".")) + ".pdf";
//        pdDocument.save(newFilePath);} catch (IOException e) {e.printStackTrace();} finally {if (pdDocument != null) {try {pdDocument.close();} catch (IOException e) {e.printStackTrace();}}if (jpgStream != null) {try {jpgStream.close();} catch (IOException e) {e.printStackTrace();}}}long now = System.currentTimeMillis();
//        File file = new File(fileAbsolutePath);
//        boolean delete = file.delete();
//        System.out.println(" -- 图片转PDF处理结束时间:" + " 处理结束 -- 删除原始文件 " + delete);return pdfBytes;}

导出方法

 @Overridepublic String plantPhotoDownload(DvsPlantPhoto dvsPlantPhoto, HttpServletResponse response, HttpServletRequest request) throws Exception {DvsPlantPhoto result = this.getOne(new QueryWrapper<>(dvsPlantPhoto));if (result != null) {String uri = result.getKey();BlobServiceClient blobServiceClient = BlobUtils.getBlobServiceClient();BlobContainerClient a = BlobUtils.getContainer(blobServiceClient, containerName);ByteArrayOutputStream byteArrayOutputStream = BlobUtils.downBlobFilecao(a, uri);
//            return Base64.getEncoder().encodeToString(aa);ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());response.setCharacterEncoding(request.getCharacterEncoding());response.setContentType("application/pdf");try {response.setHeader("Content-Disposition", "attachment; filename=" + result.getKey());IOUtils.copy(byteArrayInputStream, response.getOutputStream());response.flushBuffer();} catch (Exception e) {log.error(e.getMessage(), e);} finally {if (byteArrayInputStream != null) {try {byteArrayInputStream.close();} catch (IOException e) {log.error(e.getMessage(), e);}}if (byteArrayOutputStream != null) {try {byteArrayOutputStream.close();} catch (IOException e) {log.error(e.getMessage(), e);}}}return new JSONObject().toJSONString();} else {return new JSONObject().toJSONString();}}

二 另一个图片转pDf办法

   <dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.4.2</version></dependency><dependency><groupId>org.sejda.imageio</groupId><artifactId>webp-imageio</artifactId><version>0.1.6</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><scope>test</scope></dependency><dependency><groupId>org.jacoco</groupId><artifactId>jacoco-maven-plugin</artifactId><version>0.8.8</version></dependency>
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Iterator;@Component
public class PdfUtils {/*** 将图片转换为PDF文件** @param file SpringMVC获取的图片文件* @return PDF文件流* @throws IOException       IO异常* @throws DocumentException PDF文档异常*/public static byte[] getPdfFile(MultipartFile file) throws DocumentException, IOException {File pdf = generatePdfFile(file);byte[] fileByte = FileUtils.readFileToByteArray(pdf);pdf.delete();return fileByte;}/*** 将图片转换为PDF文件** @param file SpringMVC获取的图片文件* @return PDF文件* @throws IOException       IO异常* @throws DocumentException PDF文档异常*/public static File generatePdfFile(MultipartFile file) throws IOException, DocumentException {File pdf = new File(SnowFlake.nextId() + "test.pdf");Document doc = new Document(PageSize.A4, 10, 10, 10, 10);PdfWriter.getInstance(doc, new FileOutputStream(pdf));doc.open();doc.newPage();Image image = null;float height = 0;float width = 0;try {image = Image.getInstance(file.getBytes());width = image.getWidth();height = image.getHeight();} catch (Exception e) {BufferedImage bufferedImage = ImageIO.read(file.getInputStream());ByteArrayOutputStream outputStream = new ByteArrayOutputStream();ImageIO.write(bufferedImage, "jpg", outputStream);image = Image.getInstance(outputStream.toByteArray());height = bufferedImage.getHeight();width = bufferedImage.getWidth();}int percent = getPercent(height, width);image.setAlignment(Image.MIDDLE);image.scalePercent(percent);doc.add(image);doc.close();return pdf;}/*** 等比压缩,获取压缩百分比** @param height 图片的高度* @param weight 图片的宽度* @return 压缩百分比*/private static int getPercent(float height, float weight) {float percent = 0.0F;if (height > weight) {percent = PageSize.A4.getHeight() / height * 100;} else {percent = PageSize.A4.getWidth() / weight * 100;}return Math.round(percent);}}

http://www.lryc.cn/news/177902.html

相关文章:

  • 掌握Go的运行时:从编译到执行
  • 打造香港最安全便捷的银行,众安银行发布首份技术白皮书
  • Spring实现简单的Bean容器
  • Python15题day13
  • 聊聊并发编程——多线程之AQS
  • DE0开发板交通灯十字路口红绿灯VHDL
  • 华为云云耀云服务器L实例评测使用 | 通过程序实现直播流自动分段录制
  • 前端教程-webpack
  • white-space几种属性的用法(处理空格)
  • Linux的历史
  • 软考高级系统架构设计师系列论文真题八:论企业集成平台的技术与应用
  • [H5动画制作系列] 路径引导动画 Demo
  • [React] Context上下文的使用
  • 高云FPGA系列教程(9):cmd-parser串口命令解析器移植
  • PHP8的静态变量和方法-PHP8知识详解
  • 用AI写文章被百家号封禁
  • JVM--Java类加载器笔记
  • 【在Ubuntu部署Docker项目】— PROJECT#1
  • 【学习笔记】LOJ #6240. 仙人掌
  • java通过接口转发文件(上传下载)
  • Docker-部署docker-compose以及管理服务
  • Android - Monkey 测试应用出现Crash报错IllegalStateException
  • Spring源码分析 事务 实现原理
  • ADS-B及雷达显示终端8.3
  • 第二章:最新版零基础学习 PYTHON 教程(第二节 - Python 输入/输出–从 Python 控制台获取输入)
  • linux安装配置 flume
  • SSM - Springboot - MyBatis-Plus 全栈体系(十五)
  • win10默认浏览器改不了怎么办,解决方法详解
  • C语言连接MySQL并执行SQL语句(hello world)
  • react实现动态递增展示数字特效