Search code examples
javascriptnativescript

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"; 
};

Solution

  • I've created a NativeScript plugin for displaying PDF files on iOS and Android. I haven't personally tried the WebView approach with Google Docs, because I need to display PDF files from the local device, and don't want to require an active Internet connection.

    The plugin is nativescript-pdf-view. Usage is like this:

    Plain NativeScript:

    <Page
     xmlns="http://schemas.nativescript.org/tns.xsd" loaded="pageLoaded"
     xmlns:pdf="nativescript-pdf-view">
      <StackLayout>
        <pdf:PDFView src="{{ pdfSrc }}"/>
      </StackLayout>
    </Page>
    

    Angular 2

    // somewhere in the JavaScript/TypeScript:
    import 'nativescript-pdf-view';
    
    // in the view:
    <PDFView [src]="pdfSrc"></PDFView>