티스토리 뷰

Android Tip - Displaying a PDF Document inside a WebView


One of the most requested features in Android is the ability to display a PDF document within a WebView. However, the WebView does not contain a PDF plugin that allow you to display a PDF document. One solution is to use an Intent object to launch a third-party app (such as Adobe Acrobat) which can handle the PDF document. However, this will transfer control over to the thrid-party app.

If you insists on displaying the PDF document within your own activity using a WebView, you can use the following trick. You can use Google Docs to open your PDF document and then load the URL of Google Docs using the WebView.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        WebView webView=new WebView(MainActivity.this);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setPluginState(PluginState.ON);

        //---you need this to prevent the webview from
        // launching another browser when a url
        // redirection occurs---
        webView.setWebViewClient(new Callback());
       
        String pdfURL = "http://dl.dropboxusercontent.com/u/37098169/Course%20Brochures/AND101.pdf";
        webView.loadUrl(
"http://docs.google.com/gview?embedded=true&url=" + pdfURL);

        setContentView(webView);
    }

    private class Callback extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(
                WebView view, String url) {
            return(false);
        }
    }

The loaded PDF document will look something like this:



Remember to add in the android.permission.INTERNET permission.

Come join me in the Android Post-Conference workshop on 31 May 2013 at DevTeach 2013, Toronto. 


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
글 보관함