MS Word Automation in Delphi


Techniques to control MS-Word from a Delphi application are discussed in this blog. As a demonstration, I have added different codes which allows to use Word to create tables, to format strings, to create paragraphs and to insert different objects like images, shapes, word arts etc. Finding a PC that does not have MS-Word installed may prove a difficult task: The word processor from Microsoft is ubiquitous. It therefore makes sense to use it whenever it is necessary to create beautiful output from a program. Delphi makes it actually very easy: The language support for Variants as references to OLE automation servers and the support for COM interfaces make steering MS-Word (or indeed Excel or MS-Access) quite easy.

Controlling MS-Word is done through its COM interface: Through Delphi’s OLE mechanism, an OLE reference is obtained to the MS-Word application, and then the various commands exposed by the MS-Word interface can be used to let MS-Word do virtually anything that is needed. The same can be done with Excel and other members of the MS-Office suite.

Units required to use for MS-Word automation 

Word2000, Office2000

Declare variables before writing codes


var
  sFile         :  String;
  word1       : TWordApplication;
  doc1         : WordDocument;
  section1    : Section;
  para1        : Paragraph;
  range1      : WordRange;
  table1       : Table;
  shape1      : Word2000.Shape;
  comment1 : Comment;
  iLeft, iTop  : Single;

1. Create a New document
begin
  try
    word1 := TWordApplication.Create(Self);
    word1.Connect;
    word1.Visible := True;
    word1.Caption := 'New Document';
    word1.Documents.Add(EmptyParam, EmptyParam, EmptyParam, EmptyParam);    
  finally
    word1.Disconnect;
    word1.Free;
  end;
end;

2. Open existing document
begin
  try
    word1 := TWordApplication.Create(Self);
    word1.Connect;
    word1.Visible := True;
    sFile := ExtractFilePath(Application.ExeName)+'WordTest1.docx';
    word1.Documents.Open(sFile, EmptyParam, EmptyParam, EmptyParam,
                          EmptyParam, EmptyParam, EmptyParam, EmptyParam,
                              EmptyParam, EmptyParam, EmptyParam, EmptyParam);
  Finally
    word1.Disconnect;
    word1.Free;
  end;

3. Turn auto on/off Spelling grammar check during create for performance

    word1.Options.CheckSpellingAsYouType := False;
    word1.Options.CheckGrammarAsYouType := False;

4. Do spelling and grammar check
    word1.CheckSpelling(doc1.Content.Text);
    ShowMessage(IntToStr( doc1.SpellingErrors.Count));
    word1.CheckGrammar(doc1.Content.Text);
    ShowMessage(IntToStr( doc1.GrammaticalErrors.Count));

5. Add a new document
  doc1 := word1.Documents.Add(EmptyParam, EmptyParam, EmptyParam, EmptyParam);
  doc1.Content.Text := 'test';  //Edit Document//
  Doc1.Save;   //Save Document//

6. Add a paragraph or a line with fonr format, paragraph format
    para1 := doc1.Content.Paragraphs.Add(EmptyParam);
    with para1.Range do
    begin
      Text := 'Word Automation in Delphi';
      Font.Size := 16;
      Font.Bold := 1;
      Font.Underline := 1;
      Font.Color := wdColorRed;
      ParagraphFormat.Alignment := wdAlignParagraphCenter;
    end;
    para1.Range.InsertParagraphAfter;

7. Paragraph with back groundcolor and selection color
    para1 := doc1.Content.Paragraphs.Add(EmptyParam);
    with para1.Range do
    begin
      Text := 'Line with fotn, back ground color ';
      Font.Name := 'Verdana';
      Font.Size := 11;
      Font.Italic := 1;
      Shading.BackgroundPatternColor := wdColorYellow;
      MoveStart(wdCharacter, 83);
      Font.StrikeThrough := 1;
      Font.Color := wdColorRed;
      Shading.BackgroundPatternColor := wdColorSkyBlue;
      ParagraphFormat.Alignment := wdAlignParagraphRight;
    end;
    para1.Range.InsertParagraphAfter;

8. Insert picture
    para1.Range.InlineShapes.AddPicture('C:\Test\test1.png', False, True, EmptyParam);
    para1.Range.InsertParagraphAfter;

9. Insert word art
    iLeft := para1.Range.Information[wdHorizontalPositionRelativeToPage];
    iTop := para1.Range.Information[wdVerticalPositionRelativeToPage];
    doc1.Shapes.AddTextEffect(msoTextEffect29, 'Auto Word Art', 'Algerian', 20, 0, 0, iLeft, iTop,EmptyParam);
    para1.Range.InsertParagraphAfter;

10. Insert text box
    iLeft := para1.Range.Information[wdHorizontalPositionRelativeToPage];
    iTop := para1.Range.Information[wdVerticalPositionRelativeToPage];
    Shape1 := doc1.Shapes.AddTextbox(msoTextOrientationHorizontal, iLeft, iTop, 180, 40, EmptyParam);
    shape1.TextFrame.TextRange.Text := 'Enter Your Address Here';
    shape1.TextFrame.TextRange.Font.Bold := 1;
    shape1.TextFrame.TextRange.Font.Color := wdColorBlue;
    para1.Range.InsertParagraphAfter;

11. Insert line shape
    iLeft := para1.Range.Information[wdHorizontalPositionRelativeToPage];
    iTop := para1.Range.Information[wdVerticalPositionRelativeToPage];
    Shape1 := doc1.Shapes.AddLine(iLeft, iTop, iLeft+300, iTop, EmptyParam);
    shape1.Line.ForeColor.RGB := wdColorPink;
    shape1.Line.Weight := 2;
    shape1.Line.DashStyle := msoLineDashDot;
    para1.Range.InsertParagraphAfter;

12. Insert line with style
    iLeft := para1.Range.Information[wdHorizontalPositionRelativeToPage];
    iTop := para1.Range.Information[wdVerticalPositionRelativeToPage];
    Shape1 := doc1.Shapes.AddLine(iLeft, iTop, iLeft+300, iTop, EmptyParam);
    shape1.Line.Style := msoLineThinThick;
    shape1.Line.Weight := 5;
    para1.Range.InsertParagraphAfter;

13. Insert line with color and pattern
    iLeft := para1.Range.Information[wdHorizontalPositionRelativeToPage];
    iTop := para1.Range.Information[wdVerticalPositionRelativeToPage];
    Shape1 := doc1.Shapes.AddLine(iLeft, iTop, iLeft+300, iTop, EmptyParam);
    shape1.Line.Pattern := msoPatternOutlinedDiamond;
    shape1.Line.Weight := 5;
    shape1.Line.ForeColor.RGB := wdColorRed;
    shape1.Line.BackColor.RGB := wdColorLightGreen;

14. Insert line with arrow
    iLeft := para1.Range.Information[wdHorizontalPositionRelativeToPage];
    iTop := para1.Range.Information[wdVerticalPositionRelativeToPage];
    Shape1 := doc1.Shapes.AddLine(iLeft, iTop, iLeft+300, iTop, EmptyParam);
    shape1.Line.Weight := 5;
    shape1.Line.ForeColor.RGB := wdColorPink;
    shape1.Line.BeginArrowheadStyle :=  msoArrowheadStealth;
    shape1.Line.BeginArrowheadLength :=  msoArrowheadLengthMedium;
    shape1.Line.BeginArrowheadWidth :=  msoArrowheadWide;

15. Insert Line with different arrow style
    iLeft := para1.Range.Information[wdHorizontalPositionRelativeToPage];
    iTop := para1.Range.Information[wdVerticalPositionRelativeToPage];
    Shape1 := doc1.Shapes.AddLine(iLeft, iTop, iLeft+300, iTop, EmptyParam);
    shape1.Line.Weight := 5;
    shape1.Line.ForeColor.RGB := wdColorYellow;
    shape1.Line.EndArrowheadStyle :=  msoArrowheadStealth;
    shape1.Line.EndArrowheadLength :=  msoArrowheadLengthMedium;
    shape1.Line.EndArrowheadWidth :=  msoArrowheadWide;
    shape1.Line.BeginArrowheadStyle :=  msoArrowheadDiamond;
    shape1.Line.BeginArrowheadLength :=  msoArrowheadLengthMedium;
    shape1.Line.BeginArrowheadWidth :=  msoArrowheadWide;

16. Insert arrow shape
    iLeft := para1.Range.Information[wdHorizontalPositionRelativeToPage] ;
    iTop := para1.Range.Information[wdVerticalPositionRelativeToPage];
    Shape1 := doc1.Shapes.AddShape(msoShapeUpArrow, iLeft, iTop, 100, 100, EmptyParam);
    shape1.Fill.PresetTextured(msoTextureWaterDroplets);

17. Insert smiley face
    iLeft := para1.Range.Information[wdHorizontalPositionRelativeToPage]  + 120;
    iTop := para1.Range.Information[wdVerticalPositionRelativeToPage];
    Shape1 := doc1.Shapes.AddShape(msoShapeSmileyFace, iLeft, iTop, 100, 100, EmptyParam);
    shape1.Fill.ForeColor.RGB := wdColorYellow;
    shape1.Fill.BackColor.RGB := wdColorRed;
    shape1.Fill.TwoColorGradient(msoGradientHorizontal, 1);//variant 1-3//

18. Insert shape oval
    iLeft := para1.Range.Information[wdHorizontalPositionRelativeToPage] + 240;
    iTop := para1.Range.Information[wdVerticalPositionRelativeToPage];
    Shape1 := doc1.Shapes.AddShape(msoShapeOval, iLeft, iTop, 100, 100, EmptyParam);
    shape1.Fill.PresetGradient(msoGradientFromCenter, 3, msoGradientHorizon);

19. Insert shape sun
    iLeft := para1.Range.Information[wdHorizontalPositionRelativeToPage] + 360;
    iTop := para1.Range.Information[wdVerticalPositionRelativeToPage] ;
    Shape1 := doc1.Shapes.AddShape(msoShapeSun, iLeft, iTop, 100, 100, EmptyParam);
    shape1.TextFrame.TextRange.Text := 'Sun';
    shape1.TextFrame.TextRange.Font.Bold := 1;
    shape1.TextFrame.TextRange.Font.Color := wdColorWhite;
    shape1.Fill.ForeColor.RGB := wdColorRed;
    shape1.Fill.BackColor.RGB := wdColorOrange;

20. Insert superscript character 
    para1 := doc1.Content.Paragraphs.Add(EmptyParam);
    with para1.Range do
    begin
      Text := '10th Standard';
      MoveStart(wdCharacter, 2); // from start to 2 character. 0 based index
      MoveEnd(wdCharacter, -9);  // from end to 9 character. 0 based index
      Font.Superscript := 1;
    end;

21. Insert subscript character 
    para1 := doc1.Content.Paragraphs.Add(EmptyParam);
    with para1.Range do
    begin
      Text := 'H2O is formula of water';
      MoveStart(wdCharacter, 1); // from start to 1 character.0 based index
      MoveEnd(wdCharacter, -21);  // from end to 21 character. 0 based index
      Font.Subscript := 1;
    end;

22. Insert paragraph with format and border
    para1 := doc1.Content.Paragraphs.Add(EmptyParam);
    with para1.Range do
    begin
      Text := DupeString('Paragraph with Align=Justify; BGColor, Space and border. ', 5);
      ParagraphFormat.Alignment := wdAlignParagraphJustify;
      ParagraphFormat.Shading.BackgroundPatternColor := wdColorLightOrange;
      ParagraphFormat.Space2;
      ParagraphFormat.Borders.Enable := 1;
    end;
    para1.Range.InsertParagraphAfter;

23. Removed border from paragraph
    ParagraphFormat.Borders.Enable := 0;

24. Paragraph first line indent
    para1 := doc1.Content.Paragraphs.Add(EmptyParam);
    with para1.Range do
    begin
      Text := DupeString('Paragraph with Align=Left; First Line Indent , BGColor, Space and border. ', 5);

      ParagraphFormat.Alignment := wdAlignParagraphLeft;
      ParagraphFormat.Shading.BackgroundPatternColor := wdColorLightGreen;
      ParagraphFormat.Space2;
      ParagraphFormat.FirstLineIndent := 20;
      ParagraphFormat.Borders.Enable := 1;
    end;

25. Insert bullet list
    para1 := doc1.Content.Paragraphs.Add(EmptyParam);
    with para1.Range do
    begin
      Text := 'INDIA'+#13+'PAKISTAN'+#13+'CHINA'+#13+'BANGLADESH'+#13+'SRILANKA';
      ListFormat.ApplyBulletDefaultOld;
      Shading.BackgroundPatternColor := wdColorLightTurquoise;
    end;
    para1.Range.InsertParagraphAfter;

26. Insert numbered list
   para1 := doc1.Content.Paragraphs.Add(EmptyParam);
    with para1.Range do
    begin
      Text := 'MATH'+#13+'PHYSICS'+#13+'CHEMISTRY'+#13+'BOTANY'+#13+'ZOOLOGY';
      ListFormat.ApplyNumberDefaultOld;
      Shading.BackgroundPatternColor := wdColorLightGreen;
    end;
    para1.Range.InsertParagraphAfter;

27. Insert outlined number format
   para1 := doc1.Content.Paragraphs.Add(EmptyParam);
    with para1.Range do
    begin
      Text := 'LION'+#13+'TIGER'+#13+'ELEPHANT'+#13+'CHEETAH';
      ListFormat.ApplyOutlineNumberDefaultOld;
      Shading.BackgroundPatternColor := wdColorLightYellow;
    end;
    para1.Range.InsertParagraphAfter;

28. Insert multi level number list
   para1 := doc1.Content.Paragraphs.Add(EmptyParam);
    with para1.Range do
    begin
      Text := 'INDIA';
      ListFormat.ApplyNumberDefaultOld;
      Font.Color := wdColorBlue;
    end;
    para1.Range.InsertParagraphAfter;

    para1 := doc1.Content.Paragraphs.Add(EmptyParam);
    with para1.Range do
    begin
      Text := 'NEW DELHI'+#13+'BOMBAY'+#13+'CHENNAI';
      ListFormat.ListIndent;
      Font.Color := wdColorRed;
    end;
    para1.Range.InsertParagraphAfter;

    para1 := doc1.Content.Paragraphs.Add(EmptyParam);
    with para1.Range do
    begin
      Text := 'PAKISTAN';
      ListFormat.ListOutdent;
      Font.Color := wdColorViolet;
    end;
    para1.Range.InsertParagraphAfter;

    para1 := doc1.Content.Paragraphs.Add(EmptyParam);
    with para1.Range do
    begin
      Text := 'KARACHI';
      ListFormat.ListIndent;
      Font.Color := wdColorIndigo;
    end;
    para1.Range.InsertParagraphAfter;

    para1 := doc1.Content.Paragraphs.Add(EmptyParam);
    with para1.Range do
    begin
      Text := 'BANGLADESH';
      ListFormat.ListOutdent;
      Font.Color := wdColorBrown;
    end;
    para1.Range.InsertParagraphAfter;

    para1 := doc1.Content.Paragraphs.Add(EmptyParam);
    with para1.Range do
    begin
      Text := 'DHAKA';
      ListFormat.ListIndent;
      Font.Color := wdColorLime;
    end;
    para1.Range.InsertParagraphAfter;

29. Remove bullet and numbered format
    ListFormat.RemoveNumbers(wdNumberParagraph);

30. Insert symbol
    para1 := doc1.Content.Paragraphs.Add(EmptyParam);
    with para1.Range do
    begin
      para1.Range.InsertBefore('Symbol');
      InsertSymbol(87, 'Symbol', EmptyParam, EmptyParam);
      InsertSymbol(166, 'Webdings', EmptyParam, EmptyParam);
      InsertSymbol(253, 'Wingdings', EmptyParam, EmptyParam);
      InsertSymbol(254, 'Wingdings', EmptyParam, EmptyParam);
    end;
    para1.Range.InsertParagraphAfter;

31. Insert table with format and merged cell
    // a table of 5 rows and 5 columns//
    table1 := doc1.Content.Tables.Add(para1.Range, 5, 5, EmptyParam, EmptyParam );
    table1.Borders.Enable := 1;
    table1.Columns.Item(1).Width := word1.InchesToPoints(0.5);
    table1.Columns.Item(2).Width := word1.InchesToPoints(2);
    table1.Columns.Item(3).Width := word1.InchesToPoints(3);
    table1.Columns.Item(4).Width := word1.InchesToPoints(0.5);
    table1.Columns.Item(5).Width := word1.InchesToPoints(0.5);
    table1.Columns.Item(4).Shading.BackgroundPatternColor := wdColorYellow;
    table1.Columns.Item(5).Shading.BackgroundPatternColor := wdColorYellow;
    // table headers//
    table1.Cell(1, 1).Range.Text := 'Sr. No';
    table1.Cell(1, 2).Range.Text := 'Name';
    table1.Cell(1, 3).Range.Text := 'Address';
    table1.Rows.Item(1).Range.Font.Bold := 1;
    table1.Rows.Item(1).Range.Font.Color := wdColorBlue;
    table1.Rows.Item(1).Range.Shading.BackgroundPatternColor := wdColorGray125;
table1.Rows.Item(1).Cells.Item(4).Merge(table1.Rows.Item(1).Cells.Item(5));
    table1.Cell(1, 4).Range.Text := 'Marks';
    table1.Cell(1, 4).Range.ParagraphFormat.Alignment := wdAlignParagraphCenter;
    //data filling//    
    table1.Cell(2, 1).Range.Text := '1';
    table1.Cell(2, 2).Range.Text := 'RAJ';
    table1.Cell(2, 3).Range.Text := 'DELHI';
    table1.Cell(2, 4).Range.Text := '40';
    table1.Cell(2, 5).Range.Text := '50';
    table1.Rows.Item(2).Range.Font.Color := wdColorRed;
    table1.Cell(3, 1).Range.Text := '2';
    table1.Cell(3, 2).Range.Text := 'KAMAL';
    table1.Cell(3, 3).Range.Text := 'BOMBAY';
    table1.Cell(3, 4).Range.Text := '67';
    table1.Cell(3, 5).Range.Text := '95';
    table1.Rows.Item(3).Range.Font.Color := wdColorRed;
    table1.Cell(4, 1).Range.Text := '3';
    table1.Cell(4, 2).Range.Text := 'SARIF';
    table1.Cell(4, 3).Range.Text := 'SRINAGAR';
    table1.Cell(4, 4).Range.Text := '94';
    table1.Cell(4, 5).Range.Text := '24';
    table1.Rows.Item(4).Range.Font.Color := wdColorRed;
    table1.Cell(5, 1).Range.Text := '4';
    table1.Cell(5, 2).Range.Text := 'MITHESH';
    table1.Cell(5, 3).Range.Text := 'VARANASI';
    table1.Cell(5, 4).Range.Text := '46';
    table1.Cell(5, 5).Range.Text := '45';
    table1.Rows.Item(5).Range.Font.Color := wdColorRed;

32. Insert header and footer
    section1 := doc1.Sections.Add(EmptyParam, EmptyParam);
    with section1.Headers.Item(wdHeaderFooterPrimary) do
    begin
      Range.Text := 'Document Header';
      Range.ParagraphFormat.Alignment := wdAlignParagraphCenter;
      Range.Font.Bold := 1;
      Range.Font.Color := wdColorRed;
      PageNumbers.Add(wdAlignPageNumberRight, 1);
    end;
    with section1.Footers.Item(wdHeaderFooterPrimary) do
    begin
      Range.Text := 'Document Footer';
      Range.ParagraphFormat.Alignment := wdAlignParagraphCenter;
      Range.Font.Bold := 1;
      Range.Font.Color := wdColorBlue;
    end;

33. Selection and range
   Range1 := doc1.Range(0,7);
   Range1.Select;
   Range1 := doc1.Range(doc1.Content.Start, doc1.Content.End);
   Range1.Select;
   Doc1.Content.Select;

34. Move to specific character, line , table, paragraph etc.
//wdCharacter, wdWord, wdSentence, wdParagraph, wdCell, wdColumn, wdRow, wdTable//
    range1 := doc1.Range(1, 7);
    range1.Move(wdCharacter, 5); //will move 5 char//
    range1.MoveStart(wdCharacter, 7);
    range1.MoveEnd(wdCharacter, 7);

35. Select specific line
   Sectence1 := doc1.Sentences.Item(3);
   range1.Select;
   Range1 := doc1.Range(0,7);
   Range1.Select;

36. Cut, copy, paste
    para1.Range.Cut;
    para1.Range.Copy;
    para1.Range.Paste;

37. Find a word
    word1.Selection.Find.Text := 'some';
    word1.Selection.Find.ClearFormatting;
    word1.Selection.Find.Forward := True;
    word1.Selection.Find.Wrap := wdFindContinue;
    word1.Selection.Find.MatchWholeWord := True;
    if word1.Selection.Find.Execute(EmptyParam,EmptyParam, EmptyParam,
                EmptyParam, EmptyParam, EmptyParam, EmptyParam,
                EmptyParam, EmptyParam, EmptyParam , EmptyParam,
                EmptyParam, EmptyParam, EmptyParam, EmptyParam) then
    ShowMessage('yes');

38. Find and replace
    word1.Selection.Find.Text := 'some';
    word1.Selection.Find.ClearFormatting;
    word1.Selection.Find.Forward := True;
    word1.Selection.Find.Wrap := wdFindContinue;
    word1.Selection.Find.MatchWholeWord := True;

    word1.Selection.Find.Replacement.Text := 'test1';
    word1.Selection.Find.Replacement.ClearFormatting;
    word1.Selection.Find.Replacement.Highlight := 1;
    word1.Selection.Find.Execute(EmptyParam,EmptyParam, EmptyParam,
                EmptyParam, EmptyParam, EmptyParam, EmptyParam,
                EmptyParam, EmptyParam, EmptyParam , wdReplaceAll,
                EmptyParam, EmptyParam, EmptyParam, EmptyParam);

39. Print Preview
    doc1.PrintPreview;

40. Print and printpreview   
    doc1.PrintOut(EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam );



Comments

  1. This comment has been removed by the author.

    ReplyDelete
  2. Hi there Jitendra... this is great. I was specifically looking for how to programmatically remove a shape using delphi. I did record a macro on msword and got this:
    Sub RemoveShape()
    '
    ' RemoveShape Macro
    '
    '
    ActiveDocument.Shapes("Picture 2").Select
    Selection.ShapeRange.Delete
    ActiveDocument.Save
    End Sub

    But my attempts to translate this to delphi have failed. Can you show me where I am wrong?

    ...
    WordFile := WordApplication.Documents.Open(WordFileName);
    ...
    WordFile.Shapes('Picture 2').Select;
    WordFile.Selection.ShapeRange.Delete;

    I get "shape/selection not supported by automation object" error on both lines.

    ReplyDelete
    Replies
    1. BTW I'm trying to update logo on about 200 word documents from old to new logo on the headers

      Delete

Post a Comment

Popular posts from this blog

ShellExecute in Delphi

MS Excel Automation in Delphi

Drawing Shapes in Delphi