0


java将图片转化为pdf并输出

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

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

标签: java pdf 开发语言

本文转载自: https://blog.csdn.net/leese233/article/details/130942784
版权归原作者 leese233 所有, 如有侵权,请联系我们删除。

“java将图片转化为pdf并输出”的评论:

还没有评论