gpt4 book ai didi

java - 如何使用 PDFBox 将页面的一部分呈现为图像?

转载 作者:行者123 更新时间:2023-12-03 23:23:14 43 4
gpt4 key购买 nike

PDFBox 提供渲染整个页面的功能,但无法仅渲染页面的特定矩形。

似乎实现这一目标的唯一方法是使用 PDFRenderer.renderPageToGraphics并配置 Graphics2D对象,所以只渲染感兴趣的区域,但我不知道如何做到这一点。

另一种方法是渲染整个页面,然后提取一个子图像,但我想避免这种情况。

最佳答案

所以,这比我最初想象的要容易一些。

这是执行此操作的 Groovy 代码。

import org.apache.pdfbox.pdmodel.PDDocument
import org.apache.pdfbox.rendering.PDFRenderer

import javax.imageio.ImageIO
import java.awt.*
import java.awt.geom.AffineTransform
import java.awt.geom.Rectangle2D
import java.awt.image.BufferedImage
import java.awt.image.RenderedImage

class RegionPDFRenderer {

private static final int POINTS_IN_INCH = 72

private final PDDocument document
private final PDFRenderer renderer
private final int resolutionDotPerInch

RegionPDFRenderer(PDDocument document, int resolutionDotPerInch) {
this.document = document
this.renderer = new PDFRenderer(document)
this.resolutionDotPerInch = resolutionDotPerInch
}

RenderedImage renderRect(int pageIndex, Rectangle2D rect) {
BufferedImage image = createImage(rect)
Graphics2D graphics = createGraphics(image, rect)
renderer.renderPageToGraphics(pageIndex, graphics)
graphics.dispose()
image
}

private BufferedImage createImage(Rectangle2D rect) {
double scale = resolutionDotPerInch / POINTS_IN_INCH
int bitmapWidth = rect.width * scale
int bitmapHeight = rect.height * scale
new BufferedImage(bitmapWidth, bitmapHeight, BufferedImage.TYPE_INT_RGB)
}

private Graphics2D createGraphics(BufferedImage image, Rectangle2D rect) {
double scale = resolutionDotPerInch / POINTS_IN_INCH
AffineTransform transform = AffineTransform.getScaleInstance(scale, scale)
transform.concatenate(AffineTransform.getTranslateInstance(-rect.x, -rect.y))

Graphics2D graphics = image.createGraphics()
graphics.setBackground(Color.WHITE)
graphics.setTransform(transform)
graphics
}

static void main(String[] args) {
String filePath = './input.pdf'
def pageIndex = 0
def region = new Rectangle(70, 472, 498, 289)
def resolutionForHiDPIScreenRendering = 220 /* dpi */

PDDocument doc = PDDocument.load(new File(filePath))
try {
def renderer = new RegionPDFRenderer(doc, resolutionForHiDPIScreenRendering)
def image = renderer.renderRect(pageIndex, region)
ImageIO.write(image, "png", new File("./output/image.png"))
} finally {
doc.close()
}
}

}

关于java - 如何使用 PDFBox 将页面的一部分呈现为图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36039536/

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