Click here to Skip to main content
15,898,036 members
Articles / Desktop Programming / Win32
Tip/Trick

Programmatically Convert PDF to XPS Document Using MXDW

Rate me:
Please Sign up or sign in to vote.
3.58/5 (10 votes)
12 Mar 2015CPOL 37.3K   510   10   13
Programmatically Convert PDF-To-XPS Document

Introduction

This is a hack to programmatically convert PDF documents to XPS documents using Microsoft XPS Document Writer (MXDW).

Using the Code

This approach can be used to convert almost any document to XPS document, provided the 'ProcessStartInfo::Verbs' property of the file supports 'print' or 'printto'. The trick here is to perform UI automation, that's it.

MC++
ProcessStartInfo^ info = gcnew ProcessStartInfo( gcnew String(sourcefile));
info->Arguments = "Microsoft XPS Document Writer";
info->UseShellExecute = true;
info->WindowStyle = ProcessWindowStyle::Hidden;
info->CreateNoWindow = false;

for( int i = 0; i < info->Verbs->Length ; i++)
{
    if(info->Verbs[i]->ToString()->Equals("print",StringComparison::OrdinalIgnoreCase))
    {
        info->Verb="print";
        IsPrintable =true;
        break;
    }
}

/* --- Set MXDW as default printer --- */

Process ^ process =  gcnew Process();
process->Start(info);
Edit(targetfile);

/* --- Reset to the original default printer --- */

Some PDF apps exit after issuing print job, few don't. The following must be considered for such a scenario.

MC++
/*  wait for 20 sec */
    process->WaitForExit(20000);

/*  commented 'wait for infinite time'.
    since some application don't exit,
    even after they are done.
*/

//  process->WaitForExit();

This is where the UI automation is done. Editing the Text box and mimicking the save button key press.

MC++
//edits the filename in text box automatically
void Edit(char * pFileName)
{
    HWND hWnd =0;
    try
    {
        // Find Save File Dialog Box
        do{

            Sleep(1000);
            hWnd = FindWindow(DialogClass, "Save the file as");

        }while(!hWnd);

        GetWnd(hWnd,"Edit","");

    }catch(HWND hChild)
    {
        // Enter file name and mimic key press:
        if(SendMessage(hChild, WM_SETTEXT,NULL, (LPARAM) pFileName) !=0)
        {
            hChild = FindWindowEx(hWnd, NULL, NULL, "&Save");
            SendMessage (hChild, WM_IME_KEYDOWN, 'S', NULL);
        }
    }
    return;
}

Given the parent window handle, GetWnd function traverses through all of its child windows until it finds the one which matches classname and caption provided.

MC++
//throws an exception if match is found
void GetWnd( HWND hWnd,char * classname,char * caption)
{
    if( hWnd ==0 || classname[0] == '\0' || caption == '\0')
        return;

    GetWnd ( GetWindow(hWnd,GW_CHILD),classname,caption );
    char Class[50],Text[50];
    GetClassName(hWnd,Class,50);
    GetWindowText(hWnd,Text,50);
    /* throw exception to come out of recursion */
    if ( !strcmp(Class,classname) && !strcmp(Text,caption) )
        throw hWnd;
    GetWnd ( GetWindow(hWnd,GW_HWNDNEXT),classname,caption);
    return;
}

Fixes

Few PDF applications don't close even after issuing print job, causing pdftoxps to wait for infinite time, this was the main intent in commenting 'process.WaitForExit()' earlier. The source code has been modified a bit to address this issue.

Reference

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionNo need for cumbersome "save" automate Pin
gordon8813-Mar-15 6:27
professionalgordon8813-Mar-15 6:27 
AnswerRe: No need for cumbersome "save" automate Pin
K.badari15-Mar-15 19:59
K.badari15-Mar-15 19:59 
GeneralMy vote of 1 Pin
gordon8813-Mar-15 6:21
professionalgordon8813-Mar-15 6:21 
AnswerRe: My vote of 1 Pin
K.badari15-Mar-15 21:19
K.badari15-Mar-15 21:19 
GeneralRe: My vote of 1 Pin
gordon8811-Aug-18 12:35
professionalgordon8811-Aug-18 12:35 
GeneralMy vote of 1 Pin
Damir Valiulin9-Feb-15 7:26
Damir Valiulin9-Feb-15 7:26 
QuestionRead Acrobat Reader License before using this! Pin
gordon8831-Jan-15 7:30
professionalgordon8831-Jan-15 7:30 
AnswerRe: Read Acrobat Reader License before using this! Pin
K.badari3-Feb-15 1:57
K.badari3-Feb-15 1:57 
GeneralRe: Read Acrobat Reader License before using this! Pin
gordon883-Feb-15 6:34
professionalgordon883-Feb-15 6:34 
I can just say that the license you agree when installing Reader X (and surely others rev)
explicitly say;
4.3.1 Conversion Restriction. You will not integrate or use Adobe Reader with any plug-in software or enhancement that uses or relies upon Adobe Reader when converting or transforming PDF Files into a different format (e.g. a PDF file into a TIFF,JPEG.....)

They make money selling theses services, they will not give up on this!
And believe me they have a very aggressive legal department. They are not the friendly company they look.

BTW:
PDF is NOT a free format.
In order to comply with Adobe licenses, if you want to generate PDF you OUGHT to have at least bought a PDF book from Adobe edited by Addison Wesley.
This grant you a limited right to use and generate PDF (you are not allowed to modify or add anything to the description).

Some initiative are tolerated like PDF/A or PDF/Xn because in time it did help promoting PDF which is the bread and butter business of Adobe.

Last:
Microsoft had an excellent replacement format with XPS. Support ALL PDF features and more since it is an enhancement over SVG based rather than proprietary.
fare more compact, open and more elegantly conceived.
(at least it contain a way to have a structure and hierarchies within the document, PDF is a free for all things that mix content and container, a very very old mind set)

But because it is Microsoft and even if offered to the world, people did move away without understanding that they just continue playing with matches!
Now it is an unsupported format and Microsoft don't care anymore they use DocX.
Gordon

GeneralMy vote of 2 Pin
gordon8831-Jan-15 7:25
professionalgordon8831-Jan-15 7:25 
GeneralMy vote of 1 Pin
tom-englert30-Jan-15 2:18
tom-englert30-Jan-15 2:18 
GeneralMy vote of 3 Pin
barto29-Jan-15 3:58
barto29-Jan-15 3:58 
GeneralRe: My vote of 3 Pin
K.badari3-Feb-15 1:34
K.badari3-Feb-15 1:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.