问题
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