Reputation: 11
I've written a program in Deplhi XE2 to create a new Word document (using Word 2010 and TWordApplication), insert text, and save it as both a .doc file and a .pdf file.
The two Word components are on the form.
Everything works except for the text insertion. When I open the documents after the fact they are both empty.
procedure TForm1.btnGenerateClick(Sender: TObject);
var
sNewText: WideString;
begin
sNewText := 'Hello, World!' + #13;
{ Create the Word document, set text and close it. }
WordApplication1.Visible := False;
WordApplication1.NewDocument;
WordApplication1.Selection.EndOf(wdStory, wdMove);
WordApplication1.Selection.InsertAfter(sNewText);
WordApplication1.Selection.EndOf(wdStory, wdMove);
if FileExists('d:\temp\MyNewDocDup.doc')
then DeleteFile('d:\temp\MyNewDocDup.doc')
else ;
WordDocument1.SaveAs('d:\temp\MyNewDocDup.doc');
if FileExists('d:\temp\MyNewDocDup.pdf')
then DeleteFile('d:\temp\MyNewDocDup.pdf')
else ;
WordDocument1.SaveAs('d:\temp\MyNewDocDup.pdf', 17);
WordDocument1.Close;
WordApplication1.Disconnect;
end;
Upvotes: 1
Views: 1498
Reputation: 613572
It seems to me that the problem is likely that the document object WordDocument1
is not the document in which the text is added. The text is added fine, just to a different document. Here is a simple example that demonstrates how to do it:
var
app: TWordApplication;
doc: WordDocument;
....
app := TWordApplication.Create(nil);
try
app.Visible := False;
doc := app.Documents.Add(EmptyParam, EmptyParam, EmptyParam, EmptyParam);
app.Selection.EndOf(wdStory, wdMove);
app.Selection.InsertAfter('Hello, World!');
app.Selection.EndOf(wdStory, wdMove);
doc.SaveAs('C:\desktop\MyNewDocDup.doc', EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam);
doc.SaveAs('C:\desktop\MyNewDocDup.pdf', 17, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam);
doc.Close(EmptyParam, EmptyParam, EmptyParam);
app.Quit;
finally
app.Free;
end;
In real code you'd use the named file format constants rather than the magic number 17.
Note that NewDocument
does not create a new document. Instead you need to use Documents.Add
to make a new document. Note also the pain of early binding – all those EmptyParam
arguments are no fun at all. If you are building a large amount of code on top of Office it pays to wrap up such messy details.
As for the documentation to the Office automation API, that can be found on MSDN: http://msdn.microsoft.com/en-us/library/office/ee861527.aspx
Upvotes: 1