Skip to content

Instantly share code, notes, and snippets.

@farhan-raza
Created January 9, 2021 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save farhan-raza/dc9827687893fc506a96bc3c92debbbd to your computer and use it in GitHub Desktop.
Save farhan-raza/dc9827687893fc506a96bc3c92debbbd to your computer and use it in GitHub Desktop.
Insert or Delete Text/Image Watermark in PDF File using C#
// Load input PDF document
Document pdfDocument = new Document(dataDir + "Input.pdf");
// Access any page of the input PDF
Page testpage = pdfDocument.Pages[1];
// Create image stamp
ImageStamp imageStamp = new ImageStamp(dataDir + "aspose-logo.png");
imageStamp.Background = true;
imageStamp.Height = 300;
imageStamp.Width = 300;
// Center adjust the image watermark based on page dimensions
imageStamp.XIndent = (testpage.PageInfo.Width / 2) - (imageStamp.Width / 2);
imageStamp.YIndent = (testpage.PageInfo.Height / 2) - (imageStamp.Height / 2);
imageStamp.Opacity = 0.5;
// Set stamp id for deleting the watermark later, if required
imageStamp.setStampId(12345678);
// Add stamp to particular page
//pdfDocument.Pages[1].AddStamp(imageStamp);
// Add stamp to each page of PDF
foreach (Page page in pdfDocument.Pages)
{
page.AddStamp(imageStamp);
}
dataDir = dataDir + "Add_Image_Watermark.pdf";
// Save output document
pdfDocument.Save(dataDir);
// Open document
Document pdfDocument = new Document(dataDir + "Input.pdf");
// Create text stamp
TextStamp textStamp = new TextStamp("CONFIDENTIAL");
// Set origin
textStamp.XIndent = 25;
textStamp.YIndent = 400;
// Set text properties
textStamp.TextState.Font = FontRepository.FindFont("Arial");
textStamp.TextState.FontSize = 72.0F;
textStamp.TextState.FontStyle = FontStyles.Italic;
textStamp.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Gray);
textStamp.Opacity = 50;
// Set Stamp ID for text watermark to later identify it
textStamp.setStampId(123456);
// Add stamp to particular page
pdfDocument.Pages[1].AddStamp(textStamp);
dataDir = dataDir + "Add_Text_Watermark.pdf";
// Save output document
pdfDocument.Save(dataDir);
// Initialize PdfContentEditor class object
PdfContentEditor contentEditor = new PdfContentEditor();
// Call BindPdf method
contentEditor.BindPdf(dataDir + "Watermark.pdf");
// Delete watermark using specific id
contentEditor.DeleteStampById(12345678);
// Save output PDF with removed watermark
contentEditor.Save(dataDir + @"Remove_Watermark.pdf");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment