Lavorare con le forme

In questo argomento viene illustrato come lavorare a livello di codice con le forme utilizzando Aspose.Words.

Le forme in Aspose.Words rappresentano un oggetto nel livello di disegno, ad esempio una forma, una casella di testo, una forma libera, un oggetto OLE, un controllo ActiveX o un’immagine. Un documento di Word può contenere una o più forme diverse. Le forme in Aspose.Words sono rappresentate dalla classe Shape.

Inserimento di forme utilizzando Document Builder

È possibile inserire una forma in linea con tipo e dimensione specificati e una forma mobile con posizione, dimensione e tipo di disposizione del testo specificati in un documento utilizzando il metodo InsertShape. Il metodo InsertShape consente di inserire la forma DML nel modello del documento. Il documento deve essere salvato nel formato che supporta le forme DML, altrimenti tali nodi verranno convertiti in forma VML durante il salvataggio del documento.

L’esempio di codice seguente mostra come inserire questi tipi di forme nel documento:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
//Free-floating shape insertion.
Shape shape = builder.InsertShape(ShapeType.TextBox, RelativeHorizontalPosition.Page, 100, RelativeVerticalPosition.Page, 100, 50, 50, WrapType.None);
shape.Rotation = 30.0;
builder.Writeln();
//Inline shape insertion.
shape = builder.InsertShape(ShapeType.TextBox, 50, 50);
shape.Rotation = 30.0;
OoxmlSaveOptions so = new OoxmlSaveOptions(SaveFormat.Docx);
// "Strict" or "Transitional" compliance allows to save shape as DML.
so.Compliance = OoxmlCompliance.Iso29500_2008_Transitional;
dataDir = dataDir + "Shape_InsertShapeUsingDocumentBuilder_out.docx";
// Save the document to disk.
doc.Save(dataDir, so);

Imposta proporzioni bloccate

Usando Aspose.Words, puoi specificare se le proporzioni della forma sono bloccate tramite la proprietà AspectRatioLocked.

L’esempio di codice seguente mostra come utilizzare la proprietà AspectRatioLocked:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
var shape = builder.InsertImage(dataDir + "Test.png");
shape.AspectRatioLocked = false;
dataDir = dataDir + "Shape_AspectRatioLocked_out.doc";
// Save the document to disk.
doc.Save(dataDir);

Imposta il layout della forma nella cella

Puoi anche specificare se la forma viene visualizzata all’interno o all’esterno di una tabella utilizzando la proprietà IsLayoutInCell.

L’esempio di codice seguente mostra come utilizzare la proprietà IsLayoutInCell:

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

Crea rettangolo di angolo di cattura

È possibile creare un rettangolo con angolo di ritaglio utilizzando Aspose.Words. I tipi di forma sono SingleCornerSnipped, TopCornersSnipped, DiagonalCornersSnipped, TopCornersOneRoundedOneSnipped, SingleCornerRounded, TopCornersRounded e DiagonalCornersRounded.

La forma DML viene creata utilizzando il metodo InsertShape con questi tipi di forma. Questi tipi non possono essere utilizzati per creare forme VML. Il tentativo di creare una forma utilizzando il costruttore pubblico della classe “Shape” genera l’eccezione “NotSupportedException”.

L’esempio di codice seguente mostra come inserire questo tipo di forme nel documento:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Shape shape = builder.InsertShape(ShapeType.TopCornersSnipped, 50, 50);
OoxmlSaveOptions so = new OoxmlSaveOptions(SaveFormat.Docx);
so.Compliance = OoxmlCompliance.Iso29500_2008_Transitional;
dataDir = dataDir + "AddCornersSnipped_out.docx";
//Save the document to disk.
doc.Save(dataDir, so);

Ottieni punti relativi ai limiti della forma effettivi

Utilizzando Aspose.Words API, puoi ottenere la posizione e la dimensione del blocco contenente la forma in punti, rispetto all’ancoraggio della forma più in alto. A tale scopo, utilizzare la proprietà BoundsInPoints.

Il seguente esempio di codice mostra come utilizzare la proprietà BoundsInPoints:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
var shape = builder.InsertImage(dataDir + "Test.png");
shape.AspectRatioLocked = false;
Console.Write("\nGets the actual bounds of the shape in points.");
Console.WriteLine(shape.GetShapeRenderer().BoundsInPoints);

Specificare l’ancoraggio verticale

È possibile specificare l’allineamento verticale del testo all’interno di una forma utilizzando la proprietà VerticalAnchor.

L’esempio di codice seguente mostra come utilizzare la proprietà VerticalAnchor:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + @"VerticalAnchor.docx");
NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);
Shape textBoxShape = shapes[0] as Shape;
if (textBoxShape != null)
{
textBoxShape.TextBox.VerticalAnchor = TextBoxAnchor.Bottom;
}
doc.Save(dataDir + "VerticalAnchor_out.docx");

Rileva forma SmartArt

Aspose.Words consente anche di rilevare se la Shape ha un oggetto SmartArt. A tale scopo, utilizzare la proprietà HasSmartArt.

L’esempio di codice seguente mostra come utilizzare la proprietà HasSmartArt:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "input.docx");
int count = 0;
foreach (Shape shape in doc.GetChildNodes(NodeType.Shape, true))
{
if (shape.HasSmartArt)
count++;
}
Console.WriteLine("The document has {0} shapes with SmartArt.", count);

Inserisci la riga orizzontale nel documento

È possibile inserire la forma della riga orizzontale in un documento utilizzando il metodo InsertHorizontalRule.

L’esempio di codice seguente mostra come eseguire questa operazione:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Initialize document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Insert a horizontal rule shape into the document.");
builder.InsertHorizontalRule();
dataDir = dataDir + "DocumentBuilder.InsertHorizontalRule_out.doc";
doc.Save(dataDir);

Aspose.Words API fornisce la proprietà HorizontalRuleFormat per accedere alle proprietà della forma della regola orizzontale. La classe HorizontalRuleFormat espone proprietà di base come Altezza, Colore, NoShade ecc. per la formattazione di una linea orizzontale.

Il seguente esempio di codice mostra come impostare HorizontalRuleFormat:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
DocumentBuilder builder = new DocumentBuilder();
Shape shape = builder.InsertHorizontalRule();
HorizontalRuleFormat horizontalRuleFormat = shape.HorizontalRuleFormat;
horizontalRuleFormat.Alignment = HorizontalRuleAlignment.Center;
horizontalRuleFormat.WidthPercent = 70;
horizontalRuleFormat.Height = 3;
horizontalRuleFormat.Color = Color.Blue;
horizontalRuleFormat.NoShade = true;
builder.Document.Save("HorizontalRuleFormat.docx");

Importa forme con XML matematico come forme in DOM

È possibile utilizzare la proprietà ConvertShapeToOfficeMath per convertire le forme con EquationXML in oggetti Office Math. Il valore predefinito di questa proprietà corrisponde al comportamento Microsoft Word, ovvero le forme con equazione XML non vengono convertite in oggetti matematici di Office.

L’esempio di codice seguente mostra come convertire le forme in oggetti Office Math:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
LoadOptions lo = new LoadOptions();
lo.ConvertShapeToOfficeMath = true;
// Specify load option to use previous default behaviour i.e. convert math shapes to office math ojects on loading stage.
Document doc = new Document(dataDir + @"OfficeMath.docx", lo);
//Save the document into DOCX
doc.Save(dataDir + "ConvertShapeToOfficeMath_out.docx", SaveFormat.Docx);