简体   繁体   English

如何用iTextSharp编辑PDF的大矩形?

[英]How to redact a large rectangle of a PDF by iTextSharp?

I tried to use iTextSharp 5.5.9 to redact PDF files. 我尝试使用iTextSharp 5.5.9编辑PDF文件。 The problem is when I redact a large rectangle field on a PDF, it can not save the file. 问题是当我在PDF上编辑一个大矩形字段时,它无法保存文件。 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 如果我将Rectangle更改为,则使用http://sox.sourceforge.net/sox.pdf进行测试

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

It will work well... But when I change back the larger Rectangle: 它将很好用...但是当我换回较大的Rectangle时:

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

It stops working. 它停止工作。 Please help! 请帮忙!

iText development usually warns against stamping to the same file the underlying PdfReader reads from. iText开发通常会警告不要将底层PdfReader读取相同的文件。 If done as in the OP's code, reading and writing operations can get into each other's way, the results being unpredictable. 如果按照OP的代码进行操作,则读写操作会互相影响,结果是不可预测的。

After using different files to read from and write to, the OP's solution started working. 使用不同的文件进行读写后,OP的解决方案开始工作。


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. 如果首先将源文件作为byte[]读取到内存中,然后从该数组构造PdfReader ,则可以将同一文件用作在该读取器上运行的PdfStamper输出。 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. 但是,也不建议使用这种模式:如果在标记过程中出现问题,则可能已经删除了原始文件的内容,因此您既没有未标记的原始PDF也没有标记的结果PDF。

It might be embarrassing to have to explain to the client that his documents are completely gone for good... 不得不向委托人解释说他的文件已经完全消失了,这可能很尴尬。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM