Automatizando CorelDraw

Funciones que se utilizan cuando queremos manejar archivos creados con CorelDraw dentro de nuestros programas Delphi





Abrir un documento Corel




var


 
CorelDraw: Variant;


 
…


CorelDraw := CreateOleObject('CorelDraw.Automation.8');


CorelDraw.FileNew;


 
// también se puede usar CorelDraw.FileOpen(FileName);


CorelDraw.SetDocVisible(True);


CorelDraw.FileSave('NewName', 0,
False,
0, False);


CorelDraw.FileExit(False); 


CorelDraw := Unassigned;





Parámetros de la función FileSave




FileName: WideString


ThumbNailSize: Integer


SaveSelectedOnly: WordBool


FileVersion: Integer


IncludeCMXData: WordBool













Abrir un documento usando COM




  var


    Disp: IDispatch;


  begin


    Disp := CreateComObject(CLASS_CDrawAutomate) as IDispatch;


    Draw := IDrawAutomate(Disp);










Cerrar  CorelDraw




  Draw.FileExit(False);


  Draw := nil;             // si Draw es una variable del tipo IDrawAutomate 





o





  Draw.FileExit(False);


  Draw := Unassigned;      // si Draw es una variable de tipo variant










Cerrar un documento


 Draw.FileClose(False); 





Cambiar la orientación del texto y otras propiedades.




CorelDraw.SetPageOrientation(0);


CorelDraw.SetPageSize(PageW, PageH);


CorelDraw.NewLayer('NewLayer1');


CorelDraw.SelectLayer('NewLayer1');


CorelDraw.CreateEllipse(CalcY(Y1)), CalcX(X1), CalcY(Y2),
CalcX(X2),
0, 0,
0);


CorelDraw.CreateRectangle(CalcY(Y1)), CalcX(X1), CalcY(Y2),
CalcX(X2), CalcX(Radius));








Primero hay que crear el objeto del dibujo y luego se asignan distintas propiedades, como color, tipo de relleno, grosor, etc Por defecto, estos valores no se pueden establecer a través de la automatización.







CorelDraw.CreateArtisticText( Text, CalcX(X), CalcY(Y));


With
Font
do


 
begin


 
if
(Italic)
and
(Bold)
then
FSK:=
14 else


 
if
(Italic)
then
FSK:=
8 else


 
if
(bold)
then
FSK:=
13 else FSK:=7;


 
end;


CorelDraw.SetCharacterAttributes( 0, 0,
Font.
Name, FSK, Abs(Font.Size)*10,


 
0, 0,
0, 0,
0, 1000, 1000, HAlign);


ColorToCMYK(Font.Color, C,M,Y,K);


CorelDraw.StoreColor(2,
C,M,Y,K,
0,0,0,0); 


CorelDraw.ApplyUniformFillColor; 







CorelDraw.GetSize(XSize, YSize); 


CorelDraw.MoveObject(0,
-YSize); 





Mostrar todos los objetos:




var
ObjID, FirstObjID:longint;


begin


CorelDraw.SelectAllObjects;


CorelDraw.SelectNextObject(true);


FirstObjID := CorelDraw.GetObjectsCDRStaticID;


Repeat


...


// otra opción    CorelDraw.SelectNextObject(true);


ObjID :=
CorelDraw.GetObjectsCDRStaticID;


Until ObjID = FirstObjID; ...



















Lotus Notes con Delphi

Abre la base de datos de Lotus Notes  names.nsf y muestra su libro de direcciones.






unit
Unit1;





interface





uses


Windows,
Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,


Dialogs,
Domino_TLB, Menus, ComCtrls;


const


PASSWD =
'ur70';


type


TForm2 =
class(TForm)


  
TV_INFO: TTreeView;


  
MainMenu1: TMainMenu;


  
File1: TMenuItem;


  
Create1: TMenuItem;


  
Init1: TMenuItem;


  
AddressBook1: TMenuItem;


  
Scan1: TMenuItem;


  
procedure Create1Click(Sender: TObject);


  
procedure Init1Click(Sender: TObject);


  
procedure Scan1Click(Sender: TObject);


private


  
{ Private declarations
}


public


  
{ Public declarations
}


end;





var


Form2:
TForm2;


Session:
TNotesSession;


implementation





{$R
*.dfm}





procedure TForm2.Create1Click(Sender: TObject);


begin


Session
:= TNotesSession.Create(
nil);


end;





procedure TForm2.Init1Click(Sender: TObject);


begin


Session.Initialize(PASSWD);


end;








Abre la base de datos names.nsf y muestra el libro de direcciones





procedure TForm2.Scan1Click(Sender: TObject);


var


NotesDb:
NotesDatabase;


addrBook: NotesDatabase;


People,
People2: NotesView;


Person,
Person2: NotesDocument;


View:
NotesView;


Item:
NotesItem;


AddrBooks: OleVariant;


Views:
OleVariant;


Items:
OleVariant;


x, y, z:
integer;


view_name: string;


tn, tc:
TTreeNode;


begin


NotesDb
:= Session.GetDatabase(
'',
'names.nsf', False);


AddrBooks := Session.AddressBooks;


for
x :=
0 to VarArrayHighBound(AddrBooks,
1) -


  
VarArrayLowBound(AddrBooks,
1)
do


begin


  
addrBook := NotesDatabase(IUnknown(AddrBooks[x]));


  
if
(addrBook.IsPrivateAddressBook)
then


  
begin


    
addrBook.Open;


  
end


  
else


    
addrBook :=
nil;


  
if
(addrBook <>
nil)
then


  
begin


    
Views := addrBook.Views;


    
for
y :=
0 to VarArrayHighBound(Views,
1) -


      
VarArrayLowBound(Views,
1)
do


    
begin


      
View := NotesView(IUnknown(Views[y]));


      
view_
name
:= View.
Name;


      
tn := tv_info.Items.AddNode(
nil, nil, view_name, nil, naAdd);





      
if
copy(view_
name, 1,
1) = '$' then


        
view_
name
:= copy(view_
name, 2,
length(view_
name) - 1);


      
people := addrBook.GetView(view_
name);


      
person := people.GetFirstDocument;


      
if
Person <>
nil
then


      
begin


        
Items := Person.Items;


        
for
z :=
0 to VarArrayHighBound(Items,
1) -


           VarArrayLowBound(Items, 1) do


        
begin


           Item := NotesItem(IUnknown(Items[z]));


           tc := tv_info.Items.AddChild(tn,
Item.
Name);





           people := addrBook.GetView(view_name);


           person := people.GetFirstDocument;





           while (Person <> nil) do


           begin


             try


               try


                 tv_info.Items.AddChild(tc,
Person.GetFirstItem(Item.
Name).Text


                   {Item.Text});


               except


               end;


             finally


               Person :=
People.GetNextDocument(Person);


             end;


           end;


        
end;


      
end;


    
end;





  
end;


end;


end;





end.


FAQ Word / Excel

PREGUNTAS



¿Cómo mover el cursor hasta el final de un documento Word?

¿Cómo cambiar el tipo de letra de una celda?

¿Cómo cambiar el color de la tabla?

¿Cómo imprimir sin mostrar el cuadro de diálogo?

Cómo alinear texto en Word

Utilizar Excel a través de la interfaz COM

Utilizar Excel usando OLE

COMPROBAR SI OLE está instalado

¿Cómo exportar una tabla Word a un StringGrid?



RESPUESTAS



¿Cómo mover el cursor hasta el final de un documento Word?


Function EndOfDoc:boolean;


begin


EndOfDoc:=true;


try


W.ActiveDocument.Range.Select;


W.Selection.Start:=W.Selection.End;


except


EndOfDoc:=false;


end;


End;





¿Cómo cambiar el tipo de letra de una celda?




Function SelectCell(Table:integer;


Row,Column:integer):boolean;


begin


SelectCell:=true;


try


W.ActiveDocument.Tables.Item(Table).Columns.Item


 
(Column).Cells.Item(Row).Select;


except


SelectCell:=false;


end;


End;





Function FontToEFont(font:Tfont;EFont:variant;





ColorIndex:integer):boolean;


begin


FontToEFont:=true;


try


EFont.Name:=font.Name;


if
fsBold
in
font.Style


 
then
EFont.Bold:=True 


 
else
EFont.Bold:=False; 


if
fsItalic
in
font.Style


 
then
EFont.Italic:=True


 
else
EFont.Italic:=False; 


EFont.Size:=font.Size; 


if
fsStrikeOut
in
font.Style


 
then
EFont.Strikethrough:=True 


 
else
EFont.Strikethrough:=False; 


if
fsUnderline
in
font.Style


 
then
EFont.Underline:=wdUnderlineSingle 


 
else
EFont.Underline:=wdUnderlineNone; 


EFont.ColorIndex:=ColorIndex; 


except


FontToEFont:=false;


end;


End;





Cuando se selecciona un objeto, podemos cambiar la fuente, para ello utilizamos la siguiente función para la selección de objetos:




Function SetFontSelection(font:Tfont;


ColorIndex:integer):boolean;


begin


SetFontSelection:=true;


try


SetFontSelection:=FontToEFont(font,W.Selection.font,ColorIndex);


except


SetFontSelection:=false;


end;


End;





¿Cómo cambiar el color de la tabla?


W.ActiveDocument.Tables.Item(tab_).Columns.Item(col_).Cells.Item(row_).Borders.Item(wdBorderTop).ColorIndex:=wdDarkRed;





¿Cómo imprimir sin mostrar el cuadro de diálogo?




Function PrintOutDoc(NumCopies:integer):boolean;


begin


PrintOutDoc:=true;


try


W.ActiveDocument.PrintOut(NumCopies);


except


PrintOutDoc:=false;


end;





Cómo alinear texto




W.Selection.ParagraphFormat.Alignment:=wdAlignParagraphCenter;


W.Selection.ParagraphFormat.Alignment:=wdAlignParagraphRight;


W.Selection.ParagraphFormat.Alignment:=wdAlignParagraphJustify;





Utilizar Excel a través de la interfaz COM





EJEMPLO 1 




var
Excel, WorkBook, Sheet: Variant;


begin


Excel :=
CreateOleObject(
'Excel.Application');


Excel.WorkBooks.Open(FileName,False);


WorkBook
:= Excel.WorkBooks.Item[
1];


Sheet :=
Workbook.Sheets.Item[
3];


Sheet.Cells[1,2]:='ASDFG';


Sheet.Cells[2,2]:=230;





EJEMPLO 2


uses


ComObj,
ActiveX;





var


Row,
Col: integer;


DestRange: OleVariant;


Excel:
Variant;





begin


Excel :=
CreateOleObject(
'Excel.Application');


Excel.Visible := True;


Excel.WorkBooks.Add; 


Excel.ActiveSheet.Range['A2', 'B3'].Value := 'Тест';


Excel.ActiveSheet.Range['A4', 'B5'].Value := 42;


Excel.ActiveSheet.Range['A10', 'A11'].Formula := '=RAND()';


Excel.ActiveSheet.Cells.Item[1, 1].Value := 'prueba';





Row:=1;


Col:=3;


Excel.ActiveSheet.Cells.Item[Row, Col].Value := 'prueba';





DestRange := Excel.Range['D6', 'F10'];


Excel.Range['A1', 'C5'].Copy(DestRange);





Excel.Range['A2', 'A2'].Font.Size := 20;


Excel.Range['A2', 'A2'].Font.FontStyle := 'Bold';


Excel.Range['A2', 'A2'].Font.Color := clFuchsia;


Excel.Range['A2', 'A2'].Font.Name := 'Arial';


Excel.Range['B2', 'C6'].Interior.Color := RGB(223,
123, 123);


end;





EJEMPLO 3







uses


ComObj,
ActiveX;





var


Excel:
Variant;


WBk :
OleVariant;


SaveChanges: OleVariant;


begin


Excel :=
CreateOleObject(
'Excel.Application');


Excel.Visible := True;


WBk :=
Excel.WorkBooks.Open(
'C:\Test.xls');




...





WBk.Close(SaveChanges := True);


Excel.Quit;


end;








Utilizar Excel usando OLE







{


Ejemplo para imprimir un archivo utilizando OLE


}


uses


ComObj;





procedure TForm1.Button1Click(Sender: TObject);


var


ExcelApp: OLEVariant;


begin


//
Create an Excel instance


//
Excel Instanz erzeugen


ExcelApp
:= CreateOleObject(
'Excel.Application');


try


  
ExcelApp.Workbooks.Open(
'C:\test\xyz.xls');


  
// you can also modify
some settings from PageSetup


  
// Man kann auch noch
einige Einstellungen von "Seite Einrichten" anpassen


  
ExcelApp.ActiveSheet.PageSetup.Orientation := xlLandscape;


  
// Print it out


  
// Ausdrucken


  
ExcelApp.Worksheets.PrintOut;


finally


  
// Close Excel


  
// Excel wieder
schliessen


  
if
not
VarIsEmpty(ExcelApp)
then


  
begin


    
ExcelApp.Quit;


    
ExcelApp := Unassigned;


  
end;


end;


end;  










//COMPROBAR SI OLE está instalado




if
not
IsOLEObjectInstalled(
'Excel.Application') then


  
ShowMessage(
'no instalado')


else


  
ShowMessage(
'instalado');








function IsOLEObjectInstalled(Name: String): boolean;


var


ClassID:
TCLSID;


Rez :
HRESULT;


begin





Rez :=
CLSIDFromProgID(PWideChar(WideString(
Name)), ClassID);





if
Rez = S_OK
then


  
Result := true


else


  
Result := false;


end;








¿Cómo exportar una tabla Word a un StringGrid?







uses


ComObj;





procedure TForm1.Button1Click(Sender: TObject);


const


AWordDoc
=
'C:\xyz\testTable.doc';


var


MSWord,
Table: OLEVariant;


iRows,
iCols, iGridRows, jGridCols, iNumTables, iTableChosen: Integer;


CellText: string;


InputString: string;


begin


try


  
MSWord := CreateOleObject(
'Word.Application');


except


  
// Error....


   Exit;


end;





try


  
MSWord.Visible := False;


  
MSWord.Documents.Open(AWordDoc);





  
// Get number of tables
in document


  
iNumTables := MSWord.ActiveDocument.Tables.Count;





  
InputString := InputBox(IntToStr(iNumTables) +


    
' Tables in Word
Document'
, 'Please Enter Table
Number'
, '1');


  
// Todo: Validate string
for integer, range...


  
iTableChosen := StrToInt(InputString);





  
// access table


   Table
:= MSWord.ActiveDocument.Tables.Item(iTableChosen);


  
// get dimensions of
table


   iCols
:= Table.Rows.Count;


   iRows
:= Table.Columns.Count;


  
// adjust stringgrid
columns


  
StringGrid1.RowCount := iCols;


  
StringGrid1.ColCount := iRows +
1;





  
// loop through cells


  
for
iGridRows :=
1
to
iRows
do


    
for
jGridCols :=
1
to
iCols
do


    
begin


      
CellText := Table.Cell(jGridCols, iGridRows).Range.FormattedText;


      
if
not
VarisEmpty(CellText)
then


      
begin


        
// Remove Tabs


        
CellText := StringReplace(CellText,


           #$D, '',
[rfReplaceAll]);


        
// Remove linebreaks


        
CellText := StringReplace(CellText, #$7,
'',
[rfReplaceAll]);





        
// fill Stringgrid


        
Stringgrid1.Cells[iGridRows, jGridCols] := CellText;


      
end;


    
end;


  
//..


finally


  
MSWord.Quit;


end;


end;





































Delphi twain



Implementación de las funciones twain para Delphi.

Captura imágenes  desde una webcam con unas pocas líneas de código.

3 modos de transferencia de imágenes:

-Desde la memoria,

-Utilizando un handle de windows.

-Utilizando un archivo temporal.



Autor: Gustavo Daud

http://delphitwain.sourceforge.net/

Sitio2:












Trabajar en Google












Esta es una conferencia dada por Arturo Gómez del Castillo (máster en Ingeniería del Software e Ingeniero Técnico en Informática - nota media de 8-) que tiene la suerte de trabajar en la sede de Google en Londres, en la que nos describe su trabajo, nos habla sobre Google, cómo contrata, que requisitos hacen falta para trabajar allí, cuanto se puede ganar, como gestionan la movilidad del personal entre departamentos, etc...por cierto las entrevistas previas a su contratación fueron en inglés.

Casi dos horas de video, muy instructivo para los jóvenes ingenieros que han acabado su carrera.



Asegurar / monitorizar Firebird

Estos son algunos tips que hay que tener encuenta para proteger las bases de datos Firebird:



-Cambiar la contraseña:

gsec –user SYSDBA –pa "antiguo pass" –modify SYSDBA –pw "nuevo pass"


-Abrir el puerto 3050 como aquí te indica si quieres que los usuarios accedan desde fuera a tu sistema, si estás en un entorno web en donde tienes en el servidor tus bases de datos esto no hace falta hacerlo.

Ejecutar Firebird como non-system-user:

-Crear un usuario por ejemplo "UsuarioFB", que no pertenezca a ningun grupo de usuarios del sistema y en la ventana de propiedades desmarcar el check "Allow logon to terminal server"

-En la carpeta donde estén las bases de datos en Propiedades->Seguridad añadir el usuario "UsuarioFB" con los permisos de lectura, escritura,listar directorios, listado y ejecución.

En entornos web con que des permisos al usuario "iusr" de lectura y escritura es suficiente.

- Hay que cambiar las propiedades del servicio "Firebird Server – DefaultInstance" y "FB Guardian" de la siguiente manera:

1) desde Propiedades->Recovery cambiando todos los desplegables a "restart recovery"

2) desde Propiedades->Log on pinchar en "This account" y seleccionar el usuario "UsuarioFB" con la contraseña y usuario que hayamos indicado previamente.

3) desde Propiedades->General marcar en tipo de inicio "Automático"

Por regla general, sólo el proceso del servidor Firebird debería tener acceso a los archivos de base de datos. Los usuarios no necesitan, y no deben tener, el acceso a los archivos - ni siquiera de sólo lectura. Ellos consultan bases de datos a través del servidor, y el servidor se asegura de que sólo los usuarios obtengan el tipo de acceso permitido (en su caso) a cualquier objeto dentro de la base de datos.



Monitorización

Firebird incorpora tablas de monitorización que permiten conocer información relativa a la base de datos y a las consultas de los clientes respecto a la base de datos conectada, sentencias preparadas, transacciones, etc

Las tablas son las siguientes:

MON$DATABASE: base de datos conectada. Con información como ruta de la base de

datos, versión de ODS, identificadores de proceso, etc.

- MON$ATTACHMENTS: Conexiones realizadas. Con información de estado, usuario que

hace la conexión, protocolo de conexión, etc.

- MON$STATEMENTS: Sentencias preparadas para ejecutar. Con información como

identificadores, texto, estado, etc.

- MON$CALL_TACK: Pila de llamadas de las sentencias PSQL activas.

- MON$IO_STATS: Estadísticas de I/O.

- MON$RECORD_STATS: Estadísticas a nivel de fila.

- MON$MEMORY_USAGE: Uso de memoria actual.

- MON$CONTEXT_VARIABLES: Variables de contexto conocida



Ejemplos de consultas:



-Para saber todos los identificadores de procesos con carga de CPU actuales:

SELECT MON$SERVER_PID

FROM MON$ATTACHMENTS

WHERE MON$ATTACHMENT_ID <> CURRENT_CONNECTION

AND MON$STATE = 1



-Para obtener información sobre las aplicaciones clientes

SELECT MON$USER, MON$REMOTE_ADDRESS,

MON$REMOTE_PID,

MON$TIMESTAMP

FROM MON$ATTACHMENTS

WHERE MON$ATTACHMENT_ID <> CURRENT_CONNECTION



-Para obtener el nivelde aislamiento de la transacción actual

SELECT MON$ISOLATION_MODE

FROM MON$TRANSACTIONS

WHERE MON$TRANSACTION_ID = CURRENT_TRANSACTION



-Para obtener las sentencias actualmente activas

SELECT ATT.MON$USER,

ATT.MON$REMOTE_ADDRESS,

STMT.MON$SQL_TEXT,

STMT.MON$TIMESTAMP

FROM MON$ATTACHMENTS ATT

JOIN MON$STATEMENTS STMT

ON ATT.MON$ATTACHMENT_ID = STMT.MON$ATTACHMENT_ID

WHERE ATT.MON$ATTACHMENT_ID <> CURRENT_CONNECTION

AND STMT.MON$STATE = 1



Créditos:

Simon Carter

Vicente Tejero Trueba (Monitorización)


















Multibuscador con Delphi


Este pequeño programa realiza una búsqueda de archivos utilizando programación multi-hilo.

El buscador estándar de Window permite también realizar búsquedas en varias rutas, pero las realiza en serie, es decir: cuando termina de buscar en una carpeta comienza con la siguiente.

Con este programa se puede buscar en varias carpetas de forma simultanea, mejorando así el tiempo de búsqueda, especialmente en búsquedas sobre unidades de red de distintos servidores (mejora los tiempos del buscador de Windows en un 140% para unidades locales de disco duro y en un 300% para unidades en red.

La idea original y el desarrollo son de Salvador Jover (www.sjover.com) y JM (www.lawebdejm.com).

Realizado inicialmente para la revista Síntesis del Grupo Albor (www.grupoalbor.com)



Codigo fuente






Simulación del movimiento de los electrones en un campo electrico

Espectacular simulación realizada con OpenGL del movimiento de los electrones cuando atraviesan un campo eléctrico. Como muestra la image...