Search code examples
delphims-wordole

Reading Word-file (*.dot) from program resources


Have a set of Word-templates (files *.dot) and a little program, which create new files base on that templates. It's works fine, but the goal is to make all in one exe-file. I see the solution is to move templates files into program resources. But I don't know, how then I will read them from resources. Tell me, please, how to do this. Maybe you can advise me another solution.

Now, my code is:

procedure TfmMain.CreateDocument0;
var
  TempleateFileName: string;
  WordApp, Document: OleVariant;

  procedure FillBookmark(BookmarkName, bText: string);
  var
    Range: OleVariant;
  begin
    if Document.Bookmarks.Exists(BookmarkName) then
    begin
      Range := Document.Bookmarks.Item(BookmarkName).Range;
      Range.Text := bText;
    end;
  end;
begin
  TempleateFileName := ExtractFilePath(Application.ExeName)+'Templates\0.dot';
  try
    WordApp := GetActiveOleObject('Word.Application');
  except
    try
      WordApp := CreateOleObject('Word.Application');
    except
      on E: Exception do
      begin
        MessageBox(Self.Handle, PChar(E.Message), PChar(fmMain.Caption), MB_OK+MB_ICONERROR);
        Exit;
      end;
    end;
  end;

  try
    Document := WordApp.Documents.Add(TempleateFileName, False);

    FillBookmark('ObjectType', edt0ObjectType.Text);
    ...

    WordApp.Visible := True;
    WordApp.Activate;
  finally
    WordApp := Unassigned;
  end;
end;

That is, I should change this line: Document := WordApp.Documents.Add(TempleateFileName, False);

Read not from file, but from program resource.


Solution

  • Word cannot open documents from memory. Not only does it not have such a feature, you must also bear in mind that Word executes in a separate process. It cannot see the memory in your process, even if it were able to open documents from memory.

    If you do put the documents into linked resources then you will need to extract them to file before asking Word to open them.