【发布时间】:2021-06-23 12:33:04
【问题描述】:
我有一个包含一些图像的 PDF 文件,我想将其替换为其他一些 PDF。代码遍历pdf并获取图片引用:
PdfDocument pdf = new PdfDocument(new PdfReader(args[0]), new PdfWriter(args[1]));
for(int i=1; i<=pdf.GetNumberOfPages(); ++i)
{
PdfDictionary pageDict = pdf.GetPage(i).GetPdfObject();
PdfDictionary resources = pageDict.GetAsDictionary(PdfName.Resources);
PdfDictionary xObjects = resources.GetAsDictionary(PdfName.XObject);
foreach (PdfName imgRef in xObjects.KeySet())
{
// image reference
}
}
对于我所有的图像,我都有一个相应的 PDF,我想用它来替换图像。我尝试将Put 另一个PDF(始终是单页)作为对象:
PdfDocument other = new PdfDocument(new PdfReader("replacement.pdf"));
xObjects.Put(imgRef, other.GetFirstPage().GetPdfObject().Clone());
但是在关闭PdfDocument 时会抛出异常:
iText.Kernel.PdfException: 'Pdf indirect object belongs to other PDF document. Copy object to current pdf document.'
如何用另一个 PDF 的(内容)替换图像?
更新
我还尝试了一些其他方法,可能会改善结果。为了克服之前的错误信息,我将页面复制到原始 pdf 中:
var page = other.GetFirstPage().CopyTo(pdf);
但是,替换 xObject 不起作用:
xObjects.Put(imgRef, page.GetPdfObject());
导致 PDF 损坏。
【问题讨论】: