现有pdf中的水印(文字或图像)

时间:2016-01-07 07:00:37

标签: c# itextsharp

如何在c#?

中的现有pdf中添加水印(文本或图像)

我希望为pdf的所有页面显示水印。

我尝试使用itextsharp,但水印只显示在pdf的最后一页。

    public void CreateTemplate(string watermarkText, string targetFileName)
    {
        var document = new Document();
        var pdfWriter = PdfWriter.GetInstance(document, new FileStream(targetFileName, FileMode.Create));
        var font = new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 60, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.LIGHT_GRAY);
        document.Open();
        ColumnText.ShowTextAligned(pdfWriter.DirectContent, Element.ALIGN_CENTER, new Phrase(watermarkText, font), 300, 400, 45);
        document.Close();
    }
    public void AddTextWatermark(string sourceFilePath, string watermarkTemplatePath, string targetFilePath)
    {
        var pdfReaderSource = new PdfReader(sourceFilePath);
        var pdfStamper = new PdfStamper(pdfReaderSource, new FileStream(targetFilePath, FileMode.Create));
        var pdfReaderTemplate = new PdfReader(watermarkTemplatePath);
        var page = pdfStamper.GetImportedPage(pdfReaderTemplate, 1);

        for (var i = 0; i < pdfReaderSource.NumberOfPages; i++)
        {
            var content = pdfStamper.GetUnderContent(i + 1);
            content.AddTemplate(page, 0, 0);
        }

        pdfStamper.Close();
        pdfReaderTemplate.Close();
    }

1 个答案:

答案 0 :(得分:0)

以下内容受Bruno Lowagie的' iText in Action - 2nd Edition '的启发。我使用的是iTextSharp版本5.4。

下面的代码将文本水印和透明图像水印添加到现有的pdf中。评论中的详细信息......

public interface IWriter { void Write(Stream stream); }

public class TextAndImageWatermarker : IWriter 
{
  public readonly string INPUT_PDF = "the_pdf_you_are_watermarking";

  // inner class for text watermark
  class TextWatermarkPdfPageEventHelper : PdfPageEventHelper
  {
      static readonly Font FONT = new Font(Font.FontFamily.HELVETICA, 40, Font.NORMAL, new GrayColor(0.75f));

      // write text SW to NE for odd pages, NW to SE for even pages
      public override void OnEndPage(PdfWriter writer, Document document)
      {
          ColumnText.ShowTextAligned(
            writer.DirectContentUnder,
            Element.ALIGN_CENTER, new Phrase("watermark (text or image) in existing pdf", FONT),
            300, 400, writer.PageNumber % 2 == 1 ? 60 : -60
          );
      }
  }

  // inner class for image watermark
  class ImageWatermarkPdfPageEventHelper : PdfPageEventHelper
  {
      // the image you use as a watermark 
      static readonly Image img = null;

      public override void OnEndPage(PdfWriter writer, Document document)
      {
          img.SetAbsolutePosition(
              (document.PageSize.Width - img.ScaledWidth) / 4,
              (document.PageSize.Height - img.ScaledHeight) / 4
            );

          writer.DirectContentUnder.SaveState();

          writer.DirectContentUnder.SetGState(new PdfGState() { FillOpacity = 0.5f });
          writer.DirectContentUnder.AddImage(img, true);

          writer.DirectContentUnder.RestoreState();
      }
  }

  public void Write(Stream stream)
  {
      var reader = new PdfReader(INPUT_PDF);
      using (reader)
      {
          using (Document document = new Document())
          {
              // trick is to use page events
              PdfWriter writer = PdfWriter.GetInstance(document, stream);
              writer.PageEvent = new TextWatermarkPdfPageEventHelper();
              writer.PageEvent = new ImageWatermarkPdfPageEventHelper();

              document.Open();
              var n = reader.NumberOfPages;

              // dump pages from source, watermarks will be added OnEndPage
              for (int i = 1; i <= n; i++)
              {
                  document.NewPage();
                  var pagei = writer.GetImportedPage(reader, i);
                  writer.DirectContentUnder.AddTemplate(pagei, 0, 0);
              }
          }
      }
    }
}