Monday, October 24, 2011

Convert external document files to PDF via ShellExecute()

Originally posted in

The easiest way to convert a report into a pdf file is via using a pdfprinter.  There are lots of pdf printers outside there which you can use.  You can check these sites:

to name a few.  Converting the report is as easy as these:

SET PRINTER TO NAME('PrimoPDF') && or something like that or a variable that contains the name of the PDF printer


SET PRINTER TO DEFAULT && This is essential to instruct VFP to return back to its default printer

However, when you will be printing a let us say a text or document file and you want to use ShellExecute() to print it, simply using SET PRINTER TO NAME won’t work.  Why?  Because with ShellExecute(), you are actually going outside of VFP environment.  You will be tapping onto that program where that text file is associated like a Notepad, Wordpad, Excel or MSWord and your SET PRINTER TO NAME will simply be ignored as it is scoped just within your VFP Project.

In cases like that, you need to employ WinApis instead of SET PRINTER NAME trick.  Here is  a simple snippet for that:

?apiSetDefaultPrinter('PrimoPDF')   && for this sample, I am using PrimoPDF

Declare Integer ShellExecute In shell32.dll ;
      INTEGER hndWin, ;
      STRING cAction, ;
      STRING cFileName, ;
      STRING cParams, ;
      STRING cDir, ;
      INTEGER nShowWin

* I used getfile() here so you can test but you can use the target file instead
* if you have one, e.g., “c:\MyFile.txt”

* A delay is necessary to give enough time for spooling, you can increase the delay
* if you think it is needed.  If you don’t put this, the printer will be switched back
* very fast by the command below to the default printer that switching to the pdf printer
* will seem to have failed

* Witch back to default printer (what we have here in the office)
?apiSetDefaultPrinter('Canon MF5700 Series')

Function apiSetDefaultPrinter
Lparameters pszPrinter
Declare Integer SetDefaultPrinter In winspool.drv As apiSetDefaultPrinter ;
      String  pszPrinter
Return apiSetDefaultPrinter(m.pszPrinter)

Function StandbyDelay(lnDelay)
Declare Sleep In kernel32 Integer
dwmilliseconds = m.lnDelay * 1000
Clear Dlls 'Sleep'

And there you have it.  A very easy trick on converting text file using ShellExecute()


  1. Simpo PDF to Text Converter is one of the most efficient PDF converters, as this converter supports batch converting PDF documents to text pdf converters

  2. Thanks for the info! TO add up to the list above, I also found as useful form engine and file to pdf converter, check it out here

  3. This comment has been removed by a blog administrator.

  4. This comment has been removed by a blog administrator.