I have the code to create a watermark when the user uploads the file. the watermark is created in the middle page and the footer page. but my problem is the watermark work is not perfect depending on the contents of the uploaded file content. for more details try to note the image below :
And this is my code :
public bool InsertWaterMark(string path)
{
bool valid = true;
string FileDestination = AppDomain.CurrentDomain.BaseDirectory + "Content/" + path;
string FileOriginal = AppDomain.CurrentDomain.BaseDirectory + "Content/" + path.Replace("FileTemporary", "FileOriginal");
System.IO.File.Copy(FileDestination, FileOriginal);
string watermarkText = "Controlled Copy";
PdfReader reader = new PdfReader(FileOriginal);
using (FileStream fs = new FileStream(FileDestination, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (PdfStamper stamper = new PdfStamper(reader, fs))
{
int pageCount = reader.NumberOfPages;
for (int i = 1; i <= pageCount; i++)
{
PdfContentByte cbCenter = stamper.GetUnderContent(i);
PdfGState gState = new PdfGState();
cbCenter.BeginText();
iTextSharp.text.Rectangle rect = reader.GetPageSize(i);
cbCenter.SetColorFill(BaseColor.GRAY);
gState.FillOpacity = 0.15f;
cbCenter.SetGState(gState);
cbCenter.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 80);
cbCenter.ShowTextAligned(PdfContentByte.ALIGN_CENTER, watermarkText, rect.Width / 2, rect.Height / 2, 45f);
cbCenter.EndText();
PdfContentByte cbFooter = stamper.GetUnderContent(i);
PdfGState gStateFooter = new PdfGState();
cbFooter.BeginText();
cbFooter.SetColorFill(BaseColor.RED);
gStateFooter.FillOpacity = 1f;
cbFooter.SetGState(gStateFooter);
cbFooter.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_OBLIQUE, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12);
cbFooter.ShowTextAligned(PdfContentByte.ALIGN_CENTER, '"' + "When printed, this documents are considered uncontrolled" + '"', 300.7f, 10.7f, 0);
cbFooter.EndText();
}
}
}
reader.Close();
return valid;
}
Please correct my code and give a solution. Thanks Advance
You are using stamper.GetUnderContent(i)
, which means that you are adding content under the existing content.
In other words: the watermark is covered by the existong content. If the existing content is opaque, the watermark will be invisible. You will be able to see the shape if you do Ctrl+A, but you won't see it when printing the page.
In example ALFA, you see the watermark under the existing text, because the existing text has no background. In example CARLIE, you don't see it because the text has a white background that covers the watermark.
How to fix this? Use stamper.GetOverContent(i)
instead of stamper.GetUnderContent(i)
.
Also: why are you still using iTextSharp version 5 or earlier? The current version is iText 7 for .NET. Please upgrade!