itext修改图片,导致图片被多次重复保存

按照例子 https://kb.itextpdf.com/itext/replacing-images,对图片进行修改。
如果原来的pdf中,图片被多个页面多次引用,因为修改后的图片,是新的 PdfStream ,其并没有 indirectReference。在 FlushResourcesContentStreams 的时候,会调用 FlushMustBeIndirectObject,继而调用 MakeIndirect,给这个 PdfStream 一个新的 indirectReference 编号。这样,每一页处理xobject的时候,都会生成一个新的 indirectReference 编号。

要重复利用以前的 indirectReference 编号,可以这样

                ImageData imageData = ImageDataFactory.Create(stream.ToArray());
                PdfImageXObject imageXObject = new PdfImageXObject(imageData);
                PdfStream imageXObjectStream = imageXObject.GetPdfObject();
                imageXObjectStream.Put(PdfName.ColorSpace, PdfName.DeviceGray);
+                var indirect = image.GetPdfObject().GetIndirectReference();
+                imageXObjectStream.MakeIndirect(indirect.GetDocument(), indirect);

                // Remove a redundant submask
                imageXObjectStream.Remove(PdfName.Mask);

版权声明:
作者:siwei
链接:https://www.techfm.club/p/226251.html
来源:TechFM
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>