與水印共事

這個主題討論了如何在 Aspose.Words 中以程式方式使用水印。 水印是文檔中顯示在文字背後的背景圖像。 一個水印可以包含由 Watermark 類別所代表的一句文字或一張圖像。

在文件上加水印

在 Microsoft Word 中,您可以使用 Insert Watermark 指令在文件中輕鬆插入水印。 Aspose.Words 提供 watermark 類別,用於在文件中添加或移除水印。 Aspose.Words 提供了定義三種可能的水印類型(文字、圖像和無)的 WatermarkType 列舉類型,以便您進行處理。

添加文字水印

接下來的程式碼範例示範了如何透過定義 TextWatermarkOptions 來在文件中插入文字水印,並使用 SetText 方法。

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Document.doc");
TextWatermarkOptions options = new TextWatermarkOptions()
{
FontFamily = "Arial",
FontSize = 36,
Color = Color.Black,
Layout = WatermarkLayout.Horizontal,
IsSemitrasparent = false
};
doc.Watermark.SetText("Test", options);
doc.Save(dataDir + "AddTextWatermark_out.docx");

添加圖像水印

以下程式碼範例示範了如何透過定義 ImageWatermarkOptions 來在文件中插入圖像水印,並使用 SetImage 方法:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Document.doc");
ImageWatermarkOptions options = new ImageWatermarkOptions()
{
Scale = 5,
IsWashout = false
};
doc.Watermark.SetImage(Image.FromFile(dataDir + "Watermark.png"), options);
doc.Save(dataDir + "AddImageWatermark_out.docx");

您也可以透過使用形狀類別來插入水印。 您可以輕易地將任何形狀或圖像插入到標題欄或腳欄中,進而創造出所有想像得到的水印。

以下程式碼範例在 Word 文檔中插入水印:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
[Test]
public void AddWatermark()
{
Document doc = new Document(MyDir + "Document.docx");
InsertWatermarkText(doc, "CONFIDENTIAL");
doc.Save(ArtifactsDir + "WorkWithWatermark.AddWatermark.docx");
}
/// <summary>
/// Inserts a watermark into a document.
/// </summary>
/// <param name="doc">The input document.</param>
/// <param name="watermarkText">Text of the watermark.</param>
private void InsertWatermarkText(Document doc, string watermarkText)
{
// Create a watermark shape, this will be a WordArt shape.
Shape watermark = new Shape(doc, ShapeType.TextPlainText) { Name = "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.FillColor = Color.Gray;
watermark.StrokeColor = Color.Gray;
// Place the watermark in the page center.
watermark.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
watermark.RelativeVerticalPosition = RelativeVerticalPosition.Page;
watermark.WrapType = WrapType.None;
watermark.VerticalAlignment = VerticalAlignment.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 could be up to three different headers in each section.
// Since we want the watermark to appear on all pages, insert it into all headers.
InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderPrimary);
InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderFirst);
InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderEven);
}
}
private 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, so we need to 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));
}

從文件中移除水印

Watermark 類別提供 remove 方法,從文件中移除水印。

以下範例示範了如何從文件中移除水印。

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "AddTextWatermark_out.docx");
if (doc.Watermark.Type == WatermarkType.Text)
{
doc.Watermark.Remove();
}
doc.Save(dataDir + "RemoveWatermark_out.docx");

若使用 Shape 類別物件添加水印,若要從文件中移除該水印,僅需在插入時設定水印樣式名稱即可,然後再以所分配的名稱移除該水印樣式。

接下來這段程式碼示例會教你如何設定水印形状的名称並將其從文件中移除:

// Set name to be able to remove it afterwards
watermark.Name("WaterMark");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public static void Run()
{
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithImages();
string fileName = "RemoveWatermark.docx";
Document doc = new Document(dataDir + fileName);
RemoveWatermarkText(doc);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
doc.Save(dataDir);
}
private static void RemoveWatermarkText(Document doc)
{
foreach (HeaderFooter hf in doc.GetChildNodes(NodeType.HeaderFooter, true))
{
foreach (Shape shape in hf.GetChildNodes(NodeType.Shape, true))
{
if (shape.Name.Contains("WaterMark"))
{
shape.Remove();
}
}
}
}
}

在一個表格單元格中加入水印。

有時你需要將水印/圖片放入表格儲存格中,並顯示在表格外,你可以使用 IsLayoutInCell 屬性。 此屬性取得或設定一旗幟,表示該形狀是否在表格中顯示或在外面。 請注意,這特性只有在使用 OptimizeFor 方法優化文件為 Microsoft Word 2010 時才有效。

接下來的程式碼範例示範了如何使用這個屬性:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + @"LayoutInCell.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
Shape watermark = new Shape(doc, ShapeType.TextPlainText);
watermark.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
watermark.RelativeVerticalPosition = RelativeVerticalPosition.Page;
watermark.IsLayoutInCell = true; // Display the shape outside of table cell if it will be placed into a cell.
watermark.Width = 300;
watermark.Height = 70;
watermark.HorizontalAlignment = HorizontalAlignment.Center;
watermark.VerticalAlignment = VerticalAlignment.Center;
watermark.Rotation = -40;
watermark.Fill.Color = Color.Gray;
watermark.StrokeColor = Color.Gray;
watermark.TextPath.Text = "watermarkText";
watermark.TextPath.FontFamily = "Arial";
watermark.Name = string.Format("WaterMark_{0}", Guid.NewGuid());
watermark.WrapType = WrapType.None;
Run run = doc.GetChildNodes(NodeType.Run, true)[doc.GetChildNodes(NodeType.Run, true).Count - 1] as Run;
builder.MoveTo(run);
builder.InsertNode(watermark);
doc.CompatibilityOptions.OptimizeFor(MsWordVersion.Word2010);
dataDir = dataDir + "Shape_IsLayoutInCell_out.docx";
// Save the document to disk.
doc.Save(dataDir);