C++ Printing XPS Files

A Google search on 'print xps c++' gives the following article on MSDN:- How To: Print with the XPS Print API. This is all well and good but describes creating an XPS document from scratch to print. Where it is more common to have an existing XPS file, and wanting to print that.

What you actually need is tucked away in this article:- Read an XPS Document into an XPS OM.

Now with those 2 articles you can come up with some code like this to print an XPS doc.


IXpsOMObjectFactory *xpsFactory;

HRESULT hr = CoCreateInstance(__uuidof(XpsOMObjectFactory), NULL, CLSCTX_INPROC_SERVER,__uuidof(IXpsOMObjectFactory),reinterpret_cast<LPVOID*>(&xpsFactory));

IXpsOMPackage *package = NULL;

std::tstring tstrFilename = _T("C:\\MyXPSFile.xps");

hr = xpsFactory->CreatePackageFromFile((LPCTSTR)tstrFilename.c_str(),FALSE,&package);

HANDLE completionEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

IXpsPrintJob *job = NULL;
IXpsPrintJobStream *jobStream = NULL;

StartXpsPrintJob(_T("MyPrinter"),_T("Print Job 1"), NULL, NULL, completionEvent, NULL, 0, &job, &jobStream, NULL);

hr = package->WriteToStream (jobStream, FALSE);

hr = jobStream->Close();

if (completionEvent != NULL)
   if (WaitForSingleObject(completionEvent, INFINITE) == WAIT_OBJECT_0)
      XPS_JOB_STATUS jobStatus;
      hr = job->GetJobStatus(&jobStatus);

   completionEvent = NULL;

jobStream = NULL;

job = NULL;

package = NULL;

Note all error checking has been removed for brevity. The MSDN articles do actually have lots of error checking, so should use it.



Printer Utils is Niris Computer Services's website for all interesting printer software development. © 2018 Niris Computer Services
Go to top