Reputation: 1148
I am using the following code to populate the fields in a PDF as follows:
string fileNameExisting = @"C:\Old.pdf";
string fileNameNew = @"C:\New.pdf";
using (FileStream existingFileStream = new FileStream(fileNameExisting, FileMode.Open))
{
using (FileStream newFileStream = new FileStream(fileNameNew, FileMode.Create))
{
Font font = FontFactory.GetFont(FontFactory.COURIER, 6f, Font.BOLD);
PdfReader pdfReader = new PdfReader(existingFileStream);
PdfStamper stamper = new PdfStamper(pdfReader, newFileStream);
AcroFields form = stamper.AcroFields;
ICollection fieldKeys = form.Fields.Keys;
foreach (string fieldKey in fieldKeys)
{
stamper.AcroFields.SetFieldProperty(fieldKey, "textsize", 6f, null);
stamper.AcroFields.AddSubstitutionFont(font.BaseFont);
form.SetField(fieldKey, fieldKey); //Just for testing
}
stamper.Close();
}
}
It works well and fine, but my end goal is to have a bool passed to this method that will dictate whether or not the base layer of the document is rendered. (ie) if the user only needs to render the field content and hide the actual content of "Old.pdf".
I looked through the documentation but it never covers doing this in particular, is it even possible?
Upvotes: 1
Views: 999
Reputation: 96064
dictate whether or not the base layer of the document is rendered.
First of all, in the context of PDFs the term layer is not defined in the specification; if it is used, though, this usually is done as a pseudonym for optional content groups (OCG) because certain PDF processors use it so. But as OCGs have to be explicitly marked in the content, using them does not appear appropriate here.
What you can do quite easily, though, is to
either cover the existing content with some white rectangle
using (PdfReader pdfReader = new PdfReader(input))
using (PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(output, FileMode.Create, FileAccess.Write)))
{
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
Rectangle pageSize = pdfReader.GetPageSize(page);
PdfContentByte canvas = pdfStamper.GetOverContent(page);
canvas.SetColorFill(BaseColor.WHITE);
canvas.Rectangle(pageSize.Left, pageSize.Bottom, pageSize.Width, pageSize.Height);
canvas.Fill();
}
}
or remove the content as a whole.
using (PdfReader pdfReader = new PdfReader(input))
{
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
PdfDictionary pageDictionary = pdfReader.GetPageN(page);
pageDictionary.Remove(PdfName.CONTENTS);
}
using (PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(output, FileMode.Create, FileAccess.Write)))
{
}
}
As the form fields are not part of the content but as annotation hover above it, you can do so either before or after filling the form.
Upvotes: 1