Làm việc với Hình mờ

Chủ đề này thảo luận về cách làm việc theo chương trình với hình mờ bằng Aspose.Words. Hình mờ là hình nền hiển thị phía sau văn bản trong tài liệu. Hình mờ có thể chứa văn bản hoặc hình ảnh được đại diện bởi lớp Watermark.

Thêm hình mờ vào tài liệu

Trong Microsoft Word, hình mờ có thể dễ dàng được chèn vào tài liệu bằng lệnh Chèn hình mờ. Aspose.Words cung cấp lớp watermark để thêm hoặc xóa hình mờ trong tài liệu. Aspose.Words cung cấp Loại hình mờenumeration xác định ba loại hình mờ có thể sử dụng (Văn bản, Hình ảnh và Không có)

Thêm hình mờ văn bản

Ví dụ về mã sau đây minh họa cách chèn hình mờ văn bản vào tài liệu bằng cách xác định TextWatermarkOptions bằng phương pháp 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");

Thêm hình mờ hình ảnh

Ví dụ mã sau đây minh họa cách chèn hình mờ hình ảnh vào tài liệu bằng cách xác định ImageWatermarkOptions bằng phương pháp 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");

Hình mờ cũng có thể được chèn bằng cách sử dụng lớp hình dạng. Rất dễ dàng để chèn bất kỳ hình dạng hoặc hình ảnh nào vào đầu trang hoặc chân trang và do đó tạo ra hình mờ thuộc bất kỳ loại nào có thể tưởng tượng được.

Ví dụ mã sau đây chèn hình mờ vào tài liệu 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));
}

Xóa hình mờ khỏi tài liệu

Lớp Watermark cung cấp phương thức xóa để xóa hình mờ khỏi tài liệu.

Ví dụ mã sau đây cho thấy cách xóa hình mờ khỏi tài liệu:

// 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");

Nếu hình mờ được thêm bằng đối tượng lớp Shape thì để xóa hình mờ khỏi tài liệu, bạn chỉ phải đặt tên của hình mờ trong khi chèn và sau đó xóa hình mờ theo tên được gán.

Ví dụ về mã sau đây chỉ cho bạn cách đặt tên của hình mờ và xóa nó khỏi tài liệu:

// 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();
}
}
}
}
}

Thêm hình mờ vào ô bảng

Đôi khi bạn cần chèn hình mờ/hình ảnh vào ô của bảng và hiển thị nó bên ngoài bảng, bạn có thể sử dụng thuộc tính IsLayoutInCell. Thuộc tính này nhận hoặc đặt cờ cho biết hình dạng được hiển thị bên trong hay bên ngoài bảng. Lưu ý rằng thuộc tính này chỉ hoạt động khi bạn tối ưu hóa tài liệu cho Microsoft Word 2010 bằng phương pháp OptimizeFor.

Ví dụ mã sau đây cho thấy cách sử dụng thuộc tính này:

// 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);