从你的伪代码示例中,我们明白,要替换包含图像对象的流。有几个例子说明如何做到这一点。
例如,在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);
我们操纵的对象是作为图像XObject的流。拥有Image XObjects的优点是可以重复使用它们。例如:如果您在每个页面上都有相同的徽标,那么您只需要将该图像的字节存储一次,并多次重复使用相同的徽标。这意味着具有图像字节的对象不知道其位置。该位置在内容流中确定。这取决于CTM。
首先,iTextSharp不是免费的,它是开源的,它有一个非常大的差异。其次,你是正确的,'AcroFields'不是你应该走下去的道路。第三,如果您将PDF视为模板,您会遇到一些麻烦。这一切都说,通过[这里的答案](http://stackoverflow.com/a/8751517/231316)阅读从哪里开始的(不完整)示例 –
您的伪代码揭示了对PDF缺乏理解:位置的图像**从未存储在图像**中。如果是这样,那意味着你不能重用Image XObject。这1分钟的视频解释了免费/开源软件何时可以免费使用*以及何时需要商业许可证:https://www.youtube.com/watch?v = QHF3xcWnSD4 –
PDF文件中的图像不需要必须有名称或ID。你能解释Scribus如何将这些名称注入PDF中吗? – mkl