Thanks to Michael Scherotter for the details explained in this post.

Say you have an x-ms-webview element on a page in your app:

ms-webview id="webview" class="Content" src="ms-appx-web:///contenthost.html">
</x-ms-webview>    

and you want to print only the contents of the WebView. To do this, it seems at first that you need to get a DOM document object for the Webview to pass to MSApp.getHtmlPrintDocumentSource within a PrintTaskSourceRequested event. However, as noted in an earlier post, the Webview's DOM isn't accessible by the host app, for many good reasons, so it seems you're left with solutions like obtaining a bitmap of the Webview and printing that.

But there's another way that can work in a number of scenarios, especially when you know the content you're loading into the Webview and aren't wanting to print arbitrary pages. The trick is to load that content into a new document fragment and use that to obtain a source:

    //content is what you load in the Webview; printTask and printDeferral come from the WinRT print event

    var fragment = document.createDocumentFragment();
    var printSource;
    div = document.createElement("div");

    fragment.appendChild(div);
    WinJS.Utilities.setOuterHTMLUnsafe(div, content);

    source = MSApp.getHtmlPrintDocumentSource(fragment);
    printTask.setSource(source);
    printDeferral.complete();

You new methods like setOuterHTMLUnsafe had a use somewhere!


Comments are closed