简体   繁体   English

Android WebView:使用PDF显示网站

[英]Android WebView: Display Website with PDF

In my Xamarin.Android App I am using a WebView to display a website: 在我的Xamarin.Android应用程序中,我使用WebView来显示网站:

AXML: AXML:

<LinearLayout
        android:id="@+id/auditStructurUseCaseLinearLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1">
        <WebView
            android:id="@+id/auditWebview"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>

Fragment.cs: Fragment.cs:

    _webview.SetWebViewClient(new ExtendWebViewClient());
    WebSettings webSettings = _webview.Settings;
    webSettings.JavaScriptEnabled = true;
    webSettings.DisplayZoomControls = false;
    webSettings.BuiltInZoomControls = true;
    _webview.LoadUrl(URL);

ExtendWebViewClient: ExtendWebViewClient:

internal class ExtendWebViewClient : WebViewClient
{
    public override bool ShouldOverrideUrlLoading(WebView view, string url)
    {
        view.LoadUrl(url);
        return true;
    }
}

This works well for normal websites. 这适用于普通网站。 I can navigate inside awebsite and can use it like a normal browser. 我可以在网站内导航,并且可以像普通浏览器一样使用它。

Problem: I want to display PDFs which are embedded inside a website. 问题:我想显示嵌入网站内的PDF。 Today's browser come with PDF Plugins to display PDF, so the question is, is there a kind of PDF Plugin for the WebView or am I missing some settings to display a PDF inside a Website? 当今的浏览器随附有PDF插件来显示PDF,所以问题是,是否存在一种用于WebView的PDF插件,或者我是否缺少一些设置来在网站内显示PDF?

If I try to open websites with PDF, the website asks for a PDF-Viewer. 如果我尝试使用PDF打开网站,则该网站会要求提供PDF查看器。

Translation : Unfortunately, the PDF can not be displayed because you do not have a PDF viewer. 翻译 :很遗憾,由于您没有PDF查看器,因此无法显示PDF。 You can download the PDF here. 您可以在此处下载PDF。 在此处输入图片说明

Unfortunately, the download-button is functionless aswell. 不幸的是,下载按钮也不起作用。

Or maybe someone has another approach which does not use a WebView. 也许有人采用了另一种不使用WebView的方法。

EDIT: 编辑:

I tried using _webview.SetWebChromeClient(new WebChromeClient()); 我尝试使用_webview.SetWebChromeClient(new WebChromeClient()); but this opens the the Chrome App. 但这会打开Chrome应用。 So I tried to use WebViewClient and ChromeViewClient like suggested in this question. 因此,我尝试使用问题中建议的WebViewClientChromeViewClient

WebSettings webSettings = _webview.Settings;
            webSettings.JavaScriptEnabled = true;
            webSettings.DisplayZoomControls = false;
            webSettings.BuiltInZoomControls = true;
            webSettings.SetSupportMultipleWindows(true);
            _webview.SetWebChromeClient(new WebChromeClient());
            _webview.SetWebViewClient(new ExtendWebViewClient());

But this leads to the same problem as described. 但是,这导致了与所述相同的问题。

将您的网址设置为

url = "https://drive.google.com/viewerng/viewer?embedded=true&url=" + GetString(Resource.String.your_pdf_url);

You can use google docs like this 您可以像这样使用Google文档

WebView webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true); 
String pdf = "url_to_your_pdf" ;
webview.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf);

Please refer to the question here . 请在这里参考问题。

Now you will also have contents other than pdf and probably a link to pdf somewhere in your site. 现在,您还将拥有除pdf之外的其他内容,并且可能还有站点中某处pdf的链接。 in that case you can put this method inside shouldOverrideLoadingUrl () method. 在这种情况下,您可以将此方法放入shouldOverrideLoadingUrl ()方法中。

Edited based on Comment 根据评论编辑

  1. Download html 下载HTML
  2. change the line containing reference to pdf with iframe - load google docs inside an iframe 使用iframe更改包含对pdf的引用的行-在iframe中加载google docs
  3. instead of webview.loadUrl() try loadDataWithBaseURL(). 而不是webview.loadUrl()尝试使用loadDataWithBaseURL()。 - please refer to this answer if you want more information about how to use loadDataWithBaseUrl(). -如果您想了解有关如何使用loadDataWithBaseUrl()的更多信息,请参考此答案

Use this code to open web view and then i have made a Floating Action Button and on the click of it, you can download the pdf view...Make Sure you enter correct URL's 使用此代码打开Web视图,然后单击“ Floating Action”(浮动操作)按钮,然后单击该按钮即可下载pdf视图...确保输入正确的URL

BUT FIRST..MAKE ANOTHER CLASS NAMED PDFVIEW AND WE WILL USE THIS CLASS METHOD'S IN OUR CODE... 但首先..将另一个类命名为PDFVIEW,我们将在我们的代码中使用此类方法...

CLASS PDFVIEW CODE... CLASS PDFVIEW代码...

public class PdfView {

private static final int REQUEST_CODE=101;

/**
 * convert webview content into to pdf file
 * @param activity pass the current activity context
 * @param webView webview
 * @param directory directory path where pdf file will be saved
 * @param fileName name of the pdf file.
 * */
public static void createWebPrintJob(Activity activity, WebView webView, File directory, String fileName, final Callback callback) {

    //check the marshmallow permission
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            activity.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
            callback.failure();
           return;
        }
    }

    String jobName = activity.getString(R.string.app_name) + " Document";
    PrintAttributes attributes = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        attributes = new PrintAttributes.Builder()
                .setMediaSize(PrintAttributes.MediaSize.ISO_A3)
                .setResolution(new PrintAttributes.Resolution("pdf", "pdf", 600, 600))
                .setMinMargins(PrintAttributes.Margins.NO_MARGINS).build();
    }
    PdfPrint pdfPrint = new PdfPrint(attributes);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        pdfPrint.print(webView.createPrintDocumentAdapter(jobName), directory, fileName, new PdfPrint.CallbackPrint() {
            @Override
            public void success(String path) {
                callback.success(path);
            }

            @Override
            public void onFailure() {
                callback.failure();
            }
        });
    }else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            pdfPrint.print(webView.createPrintDocumentAdapter(), directory, fileName, new PdfPrint.CallbackPrint() {
                @Override
                public void success(String path) {
                    callback.success(path);
                }

                @Override
                public void onFailure() {
                    callback.failure();
                }
            });
        }
    }
}


/**
 * create alert dialog to open the pdf file
 * @param activity pass the current activity context
 * @param title  to show the heading of the alert dialog
 * @param message  to show on the message area.
 * @param path file path create on storage directory
 */
public static void openPdfFile(final Activity activity, String title, String message, final String path){

    //check the marshmallow permission
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            activity.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
            return;
        }
    }

    AlertDialog.Builder builder=new AlertDialog.Builder(activity);
    builder.setTitle(title);
    builder.setMessage(message);
    builder.setPositiveButton("Open", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
            fileChooser(activity,path);
        }
    });

    builder.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    AlertDialog alert = builder.create();
    alert.show();

}

/** callback interface to get the result back after created pdf file*/
public interface Callback{
    void success(String path);
    void failure();
}


/**
 * @param activity pass the current activity context
 * @param path storage full path
 */
private  static void fileChooser(Activity activity, String path) {
    File file = new File(path);
    Intent target = new Intent("android.intent.action.VIEW");
    //Uri uri = FileProvider.getUriForFile(activity, "${applicationId}.com.package.name.fileprovider", file);
    Uri uri = FileProvider.getUriForFile(activity, activity.getApplicationContext().getPackageName()+ ".fileprovider", file);
    target.setDataAndType(uri, "application/pdf");
    target.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    Intent intent = Intent.createChooser(target, "Open File");
    try {
        activity.startActivity(intent);
    } catch (ActivityNotFoundException var6) {
        var6.printStackTrace();
    }

}

} }

//NOW MAIN CLASS CODE.. //现在是主要类别代码。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_orders);

    mToolbar = (Toolbar) findViewById(R.id.toolbar);
    WebView wb = (WebView) findViewById(R.id.webview);

    wb.getSettings().setBuiltInZoomControls(true);


    Pbar = (ProgressBar) findViewById(R.id.pB1);


        WebSettings ws = wb.getSettings();
        ws.setJavaScriptEnabled(true);
        ws.setDomStorageEnabled(true);
        ws.setAllowFileAccess(true);
        wb.getSettings().setBuiltInZoomControls(true);
        //   wb.getSettings().setDisplayZoomControls(false);
        wb.clearCache(true);

    wb.setWebChromeClient(new WebChromeClient() {

        public void onProgressChanged(WebView view, int progress) {
            if (progress < 100 && Pbar.getVisibility() == ProgressBar.GONE) {
                Pbar.setVisibility(ProgressBar.VISIBLE);
            }
            Pbar.setProgress(progress);
            if (progress == 100) {
                Pbar.setVisibility(ProgressBar.GONE);
                pdfdownload.setVisibility(View.VISIBLE);
            }
        }

    });

    pdfdownload = (FloatingActionButton) findViewById(R.id.pdf);

    pdfdownload = (FloatingActionButton) findViewById(R.id.pdf);
    pdfdownload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM + "/ANY_DIRECTORY/");

            final ProgressDialog progressDialog = new ProgressDialog(context);
            progressDialog.setMessage("Please wait");
            progressDialog.show();

            //PDFView Class Method
            PdfView.createWebPrintJob(context, wb, path, fileName, new PdfView.Callback() {

                @Override
                public void success(String path) {
                    progressDialog.dismiss();
                    PdfView.openPdfFile(context.this, getString(R.string.app_name), "Do you want to open the pdf file?" + fileName, path);
                }

                @Override
                public void failure() {
                    progressDialog.dismiss();

                }
            });

        }
    });

    wb.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // do your handling codes here, which url is the requested url
            // probably you need to open that url rather than redirect:
            Log.e("redirectUrl", "" + url);


       //CHECK YOUR URL CONDITIONS TO OPEN RIGHT URL FOR PDF, IF ANY..OTHERWISE LOAD DIRECTLY
    if (url.contains("/guest/home")) {
                view.loadUrl(postUrl);
            } else {
                view.loadUrl(url);
            }

            return false; // then it is not handled by default action
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            Log.e("url finished", url);
                        }
    });

    wb.setDownloadListener(new DownloadListener() {
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
            Log.e("DOWNLOAD", url + " , " + userAgent + " , " + contentDisposition + " , " + mimetype + " , " + contentLength);
            try {
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(newURL[1].trim()));
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, file_name);
                DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                dm.enqueue(request);
                Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                Log.e("download", "download fail" + e.toString());
            }
        }
    });

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM