我有一个应用程序需要用图形标记现有的 PDF 文档。我正在尝试使用 iText,并且在大多数情况下,它可以工作。但是,我遇到的 PDF 文档没有基于 [0, 0] 的页面矩形或裁剪矩形。这是我的代码的精简版。
for (int i = 0; i < n; i++) {
PdfImportedPage page = writer.getImportedPage(reader, i + 1);
PdfCopy.PageStamp stamper = writer.createPageStamp(page);
PdfContentByte cb = stamper.getOverContent();
Rectangle cropRect = reader.getCropBox(i + 1);
Rectangle pageRect = reader.getPageSize(i + 1);
// construct the transform to place the crop rect of the original PDF into the new PDF
// This transform is what places the original image content accurately on the page
// construct a graphics2D object with the proper size (width, height of PDF in question)
Graphics2D g = cb.createGraphics(2449, 1576);
cb.saveState();
// Crop Rectangle coordinates of PDF in question: [0, 24824]
g.setTransform(AffineTransform.getTranslateInstance(cropRect.getLeft(), cropRect.getBottom()));
cb.restoreState();
g.setFont(new Font("Dialog", Font.BOLD, 48));
g.setColor(Color.blue);
g.drawString("Hello World", 1200, 800);
g.dispose();
stamper.alterContents();
writer.addPage(page);
}
在评论中,我指定了裁剪矩形的大小和位置(也与页面矩形相同)。此外,应用程序没有绘制“Hello World”,而是将 Graphics2D 对象传递给 Swing 面板的绘制方法。
提前致谢。