我迫切需要在不同類型的pdf上添加水印,包括普通pdf,數字簽名的pdf和密碼prodected pdf以編程方式使用C#。我可以對使用下面的代碼進行數字簽名的普通pdf和一些pdf進行水印處理,但對於數字簽名和安全保護的其他pdf文件不起作用。任何人都可以告訴我如何使用itextsharp刪除pdf的安全性,以便它們可以被嵌入水印。如何使用itextsharp去除PDF和水印的安全性pdf
以下代碼可以在不受安全保護但不能在安全保護pdf上加水印的普通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;
iTextSharp.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;
}
}
感謝
安全保護的重點在於您無法修改文檔。 – 2011-05-03 15:32:39