Aspose. Words: Add watermarks to Word documents. aspose. wordsword
Requirement: when important Word documents need to be printed, add a watermark to indicate the source.
Solution: Use the Aspose component to send a Word document
Code: dry goods:
/// <Summary>
/// Inserts a watermark into a document.
/// </Summary>
/// <Param name = "doc"> The input document. </param>
/// <Param name = "watermarkText"> Text of the watermark. </param>
Private static void InsertWatermarkText (Document doc, string watermarkText)
{
// Create a watermark shape. This will be a WordArt shape.
// You are free to try other shape types as watermarks.
Aspose. Words. Drawing. Shape watermark = new Aspose. Words. Drawing. Shape (doc, ShapeType. TextPlainText );
// Set up the text of the watermark.
Watermark. TextPath. Text = watermarkText;
Watermark. TextPath. FontFamily = "Arial ";
Watermark. Width = 500;
Watermark. Height = 100;
// Text will be directed from the bottom-left to the top-right corner.
Watermark. Rotation =-40;
// Remove the following two lines if you need a solid black text.
Watermark. Fill. Color = System. Drawing. Color. Gray; // Try LightGray to get more Word-style watermark
Watermark. StrokeColor = System. Drawing. Color. Gray; // Try LightGray to get more Word-style watermark
// Place the watermark in the page center.
Watermark. RelativeHorizontalPosition = RelativeHorizontalPosition. Page;
Watermark. RelativeVerticalPosition = RelativeVerticalPosition. Page;
Watermark. WrapType = WrapType. None;
Watermark. VerticalAlignment = verticalignment. Center;
Watermark. HorizontalAlignment = HorizontalAlignment. Center;
// Create a new paragraph and append the watermark to this paragraph.
Paragraph watermarkPara = new Paragraph (doc );
WatermarkPara. AppendChild (watermark );
// Insert the watermark into all headers of each document section.
Foreach (Section sect in doc. Sections)
{
// There cocould be up to three different headers in each section, since we want
// The watermark to appear on all pages, insert into all headers.
InsertWatermarkIntoHeader (watermarkPara, sect, HeaderFooterType. HeaderPrimary );
InsertWatermarkIntoHeader (watermarkPara, sect, HeaderFooterType. HeaderFirst );
InsertWatermarkIntoHeader (watermarkPara, sect, HeaderFooterType. HeaderEven );
}
}
Private static void InsertWatermarkIntoHeader (Paragraph watermarkPara, Section sect, HeaderFooterType headerType)
{
HeaderFooter header = sect. HeadersFooters [headerType];
If (header = null)
{
// There is no header of the specified type in the current section, create it.
Header = new HeaderFooter (sect. Document, headerType );
Sect. HeadersFooters. Add (header );
}
// Insert a clone of the watermark into the header.
Header. AppendChild (watermarkPara. Clone (true ));
}