首页 > 基础资料 博客日记

java将图片转化为pdf并输出

2023-07-24 10:11:05基础资料围观271

Java资料网推荐java将图片转化为pdf并输出这篇文章给大家,欢迎收藏Java资料网享受知识的乐趣

1.导入依赖

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.19</version>
</dependency>
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

2.在桌面准备一张图片a.png,定位并转化为multipartFile

@Test
public void testPdf() throws Exception{

    boolean is = false;

    File file = new File("C:\\Users\\scz\\Desktop\\a.png");

    FileInputStream fileInputStream = new FileInputStream(file);

    MultipartFile multipartFile = new MockMultipartFile("copy"+file.getName(),file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(),fileInputStream);

    try {
        PDDocument document = new PDDocument();

       /* PDPage page = new PDPage();
        PDRectangle rectangle = new PDRectangle(468, 450);
        page.setMediaBox(rectangle);*/
//这里是设置pdf的大小,大小固定,所有不推荐,下面是根据图片大小动态生成pdf大小

        String filename = multipartFile.getOriginalFilename();
        String fileSuffix = filename.substring(filename.lastIndexOf(".") + 1);

        Iterator readers = ImageIO.getImageReadersByFormatName(fileSuffix);
        ImageReader reader = (ImageReader) readers.next();
        ImageInputStream input = ImageIO.createImageInputStream(multipartFile.getInputStream());
        reader.setInput(input, true);

        int width = reader.getWidth(0)+300;
        int height = reader.getHeight(0)+500;
        PDPage pdPage = new PDPage(new PDRectangle(width, height));
//根据图片大小动态生成pdf大小

        document.addPage(pdPage);
        PDImageXObject pdImageXObject = PDImageXObject.createFromByteArray(document, multipartFile.getBytes(), "构建图片错误");

        PDPageContentStream contentStream = new PDPageContentStream(document, pdPage);
        //写入图片
        contentStream.drawImage(pdImageXObject, 0, 0);
        contentStream.close();

        document.save("C:\\Users\\scz\\Desktop\\1.pdf");

//pdf输出
        document.close();

        is = true;
    } catch (Exception e) {
        is = false;
    }

    System.out.println(is);
}

3.最后会在桌面输出一个1.pdf

注意:桌面的路径要改成自己的


文章来源:https://blog.csdn.net/leese233/article/details/130942784
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐

标签云