How to convert old word documents (.doc) into new documents (.docx) using a template

The job was to convert a bunch of old word documents (.doc) into the new format .docx by using a new template file (.dotx). I have done the task by using word automation (OLE, late binding). The old files contains a header and a footer which should be replaced by the header/footer within the new template file. See the comments in the source code below.

program WordOLEConverter;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  Variants,
  Vcl.OleAuto;

//Some web sites with hints and a more descriptions
//http://www.delphi-treff.de/tipps-tricks/comoledde/word/word-mit-ole-automation-steuern/
//http://www.delphipages.com/forum/archive/index.php/t-134939.html
procedure WordConverter(const aSourceFile, aTemplateFile: string);
var
  Word: Variant;
const
  wdDoNotSaveChanges = $00000000;
  wdUseDestinationStylesRecovery = 19;
  wdFormatDocumentDefault = 16;
begin
  //create word automation object (late bindung)
  Word := CreateOleObject('Word.Application');

  //open word document (*.doc)
  //see https://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.documents.open.aspx
  //for more information about parameter
  Word.Documents.Open(
    aSourceFile,
    false, //ConfirmConversions
    true,  //ReadOnly
    EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam);

  //optional show word (it is slower if word is visible)
  //Word.Visible := True;

  //select all (without header/footer)
  Word.ActiveDocument.Select;

  //copy selection to clipboard
  Word.ActiveDocument.Range.Copy;

  //close old document (no saving)
  Word.ActiveDocument.Close(wdDoNotSaveChanges, EmptyParam, EmptyParam);

  //create a new document using the template file
  Word.Documents.Add(aTemplateFile);

  //select all (if there is some text in the template)
  Word.ActiveDocument.Select;

  //insert from clipboard
  Word.ActiveDocument.Range.Paste;

  //save the document
  Word.ActiveDocument.SaveAs(ChangeFileExt(aSourceFile, '.docx'));

  //close word
  Word.Quit(wdDoNotSaveChanges, EmptyParam, EmptyParam);
end;

begin
  try
    WordConverter('C:\temp\old.doc', 'C:\temp\new_template.dotx');
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

Ein Gedanke zu „How to convert old word documents (.doc) into new documents (.docx) using a template

  1. Pingback: How to automatically apply a style to a word document | Mathias Pannier programmiert

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden /  Ändern )

Google Foto

Du kommentierst mit Deinem Google-Konto. Abmelden /  Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden /  Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden /  Ändern )

Verbinde mit %s