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 Bytes
        InputStream 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;

    }

导出方法

 @Override
    public 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);
    }

}

猜你喜欢

转载自blog.csdn.net/ole_triangle_java/article/details/133132061