How to redact a large rectangle of a PDF by iTextSharp?

て烟熏妆下的殇ゞ 提交于 2019-12-25 09:09:05

问题


I tried to use iTextSharp 5.5.9 to redact PDF files. The problem is when I redact a large rectangle field on a PDF, it can not save the file. This is the code:

PdfReader reader1 = new PdfReader(new FileStream(DesFile, FileMode.Open));

Stream fs = new FileStream(DesFile, FileMode.Open);

PdfStamper stamper = new PdfStamper(reader1, fs);

List<PdfCleanUpLocation> cleanUpLocations = new List<PdfCleanUpLocation>();

cleanUpLocations.Add(new PdfCleanUpLocation(1, new Rectangle(77f,77f,600f,600f), BaseColor.GRAY));

PdfCleanUpProcessor cleaner = new PdfCleanUpProcessor(cleanUpLocations, stamper); 

cleaner.CleanUp();

stamper.Close();

reader1.Close();

I use the http://sox.sourceforge.net/sox.pdf to test, if I change the Rectangle to

new Rectangle(77f,77f,200f,200f)

It will work well... But when I change back the larger Rectangle:

new Rectangle(77f,77f,600f,600f)

It stops working. Please help!


回答1:


iText development usually warns against stamping to the same file the underlying PdfReader reads from. If done as in the OP's code, reading and writing operations can get into each other's way, the results being unpredictable.

After using different files to read from and write to, the OP's solution started working.


If one first reads the source file into memory as a byte[] and then constructs the PdfReader from that array, it is possible to use the same file as output of a PdfStamper operating on that reader. But this pattern is not recommended either: If some problem occurs during stamping, the original file contents may already have been removed, so you have neither the unstamped original PDF nor a stamped result PDF.

It might be embarrassing to have to explain to the client that his documents are completely gone for good...



来源:https://stackoverflow.com/questions/38542052/how-to-redact-a-large-rectangle-of-a-pdf-by-itextsharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!