c# and create and handle a word document, by m.c. enrique ruiz díaz

32
C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. Página 1 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/ C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz. All Rigths Reserved. Con título y cédula profesional 5632071 en la Maestría en Ciencias de la Computación. Egresado del Instituto Tecnológico de Orizaba, Ver. (México).

Upload: enriqueruizdiaz

Post on 29-Oct-2014

307 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 1 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

C# and Create and Handle

a Word Document, by M.C. Enrique Ruiz Díaz.

All Rigths Reserved.

Con título y cédula profesional 5632071 en la Maestría en Ciencias de la Computación.

Egresado del Instituto Tecnológico de Orizaba, Ver. (México).

Page 2: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 2 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

Acerca de mi.

Titulado en la Maestría en Ciencias en Ciencias de la Computación, Cédula profesional 5632071. Egresado del Instituto

Tecnológico de Orizaba, Ver., México. Antes, me Titulé en la Licenciatura en Informática, Cédula profesional 4046033. Egresado

del Instituto Tecnológico de Tuxtepec, Oax., México, distinguiéndome además, por ser el mejor promedio de mi generación con

98%.

Bien, regresando al tema de mi Título de Maestría en Ciencias de la Computación, para subrayar que ésta, requirió el desarrollo de

una TESIS. Otro aspecto muy importante, fue que durante el desarrollo de mi Maestría escribí un ARTICULO, mismo que fue

aceptado para publicación y con mi ponencia en el evento 'Primer Encuentro de Estudiantes en Ciencia de la Computación - E2C2'

ISBN-10:970-36-0404-8 e ISBN-13:978-970-36-0404-3 celebrado en el Instituto Politécnico Nacional, México, D.F. 2007.

Page 3: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 3 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

Mi Diploma por mi Ponencia en el Instituto Politécnico Nacional, México, D.F. 2007.

Page 4: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 4 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

«Inside the great field of the Programming, I own to offer my knowledge of the Structured Programming Paradigm. This,

principally by means of the Language C. Also, I own to offer my knowledge of the Object-Oriented Paradigm. This, by means of

The Languages Java and Visual C#. Majorly».

M.C. Enrique Ruiz Díaz.

Page 5: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 5 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

ÍNDICE

Acerca de mi. ............................................................................................................................................................. 2

ÍNDICE ........................................................................................................................................................................ 5

1. Lista de objetivos que logra el código C# presentado para la manipulación de un documento Word. .................. 6

2. Recursos Software utilizados. ................................................................................................................................ 6

3. Secuencia de Imágenes que prueban la creación y manipulación de un documento Word, desde código C#. ..... 7

4. Primer paso: desde el IDE Visual C# agregar una referencia al proyecto, denominada Microsoft Word xx.x

Object Library .......................................................................................................................................................... 17

5. Elementos visuales que se insertan en la aplicación. ........................................................................................... 19

6. Código C# para construir y manipular un documento Word. ............................................................................... 20

Page 6: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 6 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

1. Lista de objetivos que logra el código C# presentado para la manipulación de un documento Word.

1) Asignar márgenes a la hoja, para nuestro documento, independientes de márgenes en Word indicados.

2) Poner encabezado.

3) Poner números de página automáticos.

4) Mandar texto al documento, asignándole formato.

5) Crear tablas de datos con cantidad de filas y columnas deseadas.

6) Asignar formato a datos en las tablas de datos creadas.

7) Imprimir una imagen en el documento.

8) Imponer un ‘Break’, un brinco incondicional a la siguiente página.

9) Enviar texto al documento e imponer alinación deseada: ‘left’, ‘center’, ‘right’ y ‘justify’.

10) Enviar el documento a la impresora. (Nota: en este caso mi impresora fue ‘pdfCreator’).

11) Guardar el documento, dado un nombre indicado y un folder señalado en el código.

12) Cerrar el documento.

2. Recursos Software utilizados. Se usó Visual C# 2008, y Microsoft Word 2007, con los resultados esperados y ya indicados. Nota: presumiblemente, no habría inconveniente que con

Visual C# 2010, y Microsoft Word 2010 se logren los mismos resultados.

Page 7: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 7 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

3. Secuencia de Imágenes que prueban la creación y manipulación de un documento Word, desde código C#.

Figura 1: Asignado formato al texto, y el encabezado de las páginas.

Page 8: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 8 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

Figura 2: La primera tabla que se genera, y formatos asignados a sus datos.

Page 9: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 9 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

Figura 3: Asignar números de página automáticos.

Page 10: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 10 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

Figura 4: Asignando un ‘Break’, es decir, brinco incondicional a la siguiente página.

Page 11: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 11 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

Figura 5: Se generó una seguna tabla, con formato para algunos datos.

Page 12: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 12 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

Figura 6: Se generó un segundo ‘Break’, otro brinco incondicional a la página siguiente.

Page 13: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 13 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

Figura 7: Se inserta una imagen en el documento, dentro de una tabla (esta, no visible).

Page 14: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 14 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

Figura 8: Se envía 4 párrafos de texto al documento, con formato ‘right’, ‘left’, ‘center’ y ‘justify’, respectivamente.

Page 15: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 15 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

Figura 9: Orden de enviar el documento a la impresora. (En este caso, la impresora fue ‘PdfCreator’).

Page 16: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 16 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

Figura 10: Guardado automático del documento en el folder indicado desde el código C#.

Page 17: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 17 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

4. Primer paso: desde el IDE Visual C# agregar una referencia al proyecto, denominada Microsoft Word xx.x

Object Library

Para crear un documento Word desde un programa de C# el primer paso consiste en utilizar el botón derecho sobre el nombre del proyecto, y

seleccionar agregar referencia

Sobre nombre del Proyecto agregamos Referencia.

Page 18: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 18 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

Luego, elegimos la pestaña COM, y de esta, seleccionamos la biblioteca Microsoft Word xx.xx Object Library.

De la pestaña COM, se selecciona Microsoft Word xx.x Object Library.

Page 19: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 19 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

5. Elementos visuales que se insertan en la aplicación.

Elementos de arrastrar y pegar en la aplicación.

a) Nombre del primer botón insertado (y único): Docto_Word.

b) Nombre del segundo y último elemento utilizado: mensaje_de_word.

Page 20: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 20 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

6. Código C# para construir y manipular un documento Word.

// Inicia el código.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using Microsoft.Office.Interop.Word;

namespace WindowsFormsApplication1

{

public partial class Form1 : Form

{

private Microsoft.Office.Interop.Word.Application ApWord;

private Microsoft.Office.Interop.Word.Document doc;

private object opc = Type.Missing; // parámetro opcional

public Form1()

{

InitializeComponent();

}

private void button1_Click(object sender, EventArgs e)

{

Page 21: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 21 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

ApWord = new Microsoft.Office.Interop.Word.Application();

doc = ApWord.Documents.Add(ref opc, ref opc, ref opc, ref opc);

doc.Range(ref opc, ref opc).Delete(ref opc, ref opc);

//Visualizar un documento

ApWord.Visible = true;

// MessageBox.Show("Observar que el nuevo doc. Word no tiene contenido ...", "", MessageBoxButtons.OK,

MessageBoxIcon.Information);

// ******************************************************************************

// IMPORTANTE: La siguiente asignacion de tipo de letra y su tamaño, afecta a todo el documento Word.

// con el mismo 'doc.Content.Font...' no se puede re-asignar nuevos valores,

// porque re-afectaría incluso la configuración antes hecha.

// Afecta todo el texto que siguira, hasta modificar otra vez estas indicaciones.

doc.Content.Font.Name = "Calibri";

doc.Content.Font.Size = 12;

doc.Content.InsertAfter("1. Lines: 1, 2 y 3 en 'Calibri', tamaño = 12. \n");

// Insertar texto al final del texto del documento Word.

doc.Range(ref opc, ref opc).InsertAfter("2. Now, the second text added. \n");

doc.Range(ref opc, ref opc).InsertAfter("3. Now, the third text placed. \n\n");

// ******************************************************************************************************

// **************************************************************************

// ASIGNAR TIPO DE LETRA, Y TAMAÑO AL TEXTO FUNCIONA PERFECTAMENTE....

object EndOfDoc1 = "\\endofdoc";

Microsoft.Office.Interop.Word.Paragraph oPara1;

object Rng1 = doc.Bookmarks.get_Item(ref EndOfDoc1).Range;

Rng1 = doc.Bookmarks.get_Item(ref EndOfDoc1).Range;

oPara1 = doc.Content.Paragraphs.Add(ref Rng1);

Page 22: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 22 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

oPara1.Range.Font.Name = "Lucida Calligraphy";

oPara1.Range.Font.Size = 18;

oPara1.Range.Text = "Hecho por M.C. Enrique Ruiz Diaz ...(Lucida Calligraphy a 18)";

oPara1.Range.InsertParagraphAfter(); // Se imprime ya en nuestro documento Word,

// porque funciona como variable, su contenido es reemplazado a continuación.

doc.Range(ref opc, ref opc).InsertAfter("\n");

oPara1.Range.Font.Name = "Courier New";

oPara1.Range.Font.Size = 18;

oPara1.Range.Text = "Maestro en Ciencias de la Computaciòn ...(Courier New a 18)";

oPara1.Range.InsertParagraphAfter();

doc.Range(ref opc, ref opc).InsertAfter("\n");

// OBSERVACION: Una asignación de tipo de letra y tamaño afecta, persiguiendo,

// todo lo demás que siga a continuación. Excepto que se indique nuevas asignaciones.

// **************************************************************************

// ***************************************************************************************************

// AÑADIR UNA TABLA DE DATOS ...

//Insert a 5 x 2 table, fill it with data, and change the column widths.

// parte de datos que debo antes tener, segun mis particulares pruebas

object oMissing = System.Reflection.Missing.Value; //System.Reflection.Missing.Value;

object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */

Microsoft.Office.Interop.Word.Table oTable;

Microsoft.Office.Interop.Word.Range wrdRng = doc.Bookmarks.get_Item(ref oEndOfDoc).Range;

wrdRng = doc.Bookmarks.get_Item(ref oEndOfDoc).Range;

oTable = doc.Tables.Add(wrdRng, 5, 2, ref oMissing, ref oMissing);

oTable.Range.ParagraphFormat.SpaceAfter = 6;

// asigno tamaño de letra que en general afectara a la siguiente tabla.

// excepto cuando se indique otras asignaciones...

Page 23: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 23 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

oTable.Range.Font.Size = 12;

int r, c;

string strText;

for (r = 1; r <= 5; r++)

for (c = 1; c <= 2; c++)

{

strText = "r=" + r + "c=" + c;

oTable.Cell(r, c).Range.Text = strText;

}

oTable.Columns[1].Width = ApWord.InchesToPoints(3); //Contrala ancho de la columna - confirmado

oTable.Columns[2].Width = ApWord.InchesToPoints(2); ////Contrala ancho de la columna - confirmado

// Sin bordes: oTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleNone;

// Sin bordes: oTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleNone;

// Poner bordes a la tabla

oTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;

oTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;

// Sobre la fila num. 1 ... a Negritas y cursiva sobre los datos ....

oTable.Rows[1].Range.Font.Bold = 1;

oTable.Rows[1].Range.Font.Italic = 1;

oTable.Rows[2].Range.Font.Name = "Bradley Hand ITC";

oTable.Rows[2].Range.Font.Size = 16;

double nPrecio = 258123658.39;

double nPrecio2 = -10201.78;

double nPrecio3 = -15987.89;

double nPrecio4 = 31325.49;

oTable.Cell(4, 1).Range.Text = provide_format(nPrecio);

Page 24: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 24 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

oTable.Cell(4, 1).Range.ParagraphFormat.Alignment =

Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

oTable.Cell(3, 2).Range.Text = provide_format(nPrecio2);

oTable.Cell(3, 2).Range.ParagraphFormat.Alignment =

Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;

oTable.Cell(4, 2).Range.Text = provide_format(nPrecio3); // la 'c' indica formato de Moneda

oTable.Cell(4,2).Range.ParagraphFormat.Alignment =

Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;

oTable.Cell(5, 2).Range.Text = provide_format(nPrecio4);

oTable.Cell(5, 2).Range.Font.Name = "Calibri";

oTable.Cell(5, 2).Range.Font.Bold = 1;

oTable.Cell(5, 2).Range.ParagraphFormat.Alignment =

Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

// fin de añadir tabla de datos

// NOTA: de acabarse la hoja por el tamaño de la tabla. Word automaticamente

// añada una nueva hoja - COMPROBADO!

// ***************************************************************************************************

// ........................................................................

// Añadir otra cosa después de la Tabla.

//Add some text after the table.

// ***************************************************************************

// FUNCIONÓ INSERTAR UN BREAK, NUEVA PÁGINA EN NUESTRO DOCUMENTO DE WORD

// C# word automation : Inserting page break

object o_EndOfDoc = "\\endofdoc";

object paramNextPage = WdBreakType.wdSectionBreakNextPage;

//wrdDocument.Bookmarks.get_Item(ref o_EndOfDoc).Range.InsertBreak(ref paramNextPage);

Page 25: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 25 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

doc.Bookmarks.get_Item(ref o_EndOfDoc).Range.InsertBreak(ref paramNextPage);

oPara1.Range.Font.Name = "Britannic Bold";

oPara1.Range.Font.Size = 14;

oPara1.Range.Text = "Yo 'texto' debo salir en una nueva página, dado un 'BREAK' ... 'Britannic Bold' a 14

\n\n";

oPara1.Range.InsertParagraphAfter();

// ***************************************************************************

oPara1.Range.Font.Size = 14;

oPara1.Range.Font.Name = "Georgia";

oPara1.Range.Text = "A continuaciòn una tabla de datos grande. Letra: 'Georgia' a 14 \n\n";

oPara1.Range.InsertParagraphAfter();

// ........................................................................

// AÑADIDR UNA TABLA DE DATOS ...

//Insert a 5 x 2 table, fill it with data, and change the column widths.

// parte de datos que debo antes tener, segun mis particulares pruebas

object oMissing2 = System.Reflection.Missing.Value;

object oEndOfDoc2 = "\\endofdoc";

Microsoft.Office.Interop.Word.Table oTable2;

Microsoft.Office.Interop.Word.Range wrdRng2 = doc.Bookmarks.get_Item(ref oEndOfDoc2).Range;

wrdRng2 = doc.Bookmarks.get_Item(ref oEndOfDoc2).Range;

oTable2 = doc.Tables.Add(wrdRng2, 20, 2, ref oMissing, ref oMissing);

oTable2.Range.ParagraphFormat.SpaceAfter = 6;

//int r, c; !YA EXPRESADAS ARRIBA

//string strText; !YA EXPRESADAS ARRIBA

for (r = 1; r <= 20; r++)

for (c = 1; c <= 2; c++)

{

strText = "row = " + r + "column = " + c;

Page 26: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 26 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

oTable2.Cell(r, c).Range.Text = strText;

}

oTable2.Columns[1].Width = ApWord.InchesToPoints(4);

oTable2.Columns[2].Width = ApWord.InchesToPoints(2);

// Sobre la fila num. 1 ... a Negritas y cursiva sobre los datos ....

oTable2.Rows[1].Range.Font.Bold = 1;

oTable2.Rows[1].Range.Font.Italic = 1;

oTable2.Rows[1].Range.Font.Name = "Bradley Hand ITC";

oTable2.Rows[1].Range.Font.Size = 18;

// fin de añadir tabla de datos

// NOTA: de acabarse la hoja por el tamaño de la tabla. Word automaticamente

// añada una nueva hoja - COMPROBADO!

// ........................................................................

//************************************************************************

// FIJANDO MARGENES TODO EL DOCUMENTO WORD.

// COMPROBADO - Si el usuario normal de Word altera márgenes, no importa...

// porque yo impongo mis márgenes para mi documento aquí creado ...

object nothing = System.Reflection.Missing.Value;

doc.PageSetup.PaperSize = Microsoft.Office.Interop.Word.WdPaperSize.wdPaperLetter;

doc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientPortrait;

doc.PageSetup.TopMargin = 60.0f; // Distancia desde el encabezado hasta el primer texto para todas las hojas -

confirmado 57.0f;

doc.PageSetup.BottomMargin = 60.0f; // Distancia del ultimo texto en cada hoja, hasta el pie de página -

confirmado ...

doc.PageSetup.LeftMargin = 80.0f; // Afirmativo: este es para margen izquiedo para todas las hojas generadas...

doc.PageSetup.RightMargin = 60.0f; // ... Posible- contrada distancia del margen derecho de cada hoja ...

doc.PageSetup.HeaderDistance = 30.0f; // desconozco que controla, pero valor correcto debe ser 30.0f ...

//************************************************************************

Page 27: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 27 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

// ****************************************************************************************

//How to insert <Current Page> of <Total Pages> into the footer for a MS Word Document in VSTO

//Open up the footer in the word document

doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter;

// Set current Paragraph Alignment to Center

doc.ActiveWindow.ActivePane.Selection.Paragraphs.Alignment =

Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;

// Type in 'Page '

doc.ActiveWindow.Selection.TypeText("Page ");

// Add in current page field

Object CurrentPage = Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage;

doc.ActiveWindow.Selection.Fields.Add(doc.ActiveWindow.Selection.Range, ref CurrentPage, ref opc, ref opc);

// Type in ' of '

doc.ActiveWindow.Selection.TypeText(" of ");

// Add in total page field

Object TotalPages = Microsoft.Office.Interop.Word.WdFieldType.wdFieldNumPages;

doc.ActiveWindow.Selection.Fields.Add(doc.ActiveWindow.Selection.Range, ref TotalPages, ref opc, ref opc);

// Add header in the doc

doc.Content.Application.ActiveWindow.ActivePane.View.SeekView =

Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageHeader;// =

Convert.ToInt32(Word.WdSeekView.wdSeekCurrentPageHeader);

doc.Content.Application.Selection.TypeText("M.C. Enrique Ruiz Díaz.");

doc.Content.Application.Selection.Fields.Add(doc.Content.Application.Selection.Range, ref opc, ref opc, ref

opc);

//

****************************************************************************************************************

Page 28: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 28 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

// ****************************************************************************************

// AÑADIR UNA IMAGEN AL DOCUMENTO ...

// Primero creo una tabla de una sola fila y una sola columna para allí poner la imagen.

// Se trata ya, de la tercera tabla de mi docto.

//******************************************************************************************

// CONOCIMIENTO: NUNCA DEBES GENERAR DOS TABLAS EN FORMA CONSECUTIVA. DEBES SEPARARLO CON

// TEXTO. COMO SIGUE A CONTINUACIÒN. SE GENERA ERROR DE NO HACERSE ASI.

// TABLA SIGUIENTE 1X1, SOLO PARA LA IMAGEN A AGREGARSE.

oPara1.Range.Font.Size = 14;

oPara1.Range.Font.Name = "Calibri";

oPara1.Range.Text = "\n \n \n Sigue una tercera tabla con una sola fila y una sola columna. Para IMAGEN ...

Letra: 'Calibri' a 14 \n\n";

oPara1.Range.InsertParagraphAfter();

// Creamos una nueva tabla de 1 x 1 solo para insertar una imagen ....

object oMissing3 = System.Reflection.Missing.Value;

object oEndOfDoc3 = "\\endofdoc";

Microsoft.Office.Interop.Word.Table oTable3;

Microsoft.Office.Interop.Word.Range wrdRng3 = doc.Bookmarks.get_Item(ref oEndOfDoc3).Range;

wrdRng3 = doc.Bookmarks.get_Item(ref oEndOfDoc3).Range;

oTable3 = doc.Tables.Add(wrdRng3, 1, 1, ref oMissing3, ref oMissing3);

oTable3.Range.ParagraphFormat.SpaceAfter = 6;

//oTable3.Cell(1, 1).Range.Text = "una fila, una columna";

oTable3.Columns[1].Width = ApWord.InchesToPoints(3);

// ***********************************************************************************

object missing = System.Reflection.Missing.Value;

Page 29: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 29 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

object start1 = 0;

Range rng = doc.Range(ref start1, ref missing);

Range rngPic = doc.Tables[3].Range;

rngPic.InlineShapes.AddPicture(@"C:\Imagen\The Vision.jpg", ref missing, ref missing, ref missing);

// *********************************************************************************************

// ***************************************************************************

// RECURRO A UN SEGUDO 'BREAK'. SIGNIFICA UN NUEVO BRINCO DE PAGINA.

// C# word automation : Inserting page break

object o_EndOfDoc5 = "\\endofdoc";

object paramNextPage5 = WdBreakType.wdSectionBreakNextPage;

//wrdDocument.Bookmarks.get_Item(ref o_EndOfDoc5).Range.InsertBreak(ref paramNextPage5);

doc.Bookmarks.get_Item(ref o_EndOfDoc).Range.InsertBreak(ref paramNextPage);

oPara1.Range.Font.Name = "Footlight MT Light";

oPara1.Range.Font.Size = 14;

oPara1.Range.Text = "Este es un nuevo BREAK (el segundo). Debo salir en una nueva página, dado un 'BREAK' ...

'Footlight MT Light' a 14 \n\n";

oPara1.Range.InsertParagraphAfter();

// ***************************************************************************

// ALINEACION AL CENTRO, A LA IZQUIERA JUSTIFICADO Y A LA DERECHA

string var5 = "[right] «You attitude determines your altitude».";

string var6 = "[left] «As a diamond, the English Language is forever».";

string var7 = "[center] «Siempre hay un lugar en la cima».";

Page 30: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 30 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

string var8a = "[justify] «Avoid sugar, salt, white flour products or deserts. ";

string var8b = "Avoid soft drinks and candy bars or pastries. ";

string var8c = "Feed yourself as you would feed a world class athlete before a competition, ";

string var8d = "because in many respects, ";

string var8e = "that is what you are before starting work each day».";

Microsoft.Office.Interop.Word.Table oTable5;

Microsoft.Office.Interop.Word.Range wrdRng5 = doc.Bookmarks.get_Item(ref oEndOfDoc3).Range;

wrdRng5 = doc.Bookmarks.get_Item(ref oEndOfDoc3).Range;

oTable5 = doc.Tables.Add(wrdRng5, 4, 1, ref oMissing3, ref oMissing3);

oTable5.Range.ParagraphFormat.SpaceAfter = 6;

oTable5.Cell(1, 1).Range.Text = var5;

oTable5.Cell(1, 1).Range.ParagraphFormat.Alignment =

Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

oTable5.Cell(2, 1).Range.Text = var6;

oTable5.Cell(2, 1).Range.ParagraphFormat.Alignment =

Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;

oTable5.Cell(3, 1).Range.Text = var7;

oTable5.Cell(3, 1).Range.ParagraphFormat.Alignment =

Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;

oTable5.Cell(4, 1).Range.Text = var8a + var8b + var8c + var8d + var8e;

oTable5.Cell(4, 1).Range.ParagraphFormat.Alignment =

Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;

// ******************************************************************************

//Enviar a la impresora

ApWord.ActiveDocument.PrintOut(ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc,

ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc);

String nuevoNombreDoc = @"C:\Imagen\Poliza_01.docx";

Page 31: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 31 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

object param = nuevoNombreDoc;

MessageBox.Show("Requiere IMPRIMIR, primero. Luego pulse aquí ...", "", MessageBoxButtons.OK,

MessageBoxIcon.Information);

try

{

//Para guardar los cambios y además, asignar un nombre a nuestro docto. Word.

doc.SaveAs(ref param, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref

opc, ref opc, ref opc, ref opc, ref opc, ref opc);

//Cuando la ventana Word está visible y se cierra.

ApWord.Visible = false;

ApWord.Quit(ref opc, ref opc, ref opc);

ApWord = null;

doc = null;

mensaje_de_word.Text = "Word se acaba de cerrar, para mi propio docto. No para otro ajeno ...";

}

catch

{

MessageBox.Show("Word no requiere cerrarse, ya está cerrado...", "", MessageBoxButtons.OK,

MessageBoxIcon.Error);

}

}

private string provide_format(double num)

{

string var_String = string.Format("Order Total: {0:C}", num); //string.Format("{0:#,###.00}", num);

string resultado = "";

Page 32: C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz

C# and Create and Handle a Word Document, by M.C. Enrique Ruiz Díaz.

Página 32 de 32 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

for (int i=0; i<var_String.Length; i++) //(int i = var_String.Length-1; i>=0; i--)

{

if (var_String[i] == '-' || var_String[i] == '0' || var_String[i] == '1' || var_String[i] ==

'2' || var_String[i] == '3' || var_String[i] == '4' || var_String[i] == '5' || var_String[i] == '6' || var_String[i] == '7'

|| var_String[i] == '8' || var_String[i] == '9')

{

resultado = resultado + var_String[i];

}

else

{

if (var_String[i] == '.')

{

resultado = resultado + ',';

}

else

{

if (var_String[i] == ',')

{

resultado = resultado + '.';

}

} // fin del segundo else

} // fin del primer else

} // fin del for

return resultado;

}

} // de la clase

} // del NameSpace

// Fin del código.