Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print a PDF file with MFC

In my app (MFC, C++) I have a button that creates a PDF file in a path. Now I want to create another button that will print the pdf starting from the path and choosing some option like orientation and number of copies... but I'm not able to do that...

I saw that CPrintDialog shows the default dialog of the printer but I'm not able to attach the PDF file using the path.

I saw also the

ShellExecute(NULL, L"print", L"C:\\Documents\\1.pdf", NULL, NULL, SW_SHOWNORMAL);

that works but in this way I cannot choose any parameter...

How I can use the CPrintDialog to print an existing PDF that is in a path?

like image 905
GiordiX Avatar asked Nov 21 '22 21:11

GiordiX


1 Answers

You have to use ShellExecuteEx and verb printto to get more control over printing:

      SHELLEXECUTEINFO ShellInfo;
      ZeroMemory(&ShellInfo, sizeof(SHELLEXECUTEINFO));
      ShellInfo.cbSize = sizeof(SHELLEXECUTEINFO);
      ShellInfo.lpVerb = L"printto";
      ShellInfo.lpFile = L"C:\\Documents\\1.pdf";
      ShellInfo.lpParameters = szPrinter;
      ShellInfo.nShow = SW_SHOWNORMAL;
      ShellInfo.fMask = SEE_MASK_FLAG_DDEWAIT | SEE_MASK_NOCLOSEPROCESS;
      if(::ShellExecuteEx(&ShellInfo))
      {
         if((int)ShellInfo.hInstApp > 32)
         {
            if(ShellInfo.hProcess != NULL)
            {
               DWORD dwExitCode = STILL_ACTIVE;
               while(dwExitCode == STILL_ACTIVE)
               {
                  if(!::GetExitCodeProcess(ShellInfo.hProcess, &dwExitCode))
                  {
                     dwExitCode = 0;
                  }
               }
               ::CloseHandle(ShellInfo.hProcess);
            }
         }
      }

To get the printer name:

CPrintDialog dlg(TRUE);
if (dlg.DoModal() == IDOK)
{
    CString sPrinterName = dlg.GetDeviceName();
}
like image 119
Andrew Komiagin Avatar answered Jan 10 '23 13:01

Andrew Komiagin