Navigation Menu Search PhysiologyWeb
PhysiologyWeb Logo Search PhysiologyWeb
   
— share —
Share on Facebook    Share on X    Share on LinkedIn    Share on Pinterest    Share on Reddit    Email    Copy URL
procedure TForm1.PrintMicrosoftWordFileToAdobePDF(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.ExportAsFixedFormat(PDFFileName, 17, False, 0, 0); //wdExportFormatPDF = 17
//If a file with the new name already exists, it overwrites it. Write additional code to address as desired.
//parameters:
//Name Required/Optional Data type Description
//OutputFileName Required String The path and file name of the new PDF or XPS file.
//ExportFormat Required WdExportFormat Specifies either PDF or XPS format. wdExportFormatPDF = 17; wdExportFormatXPS = 18
//OpenAfterExport Optional Boolean Opens the new file after exporting the contents.
//OptimizeFor Optional WdExportOptimizeFor Specifies whether to optimize for screen or print. wdExportOptimizeForPrint = 0; wdExportOptimizeForOnScreen = 1
//Range Optional WdExportRange Specifies whether the export range is the entire document (0), the current page (2), a range of text (3), or the current selection (1). The default is to export the entire document.
//see reference below for additional optional parameters
//reference
//https://docs.microsoft.com/en-us/office/vba/api/word.document.exportasfixedformat
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
— share —
Share on Facebook    Share on X    Share on LinkedIn    Share on Pinterest    Share on Reddit    Email    Copy URL