Stavros_S Stavros_S - 4 months ago 82
Javascript Question

Displaying a PDF from a URL in Nativescript

I'm trying to display a PDF from a url using a webview. I've tried loading it using the src attribute and the url attribute. I've also attempted to load it from the onLoaded event in Javascript, but still no luck...Is there a better way to load a PDF doc in a Nativescript app? The webview loads something small like the google url with out any issues. Here's some of the code I've tried.

// did not work
<WebView row="0" id="eula-view" src="https://somewebsite/eula/foo.pdf"/>

// did not work
<WebView row="0" id="eula-view" url="https://somewebsite/eula/foo.pdf" />

//worked fine
<WebView row="0" id="eula-view" url="http://google.com" />


Loading from JS rather than from xml

//did not work
exports.viewLoaded = function (args) {
var page = args.object;
var webview = page.getViewById("eula-view");
webview.url = "https://somewebsite/eula/foo.pdf";
};

// worked fine
exports.viewLoaded = function (args) {
var page = args.object;
var webview = page.getViewById("eula-view");
webview.url = "http://google.com";
};

Answer

You could use Google Docs to display PDF file in NativeScript WebView for Android. You could review my example below:

main-page.xml

<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo">
</Page>

main-page.js

var web_view_1 = require("ui/web-view"); 
function navigatingTo(args) {
    // Get the event sender
    var page = args.object;
    var webview = new web_view_1.WebView();
    var webview2 = new web_view_1.WebView();
    webview.on(web_view_1.WebView.loadFinishedEvent, function (args) {
        var message;
        if (!args.error) {
            message = "WebView finished loading " + args.url;
        }
        else {
            message = "Error loading " + args.url + ": " + args.error;
        }
    });
    webview.src = "<!DOCTYPE html><html><head><title>MyTitle</title> <meta charset='utf-8' /></head><body>\n  <h1>Test loading pdf document</h1>\n  <iframe src=\"http://docs.google.com/gview?url=“+pdfFileURL+"&embedded=true\" \nstyle=\"width:600px; height:500px;\" frameborder=\"0\"></iframe>\n  </body></html>";
    page.content = webview;
}
exports.navigatingTo = navigatingTo;