java图片转pdf ,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);
    }

}
 /**
     * @param arrayList
     * @param byteArrayInputStream
     * @Description pdf page转 图片
     * @author caohong
     * @date 8:35 AM 9/27/2023
     */
    public static void pdfConvertImage(ArrayList arrayList, ByteArrayInputStream byteArrayInputStream) throws IOException {
        // 加载PDF文档
        PDDocument document = PDDocument.load(byteArrayInputStream);
        try {
            // 创建PDFRenderer对象
            PDFRenderer renderer = new PDFRenderer(document);
            // 遍历每个页面,并将其转换为图片
            for (int i = 0; i < document.getNumberOfPages(); i++) {
                //中间的参数是设置图片大小的
                BufferedImage image = renderer.renderImageWithDPI(0, 300, ImageType.RGB);
                ByteArrayOutputStream imageOutputStream = new ByteArrayOutputStream();
                ImageIO.write(image, "jpg", imageOutputStream);
                String s = Base64.getEncoder().encodeToString(imageOutputStream.toByteArray());
                arrayList.add(s);
                imageOutputStream.flush();
                imageOutputStream.close();
            }
        } finally {
            if(document != null){
                // 关闭文档
                document.close();
            }
        }
    }


    /**
     * @param arrayList
     * @param byteArrayInputStream
     * @Description pdf 提取 图片
     * @author caohong
     * @date 8:35 AM 9/27/2023
     */
    public static boolean extractImages(ArrayList arrayList, ByteArrayInputStream byteArrayInputStream) {
        boolean result = true;
        try {
            //通过文件名加载文档
            PDDocument document = PDDocument.load(byteArrayInputStream);
            PDPageTree pages = document.getPages();
            Iterator<PDPage> iter = pages.iterator();
            while (iter.hasNext()) {
                PDPage page = iter.next();
                PDResources resources = page.getResources();
                resources.getXObjectNames().forEach(e -> {
                    try {
                        if (resources.isImageXObject(e)) {
                            PDImageXObject imageXObject = (PDImageXObject) resources.getXObject(e);
                            BufferedImage bufferedImage = imageXObject.getImage();
                            System.out.println(bufferedImage);
                            ByteArrayOutputStream imageOutputStream = new ByteArrayOutputStream();
                            ImageIO.write(bufferedImage, "jpg", imageOutputStream);
                            String s = Base64.getEncoder().encodeToString(imageOutputStream.toByteArray());
                            arrayList.add(s);
                            imageOutputStream.flush();
                            imageOutputStream.close();
                        }
                    } catch (IOException ioException) {
                        ioException.printStackTrace();
                    }
                });
            }
            document.close();
            byteArrayInputStream.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            return false;
        }
        return result;
    }

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将Java导出的Excel换为PDF,您可以使用iText库。iText是一个流行的Java库,可以用于创建和操作PDF文档,其中包括将Excel文件换为PDF格式。以下是一个简单的示例代码,演示如何使用iText将Excel文件换为PDF: ```java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import com.itextpdf.text.Document; import com.itextpdf.text.pdf.PdfCopy; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfWriter; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Workbook; public class ExcelToPdfConverter { public static void main(String[] args) throws Exception { // 读取Excel文件 InputStream input = new FileInputStream(new File("input.xls")); Workbook workbook = new HSSFWorkbook(input); // 创建PDF文档 Document document = new Document(); OutputStream output = new FileOutputStream(new File("output.pdf")); PdfWriter writer = PdfWriter.getInstance(document, output); document.open(); // 将Excel文件内容写入PDF文档 PdfCopy pdf = new PdfCopy(document, output); for (int i = 0; i < workbook.getNumberOfSheets(); i++) { PdfReader reader = new PdfReader(workbook.getBytesAt(i)); pdf.addDocument(reader); } // 关闭文档 document.close(); output.close(); input.close(); } } ``` 在上面的示例中,我们首先使用Apache POI库读取Excel文件,然后使用iText库创建PDF文档。我们将Excel文件的内容写入PDF文档,然后关闭文件流。最后,我们将生成的PDF文件保存到磁盘上。请注意,该示例需要iText和Apache POI库的依赖项。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值