在webview中打开多个页面并创建PDF [英] Open several pages in webview and create PDF

查看:88
本文介绍了在webview中打开多个页面并创建PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个应用程序,以从Web视图中的多个页面创建PDF.

I am trying to build an app to create a PDF from several pages in webview.

作为初学者,我很高兴发现了以下内容: Android从具有多个页面的webview创建pdf文档

As beginner i was happy i found this: Android create pdf document from webview with multiple pages

但是我无法正确处理. 在PDF中创建的页面数量很好,但内容却不行. 创建具有(在这种情况下)3个相似页面的PDF.均显示调用该方法之前的webview. 完成创建PDF后,将加载url数组的最后一个URL.

However I am not able to get it right. The amount of pages created in the PDF is fine, but the content is not. A PDF with (in this case) 3 similar pages is created. All showing the webview of before the method was called. Once finished creating the PDF, the last url of the url array loads.

我如何才能实现仅在将新的URL加载到Webview中之后创建pdf页面?

我确实尝试过使用延迟,但这似乎不是问题. 如果延迟,则会先创建pdf文件,然后才打开页面.

I did try to use delay, but that does not seem to be the issue. If delayed, the pdf is created first and pages are opened up only after.

我确实尝试从onPageFinished()内部调用pdf创建. 它也没有做这项工作.

I did try to call the pdf creation from within onPageFinished(). It did not do the job either.

也许我确实使用了所有这些错误. 这是我的代码现在的样子:

Maybe i did use all this wrong. Here is what my code looks like right now:

            //Create folder
            String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
            String dirName = "exampledirectory";
            File newdir = new File(baseDir + File.separator + dirName);
            newdir.mkdirs();
            //Create PDF
            String fileName = "example.pdf";
            String fileNameWithPath = newdir + File.separator + fileName;
            //Create document
            PdfDocument document = new PdfDocument();

            String[] urlArr = {"exampleurl1.com", "exampleurl2.com", "exampleurl3.com"};

            for (int i = 0; i < urlArr.length; i++) {
                mWebView.loadUrl(urlArr[i]);
                PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(mWebView.getMeasuredWidth(), mWebView.getContentHeight(), i).create();
                // start [i]st page
                PdfDocument.Page page = document.startPage(pageInfo);
                // draw on the page
                View content = mWebView;
                content.draw(page.getCanvas());
                // finish [i]st page
                document.finishPage(page);
            }

            FileOutputStream fos;
            try {
                fos = new FileOutputStream(fileNameWithPath, false);
                // write the document content
                document.writeTo(fos);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            document.close();

推荐答案

我找到了适合我的解决方案. 感觉有点奇怪,但确实可以.

I found a solution that works for me. It feels a bit odd, but it does the job.

正如我上面提到的,onPageFinished()在我的第一次尝试中不起作用,因为调用该页面时尚未呈现该页面. 现在,我再次尝试从onPageFinished()调用另一个方法,然后再调用PDFbuilder方法.通过这种解决方法",我能够从所有URL构建PDF. 这是代码:

As I mentioned above onPageFinished() did not work on my first tries, cause the page is not rendered yet when called. Now I tried again calling another method from onPageFinished() which then calls the PDFbuilder Methods. With this "workaround" I was able to build a PDF from all URLs. Here`s the code:

private class printPDFFromWebcontent {

    int i = 0;
    public String pageURL = "exampleURL";
    public PdfDocument document = new PdfDocument();
    public String fileNameWithPath ="blank.pdf";

    private void runPDFBuilder() {
    zWebView = (WebView) findViewById(R.id.activity_main_webview);
    WebSettings webSettings = zWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    zWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(zWebView, url);
            i++;
            openNextPage();
        }
        private void openNextPage() {
            String nextPage = pageURL + "?page=" + String.valueOf(i + 1); //This works with my specific target URLs. You may want to use an URL array.
            if (i == 1) {
                zWebView.loadUrl(nextPage);
                createPDFNow();
            }
            if (i == 2) {
                zWebView.loadUrl(nextPage);
                addPageToPDF();
            }
            if (i == 3) {
                zWebView.loadUrl(nextPage);
                addPageToPDF();
            }
            if (i == 4) {
                mWebView.loadUrl("whateverYouWantToShowIfFinishedURL"); 
                //Not added to the PDF
                //Reason is to trigger onPageFinished() once more. You could probably i++ here and call openNextPage() from within.
                addPageToPDF(); //Add the last webview content to PDF.
            }
            if (i == 5) {
                createPDFNow();
                Toast.makeText(getApplicationContext(), "Finito.", Toast.LENGTH_SHORT).show();
                savePDF();
                return;
            }
        }
        public void createPDFNow(){
            String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
            String dirName = "example";
            File newdir = new File(baseDir + File.separator + dirName);
            newdir.mkdirs();
            String fileName = "example.pdf";
            fileNameWithPath = newdir + File.separator + fileName;
        }
        public void addPageToPDF() {
            PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(zWebView.getMeasuredWidth(), zWebView.getContentHeight(), i).create();
            PdfDocument.Page page = document.startPage(pageInfo);
            View content = zWebView;
            content.draw(page.getCanvas());
            document.finishPage(page);
        }
        public void savePDF(){
            FileOutputStream fos;
            try {
                fos = new FileOutputStream(fileNameWithPath, false);
                document.writeTo(fos);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            document.close();
        }
    });
    zWebView.getSettings().setUseWideViewPort(true);
    zWebView.getSettings().setLoadWithOverviewMode(true);
    zWebView.loadUrl("URL1");
    return;
}

但是,如果有一个更明智的解决方案:我想学习.

However if there is a smarter solution: I`d like to learn.

这篇关于在webview中打开多个页面并创建PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆