Stamp And Watermark

This example demonstrates how to draw stamp and watermark

Source DOC or DOCX file:
Convert HTML from:
Source image file:
Watermark Text:

Watermarks are used in the form of a logo, discreetly placed on a slide or page to brand the word document we are considering text and image base watermark

  • Text - Stamping a word document a simple text which is easy to do like using term "copy" to notify user that this is just a copy of original
  • Image - Stamping image becomes very helpful when there is a need to watermark a complex design like logo .

Selecting a word document file which we need to watermark

Stamping text - User can input any text which he/she wanted to use as watermark

Watermark Image - Choose any image which user need to add as watermark.

After clicking generate button it will generate a file with above choosen word version and user selected watermark

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;

using OfficeComponent.Word;


namespace OfficeComponent.Samples
{
    class StampAndWatermarkExample : WordExampleBase
#if WEB
, IUIExample
#endif
    {
        public string FileName;
        public string WatermarkText { get; set; }

        public bool DoWatermarkImage { get; set; }
        public string WatermarkImageFileName { get; set; }

        public StampAndWatermarkExample()
            : base(null, null)
        {

        }

        public StampAndWatermarkExample(string commonDataPath, string outputDir)
            : base(commonDataPath, outputDir)
        {

        }

        public StampAndWatermarkExample(string commonDataPath, string outputDir, string xmlFile) : base(commonDataPath, outputDir, xmlFile)
        {

        }

        public override string Execute()
        {
#if WEB
            ProcessForm();
#endif
            if (string.IsNullOrWhiteSpace(FileName))
            {
                ShowError("Please specify a file name.");
                return null;
            }

            // Create a new instance of PdfDocument class.
            WordDocument document = new WordDocument(FileName);

            if (DoWatermarkImage) // If Image watermark selected.
            {
                if (string.IsNullOrWhiteSpace(WatermarkImageFileName))
                {
                    ShowError("Please specify the image file.");
                    return null;
                }

                // Create a new Picture watermark object and set the Picture property to the loaded image.
                PictureWatermark picWatermark = new PictureWatermark();
                picWatermark.Picture = Image.FromFile(WatermarkImageFileName);
                picWatermark.Washout = false;

                // Set watermark.
                document.Watermark = picWatermark;
            }
            else // If Text watermark selected.
            {
                if (string.IsNullOrWhiteSpace(WatermarkText))
                {
                    ShowError("Please specify the watermark text.");
                    return null;
                }

                // Create a new TextWatermark object and set text color and size.
                TextWatermark textWatermark = new TextWatermark(WatermarkText);
                textWatermark.Color = Color.FromArgb(120, 255, 0, 0);
                textWatermark.Size = 100;

                // Set watermark.
                document.Watermark = textWatermark;
            }

            string fileName = Path.Combine(OutputDir, this.GetType().Name + "_" + Guid.NewGuid().ToString() + GetExtension(SaveAsFormat));
            // Save the document.
            document.Save(fileName, SaveAsFormat);

            // Close the document.
            document.Close();


            return fileName;
        }
        private static void GetHyperLinks(WordDocument document, List webLinks, List emailLinks, List fileLinks, List bookmarks)
        {
            foreach (Section section in document.Sections)
            {
                foreach (Paragraph paragraph in section.Body.Paragraphs)
                {
                    foreach (ParagraphItem item in paragraph.Items)
                    {
                        Field field = item as Field;

                        if (field != null && field.FieldType == FieldType.FieldHyperlink)
                        {
                            Hyperlink hlink = new Hyperlink(field);

                            switch (hlink.Type)
                            {
                                case HyperlinkType.WebLink:
                                    if (hlink.PictureToDisplay == null)
                                        webLinks.Add(hlink);
                                    break;
                                case HyperlinkType.EMailLink:
                                    emailLinks.Add(hlink);
                                    break;
                                case HyperlinkType.FileLink:
                                    fileLinks.Add(hlink);
                                    break;
                                case HyperlinkType.Bookmark:
                                    bookmarks.Add(hlink);
                                    break;
                            }
                        }
                    }
                }
            }
        }

        public override string ActionTitle
        {
            get
            {
                return "Process";
            }
        }

#if WEB
        void ProcessForm()
        {
            FileName = GetPostFile("SourceFile");
            WatermarkImageFileName = GetPostFile("WatermarkImageFileName");
        }
#endif
    }
}
Imports System.Drawing.Imaging
Imports System.IO
Imports System.Text

Imports OfficeComponent.Word


Namespace OfficeComponent.Samples
#If WEB Then
	Friend Class StampAndWatermarkExample
		Inherits WordExampleBase
		Implements IUIExample
#Else
	Friend Class StampAndWatermarkExample
		Inherits WordExampleBase
#End If
		Public FileName As String
		Private privateWatermarkText As String
		Public Property WatermarkText() As String
			Get
				Return privateWatermarkText
			End Get
			Set(ByVal value As String)
				privateWatermarkText = value
			End Set
		End Property

		Private privateDoWatermarkImage As Boolean
		Public Property DoWatermarkImage() As Boolean
			Get
				Return privateDoWatermarkImage
			End Get
			Set(ByVal value As Boolean)
				privateDoWatermarkImage = value
			End Set
		End Property
		Private privateWatermarkImageFileName As String
		Public Property WatermarkImageFileName() As String
			Get
				Return privateWatermarkImageFileName
			End Get
			Set(ByVal value As String)
				privateWatermarkImageFileName = value
			End Set
		End Property

		Public Sub New()
			MyBase.New(Nothing, Nothing)

		End Sub

		Public Sub New(ByVal commonDataPath As String, ByVal outputDir As String)
			MyBase.New(commonDataPath, outputDir)

		End Sub

		Public Sub New(ByVal commonDataPath As String, ByVal outputDir As String, ByVal xmlFile As String)
			MyBase.New(commonDataPath, outputDir, xmlFile)

		End Sub

		Public Overrides Function Execute() As String
#If WEB Then
			ProcessForm()
#End If
			If String.IsNullOrWhiteSpace(FileName) Then
				ShowError("Please specify a file name.")
				Return Nothing
			End If

			' Create a new instance of PdfDocument class.
			Dim document As New WordDocument(FileName)

			If DoWatermarkImage Then ' If Image watermark selected.
				If String.IsNullOrWhiteSpace(WatermarkImageFileName) Then
					ShowError("Please specify the image file.")
					Return Nothing
				End If

				' Create a new Picture watermark object and set the Picture property to the loaded image.
				Dim picWatermark As New PictureWatermark()
				picWatermark.Picture = Image.FromFile(WatermarkImageFileName)
				picWatermark.Washout = False

				' Set watermark.
				document.Watermark = picWatermark
			Else ' If Text watermark selected.
				If String.IsNullOrWhiteSpace(WatermarkText) Then
					ShowError("Please specify the watermark text.")
					Return Nothing
				End If

				' Create a new TextWatermark object and set text color and size.
				Dim textWatermark As New TextWatermark(WatermarkText)
				textWatermark.Color = Color.FromArgb(120, 255, 0, 0)
				textWatermark.Size = 100

				' Set watermark.
				document.Watermark = textWatermark
			End If

'INSTANT VB NOTE: The variable fileName was renamed since Visual Basic does not handle local variables named the same as class members well:
			Dim fileName_Renamed As String = Path.Combine(OutputDir, Me.GetType().Name & "_" & Guid.NewGuid().ToString() & GetExtension(SaveAsFormat))
			' Save the document.
			document.Save(fileName_Renamed, SaveAsFormat)

			' Close the document.
			document.Close()


			Return fileName_Renamed
		End Function
		Private Shared Sub GetHyperLinks(ByVal document As WordDocument, ByVal webLinks As List(Of Hyperlink), ByVal emailLinks As List(Of Hyperlink), ByVal fileLinks As List(Of Hyperlink), ByVal bookmarks As List(Of Hyperlink))
			For Each section As Section In document.Sections
				For Each paragraph As Paragraph In section.Body.Paragraphs
					For Each item As ParagraphItem In paragraph.Items
						Dim field As Field = TryCast(item, Field)

						If field IsNot Nothing AndAlso field.FieldType = FieldType.FieldHyperlink Then
							Dim hlink As New Hyperlink(field)

							Select Case hlink.Type
								Case HyperlinkType.WebLink
									If hlink.PictureToDisplay Is Nothing Then
										webLinks.Add(hlink)
									End If
								Case HyperlinkType.EMailLink
									emailLinks.Add(hlink)
								Case HyperlinkType.FileLink
									fileLinks.Add(hlink)
								Case HyperlinkType.Bookmark
									bookmarks.Add(hlink)
							End Select
						End If
					Next item
				Next paragraph
			Next section
		End Sub

		Public Overrides ReadOnly Property ActionTitle() As String
			Get
				Return "Process"
			End Get
		End Property

#If WEB Then
		Private Sub ProcessForm()
			FileName = GetPostFile("SourceFile")
			WatermarkImageFileName = GetPostFile("WatermarkImageFileName")
		End Sub
#End If
	End Class
End Namespace