7

I want to print a PDF file from C# code without user interaction.

I tried this accepted answer but it is not working for me.

This is the code I tried:

Process p = new Process();
p.StartInfo = new ProcessStartInfo()
{
     CreateNoWindow = true,
     Verb = "print",
     FileName = @"G:\Visual Studio Projects\PrintWithoutGUI\PrintWithoutGUI\Courses.pdf" //put the correct path here
};
p.Start();

I get this exception :

System.ComponentModel.Win32Exception: 'The specified executable is not a valid application for this OS platform.'`

Wyck
  • 10,311
  • 6
  • 39
  • 60
The None
  • 87
  • 1
  • 1
  • 7

2 Answers2

9

try this by add UseShellExecute=true it will print to default printer but if you want to print to a specific print change the verb print to verb printTo by spefiying the name of the printer Arguments proprety.

 private static void PrintByProcess()
    {
        using (Process p = new Process())
        {
            p.StartInfo = new ProcessStartInfo()
            {
                CreateNoWindow = true,
                UseShellExecute=true,
                Verb = "print",
                FileName = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\doc.pdf"
            };

            p.Start();
        }
bigtheo
  • 624
  • 9
  • 16
  • 2
    Yes, changes in .NET Core require us to use `UseShellExecute` now. See https://github.com/dotnet/runtime/issues/17938 – Dan Friedman Nov 05 '21 at 15:18
2

this is the correct way to write your code

Process p = new Process();
p.StartInfo = new ProcessStartInfo()
{
    CreateNoWindow = true,
    Verb = "print",
    FileName = "PDfReader.exe", //put the path to the pdf reading software e.g. Adobe Acrobat
    Arguments = "PdfFile.pdf" // put the path of the pdf file you want to print
};
p.Start();
Mostafa Mahmoud
  • 182
  • 1
  • 10
  • is there away to not open the **.exe** application ? – The None Sep 25 '19 at 16:58
  • nope, this is the only way to do this. unless you used a pdf library in your project. and there are many of them. for example you can use **IronPDF**, but it's not free. other than this i think this is the only choice you have. plus, in most cases the **.exe** that will run will not be visible, because you've set the *CreateNoWindow* property to true – Mostafa Mahmoud Sep 25 '19 at 17:12
  • i asked you because the **.exe** application appeared ! thanks – The None Sep 25 '19 at 17:24
  • you can try adding `WindowStyle = ProcessWindowStyle.Hidden,` to the initialization of your `new ProcessStartInfo()` – Mostafa Mahmoud Sep 25 '19 at 17:34
  • you can also try to set the `WindowStyle` to `ProcessWindowStyle.Minimized` if the above didn't work – Mostafa Mahmoud Sep 25 '19 at 17:44
  • i did what you suggested for me and the **.exe** application [adobe reader] still being visible , however ,i used Spre.pdf library to do the hide work thank you :) – The None Sep 25 '19 at 18:38