Skoči na vsebino

Printing PDF documents in C#

Objavljeno dve minuti branja

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:

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;
        // Connect to the server.
        // It must be running or an exception will be thrown.
        connected = true;
    catch (DdeException)
        // try running Adobe Reader
        System.Diagnostics.Process p = new System.Diagnostics.Process();
        p.StartInfo.FileName = "AcroRd32.exe";
        // 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.