简体   繁体   中英

PdfBox transform PDF with several pages to one Image JPG

I have a pdf with several pages and I want to transform that to one Image.

My actual code create an image by pdf's page...

@Test
public void testImage() throws IOException {

    try {
        PDDocument pdDocument = PDDocument.load(new File("download.pdf"));
        PDFRenderer pdfRenderer = new PDFRenderer(pdDocument);
        for (int x = 0; x < pdDocument.getNumberOfPages(); x++) {
            BufferedImage bImage = pdfRenderer.renderImageWithDPI(x, 300, ImageType.RGB);
            ImageIOUtil.writeImage(bImage, String.format(x +"__template_image.%s", "jpg"), 300);
            File imageFile = new File(x +"_template_image.jpg");
        }
        pdDocument.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

How may I create only one image for all pdf pages?

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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM