gpt4 book ai didi

java - PdfBox 将多页 PDF 转换为一张 JPG 图像

转载 作者:行者123 更新时间:2023-12-02 09:30:39 25 4
gpt4 key购买 nike

我有一个包含多个页面的 pdf 文件,我想将其转换为一张图像。

我的实际代码通过pdf页面创建图像...

@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();
}
}

如何为所有 pdf 页面创建一张图像?

最佳答案

解决方案如下:

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

关于java - PdfBox 将多页 PDF 转换为一张 JPG 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58014451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com