Printing PDF documents in C#
I never though about it, but printing (not creating!) PDF documents from code without user intervention is not a trivial task. Nearly everyone has Adobe Reader or an alternative PDF viewer installed doesn’t help a lot.
Let’s look at the options:
- Adobe has Acrobat SDK, you can use ActiveX controls to view the document, but there is no stable COM, ActiveX or even command line interface for printing documents without user intervention. User at least has to print a button.
- There are pricey commercial components that promise this, but nothing free and handy.
- There claims on web that you can do that using Adobe Type Library, but that’s only possible if a client has Adobe Acrobat (the real thing, but free reader) installed, which is of course a serious limitation, show stopper even.
- Starting Adobe Reader with command line switch is only possible with very old version of the Reader and it doesn’t work with current versions,
But if you dig deep enough you will find out that there is a way to automate printing. By using DDE, of all things (if you don’t know what DDE is, you probably didn’t use a phone with a rotary dial, either).
Here is a sample code I used to print PDF files:
bool tryStart = false;
bool connected = false;
do
{
try
{
// Connect to the server.
// It must be running or an exception will be thrown.
client.Connect();
connected = true;
}
catch (DdeException)
{
// try running Adobe Reader
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "AcroRd32.exe";
p.Start();
p.WaitForInputIdle();
// try this once
tryStart = !tryStart;
}
} while (tryStart && !connected);
// sucessfully connected?
if (connected)
{
// Synchronous Execute Operation
client.Execute("[DocOpen(\"C:\\Test.pdf\")]", 60000);
client.Execute("[FilePrintSilent(\"C:\\Test.pdf\")]", 60000);
client.Execute("[DocClose(\"C:\\Test.pdf\")]", 60000);
client.Execute("[AppExit]", 60000);
}
Since .NET doesn’t natively support DDE, I used free .NET library that was published on GotDotNet, which was moved to MSDN Code Gallery. The sample was not ported so it isn’t available for download, which is a real shame. There is another .NET DDE library on CodePlex, which will work too.
Next best thing is an C++ article on CodeProject that inspired the code above.