Lavorare con la filigrana
In questo argomento viene illustrato come lavorare a livello di codice con la filigrana utilizzando Aspose.Words. Una filigrana è un’immagine di sfondo visualizzata dietro il testo in un documento. Una filigrana può contenere un testo o un’immagine rappresentata dalla classe Watermark.
Prova on-line
Puoi provare questa funzionalità con il nostro Filigrana per documenti online gratuita.
Aggiungi una filigrana a un documento
In Microsoft Word, una filigrana può essere facilmente inserita in un documento utilizzando il comando Inserisci filigrana. Aspose.Words fornisce la classe watermark per aggiungere o rimuovere la filigrana nei documenti. Aspose.Words fornisce l’enumerazione Tipo filigrana che definisce tre possibili tipi di filigrane (testo, immagine e nessuna) con cui lavorare
Aggiungi filigrana di testo
L’esempio di codice seguente dimostra come inserire una filigrana di testo in un documento definendo TextWatermarkOptions utilizzando il metodo 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"); |
Aggiungi filigrana immagine
L’esempio di codice seguente dimostra come inserire una filigrana di immagine in un documento definendo ImageWatermarkOptions utilizzando il metodo 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"); |
La filigrana può anche essere inserita utilizzando la classe forma. È molto semplice inserire qualsiasi forma o immagine nell’intestazione o nel piè di pagina e creare così una filigrana di qualsiasi tipo immaginabile.
L’esempio di codice seguente inserisce una filigrana in un documento di 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)); | |
} |
Rimuovi la filigrana da un documento
La classe Watermark fornisce il metodo di rimozione per rimuovere la filigrana da un documento.
Il seguente esempio di codice mostra come rimuovere una filigrana dai documenti:
// 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"); |
Se le filigrane vengono aggiunte utilizzando l’oggetto classe Shape, per rimuovere la filigrana da un documento è necessario impostare solo il nome della forma della filigrana durante l’inserimento e quindi rimuovere la forma della filigrana con un nome assegnato.
Il seguente esempio di codice mostra come impostare il nome della forma della filigrana e rimuoverlo dal documento:
// 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(); | |
} | |
} | |
} | |
} | |
} |
Aggiungi una filigrana in una cella di tabella
A volte è necessario inserire una filigrana/immagine nella cella di una tabella e visualizzarla all’esterno della tabella, è possibile utilizzare la proprietà IsLayoutInCell. Questa proprietà ottiene o imposta un flag che indica se la forma viene visualizzata all’interno o all’esterno di una tabella. Tieni presente che questa proprietà funziona solo quando ottimizzi il documento per Microsoft Word 2010 utilizzando il metodo OptimizeFor.
L’esempio di codice seguente mostra come utilizzare questa proprietà:
// 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); |