简体   繁体   中英

iTextSharp Add Watermark Only If it Doesn't Already Exist

Does anyone know if there is a way to check for a watermark on a PDF document using iTextSharp?

I want to do this before adding a new one. In my case, I have to add a new watermark if it wasn't already added by someone, but I don't know how to check this using iTextSharp's PdfReader class. Something like this:

var reader = new PdfReader(bytes);
var stamper = new PdfStamper(reader, ms);
var dc = stamper.GetOverContent(pageNumber);
bool alreadyStamped = cd.CheckIfTextOrImageExists();

After some investigation thanks to the @ChrisHaas comment I was able to achieve that verification. So, if text is present on the particular page, I can find it using SimpleTextExtractionStrategy , even if it's in the WaterMark collection.

PdfReader pdfReader = new PdfReader(bytes);
  for (int page = 1; page <= pdfReader.NumberOfPages; page++)
  {
    ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();

    string currentPageText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
    if (currentPageText.Contains(searthText))
    {
      // adding new WaterMark here
      Console.WriteLine("text was found on page "+i);
    }
  }
pdfReader.Close();

Hopefully, this approach helps someone, who got a similar issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM