0

I am trying to make a report from my data using templates. The PDF using WebView works perfectly fine until my data gets bigger than a certain number (1 more in a for-loop), then it only produces a single blank page. I've checked all possible answers here; this, this, this, and this, but no success.

Here is a snippet of my code:

        Bitmap bitmap = callback.getMapImage();

    WebView wv = new WebView(activity);
    wv.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

            //print
            PrintManager printManager = (PrintManager) activity
                    .getSystemService(Context.PRINT_SERVICE);

            String jobName = activity.getString(R.string.app_name) + " Document";

            PrintDocumentAdapter printAdapter = wv.createPrintDocumentAdapter(jobName);

            printManager.print(jobName, printAdapter, new PrintAttributes.Builder().build());

            reference = null;
        }
    });

    PrepareDocumentForPrintTask printTask = new PrepareDocumentForPrintTask(wv, bitmap);
    printTask.execute();

And the html is created in an asyncTask and loaded as follows:

        @Override
    protected void onPostExecute(Triple<Boolean, String, File> result) {
        activity.runOnUiThread(() -> {
            if (result.getFirst()){
                wv.loadDataWithBaseURL("", result.getSecond(), "text/html", "UTF-8", null);
                reference = wv;
            } else
                Toast.makeText(activity, result.getSecond(), Toast.LENGTH_LONG).show();
        });
    }

I have added largeHeap= "true" and deactivated hardware acceleration but still no success.

Any idea how to fix the problem?

msc87
  • 943
  • 3
  • 17
  • 39

1 Answers1

0

OK, I found a work around to my problem using the following code:

String urlDoc = saveHtmlFile("report",document);
                wv.loadUrl("file://" + urlDoc);

where the function saveHtmlFile() is as follows:

private @Nullable String saveHtmlFile(String fileName, String html) {

    try {
        File outputDir = this.activity.getCacheDir(); 
        File outputFile = File.createTempFile(fileName, ".html", outputDir);
        FileOutputStream out = new FileOutputStream(outputFile);
        byte[] data = html.getBytes();
        out.write(data);
        out.close();
        return outputFile.getPath();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

So basically, storing the html as temp file and loading it using the loadUrl() fixed my problem which makes me believe this should be a bug in WebView!!!

msc87
  • 943
  • 3
  • 17
  • 39