如何使用itextsharp删除PDF的安全性和水印PDF

时间:2011-05-03 15:24:14

标签: c#

我迫切需要在不同类型的pdf上添加水印,包括普通的pdf,数字签名的pdf和使用C#以编程方式提供的密码pdf。我可以使用下面的代码为普通的pdf和一些使用数字签名的pdf添加水印,但是它不适用于其他经过数字签名和安全保护的pdf。任何人都可以告诉我如何使用 itextsharp 删除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;
        }
    }

由于

1 个答案:

答案 0 :(得分:1)

iTextSharp.text.pdf.PdfReader允许您在知道密码时指定所有者密码作为参数。如果您有权这样做,还可以使用许多在线网站来删除PDF文件的安全设置。 iTextSharp无法删除安全设置。