Pdf to image using java

帅比萌擦擦* 提交于 2021-02-08 11:09:34

问题


Good day fellow programmer. I'm new to java, and I need to create an Image from a specific part of a pdf.

Currently, I'm using pdfbox.

Here is my code to create an image from a pdf (it's working but it creates an image of the whole pdf page):

PDDocument document = PDDocument.load(new File(PDFFILE));

            PDFRenderer pdfRenderer = new PDFRenderer(document);
            for (int page = 0; page < document.getNumberOfPages(); ++page)
            {

                BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB);

                ImageIOUtil.writeImage(bim, path + "-" + (page+1) + ".png", 300);
            }
            document.close();

Problem:

I need to create an image based on the pdf in a specific position (like the rectangle).

Is there a way to do this using pdfbox, or is there another library that can do this? I tried searching but I can't find a solution.
Thank you.


回答1:


here is the solution: thanks mkl for the idea

    private void PdfToImage(String PDFFILE){
            try{

                PDDocument document = PDDocument.load(new File(PDFFILE));
                PDPage pd;

                PDFRenderer pdfRenderer = new PDFRenderer(document);
                for (int page = 0; page < document.getNumberOfPages(); ++page)
                {


                  pd = document.getPage(page);
                  pd.setCropBox(new PDRectangle(100, 100,100,100));
                  BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB);
                  ImageIOUtil.writeImage(bim, outputpath + (page+1) + ".png", 300);

                }
                document.close();
            }catch (Exception ex){
                JOptionPane.showMessageDialog(null, ex.getStackTrace());
            }
        }


来源:https://stackoverflow.com/questions/40519994/pdf-to-image-using-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!