Añadir más elementos al documento - Parte VI

En este sexto y último tutorial de esta serie, veremos cómo añadir HTML/RTF y Formas, a tus documentos.

Más información Xceed Words para .NET

Esta semana veremos cómo añadir HTML/RTF y formas a los documentos.

HTML/RTF

Existen dos opciones para insertar datos HTML o RTF en un documento DocX: insertando sólo una sección de texto o insertando otro documento en el actual.

La inserción de un fragmento de texto se realiza llamando a la función del documento InsertarContenido método.

En InsertarContenido espera los siguientes parámetros:

  • El texto a insertar (con las etiquetas HTML o RTF)
  • Tipo de contenido para especificar si el texto a insertar contiene HTML o RTF
  • Opcional: el párrafo tras el que insertar el contenido, si se deja nulo, el texto se insertará en la posición actual del documento.
// Append HTML text at the end of the document
document.InsertContent( htmlData1, ContentType.Html);

// Append HTML text after a specific paragraph
document.InsertContent( htmlData2, ContentType.Html, p1 );

// Append RTF text at the end of the document
document.InsertContent( rtfData1, ContentType.Rtf);

// Append RTF text after a specific paragraph
document.InsertContent( rtfData2, ContentType.Rtf, p2 );

La inserción de un documento HTML o RTF en un documento existente se realiza llamando a la función InsertarDocumento en el documento de destino y utilizando su sobrecarga compatible con documentos HTML/RTF.

En InsertarDocumento espera los siguientes parámetros:

  • El nombre de archivo del documento a insertar (con las etiquetas HTML o RTF)
  • Tipo de contenido para especificar si el documento a insertar contiene HTML o RTF
  • Opcional: el párrafo después del cual insertar el documento, si se deja nulo, el documento se añadirá en la posición actual en el documento de destino.
// Append an HTML document at the end of the current document
document.InsertDocument( htmlFilename1, ContentType.Html);

// Append an HTML document after a specific paragraph in the current document
document.InsertDocument( htmlFilename2, ContentType.Html, p1 );

// Append an RTF document at the end of the current document
document.InsertDocument( rtfFilename1, ContentType.Rtf);

// Append an RTF document text after a specific paragraph in the current document
document.InsertDocument( rtfFilename2, ContentType.Rtf, p2 );

Formas

 En el momento de escribir este artículo, una forma sólo puede ser un rectángulo o un cuadro de texto.

Rectángulo

Añadir una forma rectangular se hace en 2 pasos:

  1. Añade el rectángulo a la colección Shape del documento llamando al método AddShape método.
  2. Añade el rectángulo a un párrafo llamando a la función InsertShape método.
// Add a shape and specify at least a width and height
var shape = document.AddShape( 100, 50 );

// Insert the Shape in a paragraph
var p = document.InsertParagraph( “Here is a simple default rectangle, positioned on the 16th character of this paragraph:” );
p.InsertShape( shape, 16 );

En AddShape requiere una anchura y una altura, pero también acepta parámetros opcionales adicionales: fillColor, outlineColor, outlineWidth y outlineDash.

// Add a shape and specify all its properties
var shape2 = document.AddShape( 100, 50, Color.Orange, Color.Black, 4f, DashStyle.Dot );

// Insert the Shape at the end of a paragraph
var p2 = document.InsertParagraph( “Here is a custom rectangle appended to this paragraph:” );
p2.InsertShape( shape2 );

Utilizando las distintas propiedades disponibles en un objeto de forma, puede personalizar cómo se muestra una forma rectangular.

A continuación se muestra un ejemplo de cómo añadir un rectángulo con texto:

// Create a document.
using( var document = DocX.Create( "AddShapeWithTextWrapping.docx" ) )
{
	// Add a title
	document.InsertParagraph( "Add a shape with Text Wrapping" ).FontSize( 15d ).SpacingAfter( 50d ).Alignment = Alignment.center;

	// Add a shape and set its wrapping as Square.
	var shape = document.AddShape( 45, 45, Color.LightGray );
	shape.WrappingStyle = PictureWrappingStyle.WrapSquare;
	shape.WrapText = PictureWrapText.bothSides;

	// Set horizontal alignment with Alignment centered on the page.
	shape.HorizontalAlignment = WrappingHorizontalAlignment.CenteredRelativeToPage;

	// Set vertical alignment with an offset from top of paragraph.
	shape.VerticalOffsetAlignmentFrom = WrappingVerticalOffsetAlignmentFrom.Paragraph;
	shape.VerticalOffset = 20d;

	// Set a buffer on left and right of shape where no text will be drawn.
	shape.DistanceFromTextLeft = 5d;
	shape.DistanceFromTextRight = 5d;

	// Create a paragraph and append the shape to it.
	var p = document.InsertParagraph( "With its easy to use API, Xceed Words for .NET lets your application create new Microsoft Word .docx or PDF documents, or modify existing .docx documents. It gives you complete control over all content in a Word document, and lets you add or remove all commonly used element types, such as paragraphs, bulleted or numbered lists, images, tables, charts, headers and footers, sections, bookmarks, and more. Create PDF documents using the same API for creating Word documents." );
	p.Alignment = Alignment.both;
	p.AppendShape( shape );
	p.SpacingAfter( 50 );

	// Save the document
	document.Save();
}

Cuadro de texto

Añadir una forma TextBox se hace en 2 pasos:

  1. Añade el cuadro de texto a la colección TextBoxes del documento llamando al método AddTextBox método.
  2. Añade el cuadro de texto a un párrafo llamando a la función InsertShape método.
// Add a TextBox and specify at least a width and height
var textBox = document.AddTextBox( 100, 50 );

// Insert the TextBox in a new paragraph
var p = document.InsertParagraph( “Here is a simple TextBox positioned on the 16th character of this paragraph:” );
p.InsertShape( textbox, 16 );

En AddTextBox requiere una anchura y una altura, pero también acepta parámetros opcionales adicionales: text, formatting, fillColor, outlineColor, outlineWidth y outlineDash.

// Add a shape and specify all its properties
var textBox2 = document.AddTextBox( 100, 50, “My TextBox”, new Formatting() { FontColor = Color.Green } );
textBox2.TextVerticalAlignment = VerticalAlignment.Bottom;
textBox2.TextMarginBottom = 5d;
textBox2.TextMarginTop = 5d;
textBox2.TextMarginLeft = 5d;
textBox2.TextMarginRight = 5d;

// Insert the TextBox in a new paragraph
var p = document.InsertParagraph( "Here is a simple TextBox positioned on the 16th character of this paragraph." );
p.InsertShape( textBox, 16 );
p.SpacingAfter( 30 );

// Add a bold paragraph to the TextBox.
document.TextBoxes[ 0 ].InsertParagraph( "My New Paragraph" ).Bold();

Nota: La clase Shape tiene muchas otras propiedades que pueden modificarse por separado después de crear la Shape por primera vez. Consulte la documentación para obtener más información.

Para más información, consulte el documentación.