How to use itextsharp to remove the security of a PDF and water watermark the pdf
I urgently need to add watermark on different types of pdf including normal pdf, digitally signed pdf and password prodected pdf programatically using C#. I can watermark normal pdf and some pdf that are digitally signed using the code below but, it doesn't works for other pdfs that are digitally signed and security protected. Can anyone tell me how to remove the security of a pdf using itextsharp so that they can be watermarked.
The following code can add watermark on normal pdf that are not security protected but cannot watermark on the security protected pdf.
public void AddWatermarkText(string sourceFile, string outputFile,
string watermarkText, iTextSharp.text.pdf.BaseFont watermarkFont, float
watermarkFontSize, iTextSharp.text.Color watermarkFontColor, float
watermarkFontOpacity, float watermarkRotation)
{
iTextSharp.text.pdf.PdfReader reader = null;
iTextSh开发者_如何学JAVAarp.text.pdf.PdfStamper stamper = null;
iTextSharp.text.pdf.PdfGState gstate = null;
iTextSharp.text.pdf.PdfContentByte underContent = null;
iTextSharp.text.Rectangle rect = null;
int pageCount = 0;
try
{
{
reader = new iTextSharp.text.pdf.PdfReader(sourceFile);
rect = reader.GetPageSizeWithRotation(1);
stamper = new PdfStamper(reader, new System.IO.FileStream(outputFile, System.IO.FileMode.CreateNew), '\0', true);
if (watermarkFont == null)
{
watermarkFont =iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA,iTextSharp.text.pdf.BaseFont.CP1252,iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED);
}
if (watermarkFontColor == null)
{
watermarkFontColor = iTextSharp.text.Color.BLUE;
}
gstate = new iTextSharp.text.pdf.PdfGState();
gstate.FillOpacity = watermarkFontOpacity;
gstate.StrokeOpacity = watermarkFontOpacity;
pageCount = reader.NumberOfPages;
for (int i = 1; i <= pageCount; i++)
{
underContent = stamper.GetUnderContent(i);
//_with1 = underContent;
underContent.SaveState();
underContent.SetGState(gstate);
underContent.SetColorFill(watermarkFontColor);
underContent.BeginText();
underContent.SetFontAndSize(watermarkFont,watermarkFontSize);
underContent.SetTextMatrix(30, 30);
underContent.ShowTextAligned(iTextSharp.text.Element.ALIGN_CENTER,watermarkText,rect.Width / 2, rect.Height / 2, watermarkRotation);
underContent.EndText();
underContent.RestoreState();
}
}
stamper.Close();
reader.Close();
}
catch (Exception ex)
{
throw ex;
}
}
Thanks
iTextSharp.text.pdf.PdfReader allows you to specify an Owner Password as an argument if you know the password. There are also numerous online web sites that you can use to remove the security settings of a PDF file if you LEGALLY have the right to do so. iTextSharp cannot remove security setttings.
精彩评论