Search code examples
codenameone

Display pdf inside app without pdf reader


My goal is to view a pdf inside a form just like the way a browsercomponent displays inside a form. I have tried the code from here but that opens the pdf in an external pdf reader. My goal is to display the pdf contents within the app. So I thought that I would either have to display the pdf inside a browsercomponent or integrate an external pdf reader api to open the pdf inside a form. Now, I need help on either:

  1. how to display a pdf inside a browsercomponent OR
  2. is there a pdf reader api that i can integrate in my app such that the pdf opens inside a form or container?

Solution

  • In html, the "object" tag allows you to easily view pdfs in browsers that support this tag. Unfortunately, displaying a pdf with the object tag is possible without problems in desktop browsers, while inside a native app it doesn't work: in particular, Android 10 doesn't support it at all (it will display a white screen), while iOS 13 partially supports it, displaying only the first page and stretching it to the screen size without respecting the proportions of the pdf page (it doesn't allow to go to the next pages).

    Fortunately, there is a compromise solution that works well enough on both Android and iOS, though with some differences. It also works in the Simulator if you have CEF enabled (https://www.codenameone.com/blog/big-changes-jcef.html).

    This is an example code. Note that you don't need to be logged into Google, but there is an usage limit (Reaching the bandwidth limit for viewing pdf files in WebView through Google docs):

    String pdfUrl = "https://www.galgani.it/pdf/linguaggi_programmazione.pdf";
    Form hi = new Form("PDF Viewer", new BorderLayout());
    BrowserComponent browser = new BrowserComponent();
    browser.setURL("https://docs.google.com/viewer?url=" + pdfUrl);
    hi.add(BorderLayout.CENTER, browser);
    hi.show();
    

    If you don't want to end up in Google's birdcage and its limits of use, then you can implement your own cross-platform solution using this javascript: https://mozilla.github.io/pdf.js/

    Finally, you can use native interfaces to use third-party libraries for viewing pdfs, but this is the most complex case. There are commercial solutions to this, but I don't want to advertise to anyone.