Word (RTF) Watermarks

This demo illustrates how to use Word Processing Document API to add and remove watermarks. Use the right panel to set text or image watermark options, or to delete the watermark. Use the PDF Viewer's toolbar items to print or export the result.

Image Watermark
Text Watermark
Watermark text:
Color:
Font name:
Font size:
@model AspNetCoreDemos.OfficeFileAPI.WordRTFPreviewModel

<iframe id="previewFrame" src="@Url.Action(Model.PreviewDocumentAction, Model.ControllerName)" height="@Model.IFrameSize" class="demo-preview-border" style="width:100%;box-sizing:border-box"></iframe>

<script type="text/javascript">
    WordRTFPreview = {
        basePath: '@Url.Action(Model.PreviewDocumentAction, Model.ControllerName)',
        Update: function (param) {
            var iframeElementName = "previewFrame";
            var iframeElement = document.getElementById(iframeElementName);
            if (!iframeElement)
                return;
            var additionalParams = "&" + new Date().valueOf();
            if (param)
                additionalParams = param;
            iframeElement.src = this.basePath + "?" + additionalParams;
        }
    };
</script>
@model AspNetCoreDemos.OfficeFileAPI.WordRTFWatermarkModel
@using DevExtreme.AspNet.Mvc

<div class="demo-view-container">
    @await Html.PartialAsync("WordRTFPreviewPartial", Model.PreviewModel)
</div>

<script type="text/javascript">
    function UpdatePreview(action) {
        var chbWashoutValue = $("#Washout").dxCheckBox('instance').option('value');
        var chbSemitransparentValue = $("#Semitransparent").dxCheckBox('instance').option('value');
        var chbDiagonalValue = $("#Diagonal").dxCheckBox('instance').option('value');
        var chbWatermarkTextValue = $("#WatermarkText").dxSelectBox('instance').option('value');
        var chbColorValue = $("#Color").dxColorBox('instance').option('value');
        var chbFontNameValue = $("#FontName").dxSelectBox('instance').option('value');
        var chbFontSizeValue = $("#FontSize").dxSelectBox('instance').option('value');
        var args = "Washout=" + encodeURIComponent(chbWashoutValue) +
            "&Semitransparent=" + encodeURIComponent(chbSemitransparentValue) +
            "&Diagonal=" + encodeURIComponent(chbDiagonalValue) +
            "&WatermarkText=" + encodeURIComponent(chbWatermarkTextValue) +
            "&Color=" + encodeURIComponent(chbColorValue) +
            "&FontName=" + encodeURIComponent(chbFontNameValue) +
            "&FontSize=" + encodeURIComponent(chbFontSizeValue);
        WordRTFPreview.basePath = GetActualPath(action);
        WordRTFPreview.Update(args);
    }
    function GetActualPath(action) {
        switch (action) {
            case 'image':
                return '@Url.Action("WordRTFImageWatermark", "ContentManipulation")';
            case 'text':
                return '@Url.Action("WordRTFTextWatermark", "ContentManipulation")';
            default:
                return '@Url.Action("WordRTFPreviewDefaultWatermark", "ContentManipulation")';
        }
    }
</script>

<div class="options">
    <div class="caption">Image Watermark</div>
    <div class="option" style="margin-top:10px">
        @(Html.DevExtreme().CheckBoxFor(m => m.Washout)
                           .ID("Washout")
                           .Text("Washout"))
    </div>
    <div class="option-buttons">
        @(Html.DevExtreme().Button()
                           .Text("Set image watermark")
                           .Type(ButtonType.Default)
                           .StylingMode(ButtonStylingMode.Contained)
                           .OnClick("function(s) { UpdatePreview('image'); }")
        )
    </div>
    <div class="caption" style="margin-top:20px">Text Watermark</div>
    <div class="option" style="margin-top:10px">
        @(Html.DevExtreme().CheckBoxFor(m => m.Semitransparent)
                           .ID("Semitransparent")
                           .Text("Semitransparent"))
    </div>
    <div class="option">
        @(Html.DevExtreme().CheckBoxFor(m => m.Diagonal)
                           .ID("Diagonal")
                           .Text("Diagonal"))
    </div>
    <div class="option">
        <div class="label">Watermark text:</div>
        @(Html.DevExtreme().SelectBoxFor(m => m.WatermarkText)
                           .ID("WatermarkText")
                           .DataSource(new List<string>
                                    {   "SAMPLE",
                                        "DRAFT",
                                        "CONFIDENTIAL",
                                        "DO NOT COPY",
                                        "TOP SECRET" })
        )
    </div>
    <div class="option">
        <div class="label">Color:</div>
        @(Html.DevExtreme().ColorBoxFor(m => m.Color)
                           .ID("Color")
        )
    </div>
    <div class="option">
        <div class="label">Font name:</div>
        @(Html.DevExtreme().SelectBoxFor(m => m.FontName)
                           .ID("FontName")
                           .DataSource(new List<string>
                                    {   "Calibri",
                                        "Cambria",
                                        "Courier New",
                                        "Tahoma",
                                        "Times New Roman" })
                           .Value("Calibri")
        )
    </div>
    <div class="option">
        <div class="label">Font size:</div>
        @(Html.DevExtreme().SelectBoxFor(m => m.FontSize)
                           .ID("FontSize")
                           .DataSource(new object[] {
                                new { Value = 0, Text = "Auto" },
                                new { Value = 36, Text = "36" },
                                new { Value = 40, Text = "40" },
                                new { Value = 44, Text = "44" },
                                new { Value = 48, Text = "48" },
                                new { Value = 54, Text = "54" },
                                new { Value = 60, Text = "60" },
                                new { Value = 66, Text = "66" },
                                new { Value = 72, Text = "72" },
                                new { Value = 80, Text = "80" },
                                new { Value = 90, Text = "90" },
                                new { Value = 96, Text = "96" },
                                new { Value = 105, Text = "105" },
                                new { Value = 120, Text = "120" },
                                new { Value = 144, Text = "144" }})
                           .ValueExpr("Value")
                           .DisplayExpr("Text")
        )
    </div>
    <div class="option-buttons">
        @(Html.DevExtreme().Button()
                           .Text("Set text watermark")
                           .Type(ButtonType.Default)
                           .StylingMode(ButtonStylingMode.Contained)
                           .OnClick("function(s) { UpdatePreview('text'); }")
        )
    </div>
    <div class="option-buttons">
        @(Html.DevExtreme().Button()
                           .Text("Delete watermark")
                           .Type(ButtonType.Default)
                           .StylingMode(ButtonStylingMode.Contained)
                           .OnClick("function(s) { UpdatePreview('delete'); }")
        )
    </div>
</div>
using Microsoft.AspNetCore.Hosting;

namespace AspNetCoreDemos.OfficeFileAPI {
    public partial class ContentManipulationController : DocumentProcessingController {
        public ContentManipulationController(IWebHostEnvironment hostingEnvironment) : base(hostingEnvironment) {
        }
    }
}
using System;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using DevExpress.Office.Services;
using DevExpress.XtraRichEdit;
using DevExpress.XtraRichEdit.API.Native;
using DevExpress.Web.Office;
using Microsoft.AspNetCore.Hosting;
using System.Drawing;

namespace AspNetCoreDemos.OfficeFileAPI {
    public partial class ContentManipulationController {
        const string wordRTFDocumentWatermarkDefaultFile = "/Documents/Watermarks.docx";
        const string fileAttachmentWatermarkImageFile = "/Documents/WatermarkImage.png";

        public IActionResult WordRTFWatermark() {
            WordRTFWatermarkModel model = new WordRTFWatermarkModel();
            return View(model);
        }

        public IActionResult WordRTFPreviewDefaultWatermark(WordRTFWatermarkModel model) {
            Stream stream = GetImageWatermarkDocumentContentStream(model, (m,s)=> { });
            return new FileStreamResult(stream, "application/pdf");
        }

        public IActionResult WordRTFImageWatermark(WordRTFWatermarkModel model) {
            Stream stream = GetImageWatermarkDocumentContentStream(model, SetImageWatermark);
            return new FileStreamResult(stream, "application/pdf");
        }
        public IActionResult WordRTFTextWatermark(WordRTFWatermarkModel model) {
            Stream stream = GetImageWatermarkDocumentContentStream(model, SetTextWatermark);
            return new FileStreamResult(stream, "application/pdf");
        }

        Stream GetImageWatermarkDocumentContentStream(WordRTFWatermarkModel model, Action<WordRTFWatermarkModel, RichEditDocumentServer> action) {
            RichEditDocumentServer documentServer = new RichEditDocumentServer();
            string filePath = HostingEnvironment.ContentRootPath + wordRTFDocumentWatermarkDefaultFile;
            documentServer.LoadDocument(filePath);
            action(model, documentServer);
            MemoryStream result = new MemoryStream();
            documentServer.ExportToPdf(result);
            result.Seek(0, SeekOrigin.Begin);
            return result;
        }
        void SetImageWatermark(WordRTFWatermarkModel model, RichEditDocumentServer server) {
            Image image = Image.FromFile(HostingEnvironment.ContentRootPath + fileAttachmentWatermarkImageFile);
            server.Document.WatermarkManager.SetImage(image, new ImageWatermarkOptions() { Washout = model.Washout, Scale = 2f });
        }
        void SetTextWatermark(WordRTFWatermarkModel model, RichEditDocumentServer server) {
            if(string.IsNullOrWhiteSpace(model.WatermarkText))
                return;
            TextWatermarkOptions options = new TextWatermarkOptions();
            options.FontFamily = model.FontName;
            options.FontSize = model.FontSize;
            options.Layout = model.Diagonal ? WatermarkLayout.Diagonal : WatermarkLayout.Horizontal;
            options.Semitransparent = model.Semitransparent;
            options.Color = model.Color;
            server.Document.WatermarkManager.SetText(model.WatermarkText, options);
        }
    }
}
namespace AspNetCoreDemos.OfficeFileAPI {
    public class WordRTFModelBase {
        public WordRTFModelBase() {
            PreviewModel = new WordRTFPreviewModel();
            PreviewModel.OwnerPropertyName = "PreviewModel";
            FileFormat = RichEditFileFormat.Rtf;
        }

        public RichEditFileFormat FileFormat { get; set; }
        public WordRTFPreviewModel PreviewModel { get; internal set; }
    }

    public class WordRTFPreviewModel {
        public WordRTFPreviewModel() {
        }

        public string OwnerPropertyName { get; set; }
        public string PreviewDocumentAction { get; set; }
        public string ControllerName { get; set; }
        public int IFrameSize { get; set; } = 452;
    }
}
using System.Drawing;

namespace AspNetCoreDemos.OfficeFileAPI {
    public class WordRTFWatermarkModel: WordRTFModelBase {

        public WordRTFWatermarkModel() {
            PreviewModel.PreviewDocumentAction = "WordRTFPreviewDefaultWatermark";
            PreviewModel.ControllerName = "ContentManipulation";
            PreviewModel.IFrameSize = 610;
        }

        public bool Washout { get; set; }
        public bool Semitransparent { get; set; } = true;
        public bool Diagonal { get; set; } = true;
        public string WatermarkText { get; set; } = "SAMPLE";
        public Color Color { get; set; } = Color.Silver;
        public string FontName { get; set; } = "Calibri";
        public int FontSize { get; set; }
    }
}