procedure TForm1.OpenMicrosoftWordFileAndSaveAsPDFFile(Sender: TObject);
var
WordFileName, PDFFileName: String;
WordApplication, WordFile: Variant;
begin
//be sure ComObj and Variants units are included in the "uses" clause
WordFileName := 'C:\PhysiologyWeb\delphi_code_examples\word_file.docx'; //replace file name with the name of your file
PDFFileName := ChangeFileExt(WordFileName, '.pdf');
WordApplication := Null;
WordFile := Null;
try
//create Word OLE
WordApplication := CreateOleObject('Word.Application');
except
WordApplication := Null;
//add error/exception handling code as desired
end;
If VarIsNull(WordApplication) = False then
begin
try
WordApplication.Visible := True; //set to False if you do not want to see the activity in the background
WordApplication.DisplayAlerts := False; //ensures message dialogs do not interrupt the flow of your automation process. May be helpful to set to True during testing and debugging.
//Open Word File
try
WordFile := WordApplication.Documents.Open(WordFileName);
//reference
//https://docs.microsoft.com/en-us/office/vba/api/word.documents.open
except
WordFile := Null;
//add error/exception handling code as desired
end;
If VarIsNull(WordFile) = False then
begin
WordFile.SaveAs2(PDFFileName, 17); //wdFormatPDF = 17
//reference
//https://docs.microsoft.com/en-us/office/vba/api/word.saveas2
end;
finally
WordFile.Close;
WordApplication.DisplayAlerts := True;
WordApplication.Quit;
WordFile := Unassigned;
WordApplication := Unassigned;
end;
end;
end;
Posted: Saturday, September 3, 2022
Last updated: Tuesday, March 18, 2025