Printing formatted XML

EFlynn

New member
Joined
Jan 23, 2008
Messages
3
Programming Experience
1-3
I am working on a VB.NET (2.0) windows application.

Currently, the application allows you to pick a respondent, click on their name - on the click event, a formatted XML file is presented in the browser (IE6) with their details. From IE the client can print the XML document. Everything works fine.

New requirement - the client wants to print a batch of these documents without having to open up an instance of IE for each one.

I tried printing the XML directly from my VB code but of course that doesn't work because the printer can't interpret the XML (the print-out contains all the XML tags and it's not formatted).

I was thinking of trying to convert the XML document to Word and then printing that or trying to open IE and send a print command. I haven't tried either yet because I am convinced there is an easier way to do it.

Any suggestions?
 
Load each xml into a WebBrowser control and call its Print method, you could use its DocumentCompleted event, but it's far more easy to manage with a Thread. The control doesn't need to be visible, but if you decide to addd print preview functionality it has to be attached to a form else the print preview dialog will misbehave. Here is a sample of how this can be done with a Thread, runPrintJobs method starts the show and is called from your UI thread.
VB.NET:
Private Sub runPrintJobs()
    Dim t As New Threading.Thread(AddressOf printthread)
    t.IsBackground = True
    t.SetApartmentState(Threading.ApartmentState.STA)
    t.Start()
End Sub

Private Sub printthread()
    Dim wb As New WebBrowser
    Dim file As String = IO.Path.Combine(Application.StartupPath, "data.xml")
    For i As Integer = 1 To 20
        wb.Navigate(file)
        Do Until wb.ReadyState = WebBrowserReadyState.Complete
            Application.DoEvents()
        Loop
        wb.Print()
    Next
    wb.Dispose()
    MsgBox("done")
End Sub
As you see here twenty copies of same document is printed, For-Next could easily be subsituted with a For-Each of your document files.
 
Brilliant! Thanks very much JohnH. That solves my problem perfectly! And, it's so much eaiser than I was expecting.
 
Back
Top