从您的伪代码示例中,我们了解到您想要替换包含图像的对象的流。有几个示例说明如何执行此操作。
例如,在 SpecialID 示例中,我们创建了一个 PDF,其中我们使用特殊 ID 标记特定图像。在 ResizeImage 示例中,我们根据该特殊 ID 跟踪该图像并替换流:
object = reader.getPdfObject(i);
if (object == null || !object.isStream())
continue;
stream = (PRStream)object;
if (value.equals(stream.get(key))) {
PdfImageObject image = new PdfImageObject(stream);
BufferedImage bi = image.getBufferedImage();
if (bi == null) continue;
int width = (int)(bi.getWidth() * FACTOR);
int height = (int)(bi.getHeight() * FACTOR);
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
AffineTransform at = AffineTransform.getScaleInstance(FACTOR, FACTOR);
Graphics2D g = img.createGraphics();
g.drawRenderedImage(bi, at);
ByteArrayOutputStream imgBytes = new ByteArrayOutputStream();
ImageIO.write(img, "JPG", imgBytes);
stream.clear();
stream.setData(imgBytes.toByteArray(), false, PRStream.NO_COMPRESSION);
stream.put(PdfName.TYPE, PdfName.XOBJECT);
stream.put(PdfName.SUBTYPE, PdfName.IMAGE);
stream.put(key, value);
stream.put(PdfName.FILTER, PdfName.DCTDECODE);
stream.put(PdfName.WIDTH, new PdfNumber(width));
stream.put(PdfName.HEIGHT, new PdfNumber(height));
stream.put(PdfName.BITSPERCOMPONENT, new PdfNumber(8));
stream.put(PdfName.COLORSPACE, PdfName.DEVICERGB);
}
你会在书中找到另一个例子 The Best iText Questions on StackOverflow 我回答了以下问题:PDF Convert to Black And White PNGs
我编写了ReplaceImage 示例来展示如何替换图像:
public static void replaceStream(PRStream orig, PdfStream stream) throws IOException {
orig.clear();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
stream.writeContent(baos);
orig.setData(baos.toByteArray(), false);
for (PdfName name : stream.getKeys()) {
orig.put(name, stream.get(name));
}
}
如您所见,这并不像说的那么简单:
var object = Pdf.GetObjectById("company_logo");
object.SetValue(myImage);
正如我在评论中解释的那样,这没有意义:
object.SetPosition(x, y);
我们正在操作的对象是用作 Image XObjects 的流。拥有 Image XObjects 的优点是它们可以被重用。例如:如果您在每个页面上都有相同的徽标,那么您希望只存储该图像的字节一次并多次重复使用相同的徽标。这意味着具有图像字节的对象对其位置一无所知。位置在内容流中确定。这取决于 CTM。