C# iTextSharp 创建PDF水印

刚刚有人留言说需要 iTextSharp 创建PDF水印代码
那就贴一个以前写好的。

   public static void SetWatermark(string inputfilepath, string outputfilepath, string waterMarkName)
    {
        PdfReader pdfReader = null;
        PdfStamper pdfStamper = null;
        try
        {
            pdfReader = new PdfReader(inputfilepath);
            pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create));
            int total = pdfReader.NumberOfPages + 1;
            iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);
            float width = psize.Width;
            float height = psize.Height;
            PdfContentByte content;
            BaseFont font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            PdfGState gs = new PdfGState();
            for (int i = 1; i < total; i++)
            {
                content = pdfStamper.GetOverContent(i);//在内容上方加水印
                //content = pdfStamper.GetUnderContent(i);//在内容下方加水印
                //透明度
                gs.FillOpacity = 0.6f;
                content.SetGState(gs);
                //content.SetGrayFill(0.3f);
                //开始写入文本
                content.BeginText();
                content.SetColorFill(BaseColor.GRAY);
                content.SetFontAndSize(font, 50);
                content.SetTextMatrix(0, 0);
                content.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, width / 2 - 50, height / 2 - 50, 45);

                content.EndText();
            }
            for (int i = 1; i < total; i++)
            {
                /* 开始增加页码 */

                content = pdfStamper.GetOverContent(i);
                gs.FillOpacity = 0.8f;

                content.SetGState(gs);
                content.BeginText();
                content.SetColorFill(BaseColor.BLACK);
                content.SetFontAndSize(font, 12);
                content.ShowTextAligned(Element.ALIGN_CENTER, "第" + i.ToString() + "页 " + "共" + (total - 1).ToString() + "页", width / 2 - 5, 35, 0);
                content.EndText();
            }

        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {

            if (pdfStamper != null)
                pdfStamper.Close();

            if (pdfReader != null)
                pdfReader.Close();
        }
    }

你可能感兴趣的:(C#)