views:

237

answers:

1

Is there any way (library or native) to use the printing API to print an XPS document? I tried using the Document Toolkit API which works up to a point, but I get a COM exception when I try to set PrintPageEventArgs.PageVisual.

A: 

This should do it in native code, don't forget to enable COM first:

    SmartHandle event = ::CreateEvent(NULL, TRUE, FALSE, NULL);
    if (event.get() == 0)
    {
        ::AtlThrow(::GetLastError());
    }

    CComPtr<IXpsOMObjectFactory> pXpsFactory;
    HRESULT hr = pXpsFactory.CoCreateInstance(CLSID_XpsOMObjectFactory);
    if (FAILED(hr))
    {
        ::AtlThrow(hr);
    }

    CComPtr<IXpsPrintJobStream> pDocumentStream;
    hr = ::StartXpsPrintJob(printer, file, NULL, NULL, event.get(), NULL, NULL, NULL, &pDocumentStream, NULL);
    if (FAILED(hr))
    {
        ::AtlThrow(hr);
    }

    CComPtr<IXpsOMPackage> pXpsOMPackage;

    hr = pXpsFactory->CreatePackageFromFile(argv[2], false, &pXpsOMPackage);
    if (FAILED(hr))
    {
        ::AtlThrow(hr);
    }

    hr = pXpsOMPackage->WriteToStream(pDocumentStream, FALSE);
    if (FAILED(hr))
    {
        ::AtlThrow(hr);
    }

    pDocumentStream->Close();

    if (::WaitForSingleObject(event.get(), INFINITE) != WAIT_OBJECT_0)
    {
        ::AtlThrow(hr);
    }
Tony Edgecombe