Using ContentByteUtils for raw PDF manipulation

2019-09-08 15:41发布

问题:

This is a follow up question to:

Programmatically change the color of a black box in a PDF file?

I have a pdf I created in Illustrator that has basically a black shape in the middle of the page and nothing else. I need to change the color of that shape dynamically.

From the response to the post above I am using iTextSharp (.NET C#) to get the raw contents of the PDF through ContentByteUtils.GetContentBytesForPage() and changing the color at the raw level.

Problem is that I can't find any way of saving the results back into either the original PDF or a new PDF file via iTextSharp. I'm currently stuck with a byte array of the raw contents but need to figure out how to save.

Help please!

回答1:

Why are you using ContentByteUtils.GetContentBytesForPage()?

I would use:

PdfReader reader = new PdfReader(src);
byte[] content = reader.GetPageContent(pageNumber);
// do stuff with content
reader.SetPageContent(pageNumber, content);
using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
    using (PdfStamper stamper = new PdfStamper(reader, fs)) {
    }
}