PdfBox transform PDF with several pages to one Image JPG

余生颓废 提交于 2019-12-02 10:07:01

Here is the solution :

   @Test
    public void testImage() throws IOException {

        try {
            //Load PDF
            PDDocument pdDocument = PDDocument.load(new File("download.pdf"));
            //Create the renderer
            PDFRenderer pdfRenderer = new PDFRenderer(pdDocument);
            BufferedImage joinBufferedImage = new BufferedImage(10, 10,  BufferedImage.TYPE_INT_ARGB);

            for (int x = 0; x < pdDocument.getNumberOfPages(); x++) {

                BufferedImage bImage = pdfRenderer.renderImageWithDPI(x, 150, ImageType.RGB);
                joinBufferedImage = joinBufferedImage(joinBufferedImage, bImage);
                //File imageFile = new File(x +"_template_image.jpg");
            }

            ImageIOUtil.writeImage(joinBufferedImage, String.format("template_image.%s", "png"), 150);
            pdDocument.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


 public BufferedImage joinBufferedImage(BufferedImage img1, BufferedImage img2) {

        //do some calculate first
        int offset = 5;
        int wid = Math.max(img1.getWidth(), img2.getWidth()) + offset;
        int height = img1.getHeight()+ img2.getHeight() + offset;
        //create a new buffer and draw two image into the new image
        BufferedImage newImage = new BufferedImage(wid, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = newImage.createGraphics();
        Color oldColor = g2.getColor();
        //fill background
        g2.setPaint(Color.WHITE);
        g2.fillRect(0, 0, wid, height);
        //draw image
        g2.setColor(oldColor);
        g2.drawImage(img1, null, 0, 0);
        g2.drawImage(img2, null, 0 , img1.getHeight() + offset);
        g2.dispose();
        return newImage;
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!