How to redact a large rectangle of a PDF by iTextS

2019-09-14 09:16发布

问题:

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...



标签: c# pdf itext