Android Web View无法从Amazon Service URL查看PDF

xhv8bpkk  于 2023-05-12  发布在  Android
关注(0)|答案(5)|浏览(118)

我试图通过调用amazon url在android webview中显示pdf文件。但它只显示白色。没有加载。
当我使用其他的网址然后亚马逊它显示pdf文件在webview。我也试过这个:http://docs.google.com/gview?embedded=true&url=“+ MYURL
我也试过写URL:而且效果很好。http://www.durgasoft.com/Android%20Interview%20Questions.pdf
如果有人有什么建议,请指导我。
下面是我的代码供您参考:

webView.getSettings().setJavaScriptEnabled(true);
 webView.getSettings().setPluginState(PluginState.ON);
 String url = Common.getPdfFromAmazon("52f3761d290c4.pdf");   
 webView.loadUrl(url);

Android Menifest.xml also give Internet Permission:
**<uses-permission android:name="android.permission.INTERNET" />**

i can also try this "http://docs.google.com/gview?embedded=true&url=" + url ;

谢谢大家。

lxkprmvk

lxkprmvk1#

要显示来自亚马逊网络服务的PDF,您需要首先将PDF下载并存储到您的设备,然后通过设备上可用的PDF阅读器/查看器应用程序打开它。
1>>调用DownloadFileAsync()调用下载过程并传递您的Amazon Web服务URL。

new DownloadFileAsync().execute(url);

2>>在AsyncTask中执行下载PDF过程。

class DownloadFileAsync extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(final String... aurl) {

        try {
            String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
            File dir = new File(extStorageDirectory, "pdf");
            if(dir.exists()==false) {
                dir.mkdirs();
            }
            File directory = new File(dir, "original.pdf");
            try {
                if(!directory.exists())
                    directory.createNewFile();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            URL url = new URL(aurl[0]);
            URLConnection conexion = url.openConnection();
            int lenghtOfFile = conexion.getContentLength();
            conexion.connect();
            conexion.setReadTimeout(10000);
            conexion.setConnectTimeout(15000); // millis

            FileOutputStream f = new FileOutputStream(directory);

            InputStream in = conexion.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = in.read(buffer)) > 0) {
                f.write(buffer, 0, len1);
            }
            f.flush();
            f.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    @Override
    protected void onPostExecute(String unused) {
    }
}

3>>下载pdf后调用showPdfFromSdCard()

public static  void showPdfFromSdCard(Context ctx) {
    File file = new File(Environment.getExternalStorageDirectory() + "/pdf/original.pdf");
    PackageManager packageManager = ctx.getPackageManager();
    Intent testIntent = new Intent(Intent.ACTION_VIEW);
    testIntent.setType("application/pdf");
    List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    Uri uri = Uri.fromFile(file);
    intent.setDataAndType(uri, "application/pdf");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    try {
        ctx.startActivity(intent);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(ctx,
                "No Application Available to View PDF",
                Toast.LENGTH_SHORT).show();
    }
}

4>>在onResume()中调用deletePdfFromSdcard()

public static void deletePdfFromSdcard(){
    File file = new    File(Environment.getExternalStorageDirectory()+"/pdf/original.pdf");
    boolean pdfDelete = file.delete();
}
qcuzuvrc

qcuzuvrc2#

您需要将internet权限添加到应用程序标记之外的清单文件中。

<uses-permission android:name="android.permission.INTERNET" />
46scxncf

46scxncf3#

经过2天的研究没有找到解决方案,所以我尝试首先从亚马逊网络服务下载PDF文件,并存储到SD卡,然后打开PDF文件在这里我的代码
注意:-此解决方案仅适用于从Amazon Web Service在Web视图中显示PDF。从其他Web服务尝试此代码:-

WebView webview=(WebView)findviewbyid(R.id.Webview);
   String MyURL= "this is your PDF URL";
   String url = "http://docs.google.com/gview?embedded=true&url=" + MyURL;
   Log.i(TAG, "Opening PDF: " + url);
   webView.getSettings().setJavaScriptEnabled(true); 
   webView.loadUrl(url);

----------------------------------------------------------------------------------------------------->对于Amazon Web Service,请尝试此代码

1>> Download PDF from Amazon WebService

public static void DownloadFile(String fileURL, File directory) {
    try {

        FileOutputStream f = new FileOutputStream(directory);
        URL u = new URL(fileURL);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.connect();

        InputStream in = c.getInputStream();

        byte[] buffer = new byte[1024];
        int len1 = 0;
        while ((len1 = in.read(buffer)) > 0) {
            f.write(buffer, 0, len1);
        }
        f.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

2>>从SD卡显示PDF

public static  void showPdfFromSdCard(Context ctx)
{
    File file = new File(Environment.getExternalStorageDirectory()+"/pdf/MyPdf.pdf");
    PackageManager packageManager = ctx.getPackageManager();
    Intent testIntent = new Intent(Intent.ACTION_VIEW);
    testIntent.setType("application/pdf");
    List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    Uri uri = Uri.fromFile(file);
    intent.setDataAndType(uri, "application/pdf");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    try {
         ctx.startActivity(intent);
    } 
    catch (ActivityNotFoundException e) {
        Toast.makeText(ctx, 
            "No Application Available to View PDF", 
            Toast.LENGTH_SHORT).show();
    }

下载PDF后,showPdfFromSdCard方法被调用。
后显示PDF您删除PDF文件从SD卡在这里代码删除PDF从SD卡

public static void deletePdfFromSdcard(){
    File file = new    File(Environment.getExternalStorageDirectory()+"/pdf/MyPdf.pdf");
    boolean pdfDelete = file.delete();

}
liwlm1x9

liwlm1x94#

I will do some modification in @Monika Moon code,

if you don't want to save the File in the device, the process explained above is too long as well as required FileProvider to open the pdf in external pdf viewer.

so for the better solution please follow the below steps.
Step 1:

请将此库添加到您的gradle文件。AndroidPdfViewer

Step 2:

add this in your XML view->

   <com.github.barteksc.pdfviewer.PDFView
    android:id="@+id/pdfView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />

第三步:
PDFView;
InputStream;
pdfView=findViewById(R.id.pdfView);

class DownloadFileAsync extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            if (mProgressDialog!=null)
            {
                Utils.cancelProgressDialog(mProgressDialog);
            }
            mProgressDialog = Utils.showProgressDialog(DocumentViewActivity.this);

            super.onPreExecute();
        }

        @Override
        protected String doInBackground(final String... aurl) {

            try {

                URL url = new URL(aurl[0]);
                URLConnection conexion = url.openConnection();
                conexion.connect();
                conexion.setReadTimeout(20000);
                conexion.setConnectTimeout(25000); // millis

                 inputStream = conexion.getInputStream();

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;

        }

        @Override
        protected void onPostExecute(String unused) {

            if (inputStream != null) {
                pdfView.fromStream(inputStream)
                        .defaultPage(0)
                        .password(null)
                        .scrollHandle(null)
                        .enableAntialiasing(true)
                        .scrollHandle(new DefaultScrollHandle(DocumentViewActivity.this))
                        .spacing(0)
                        .onLoad(new OnLoadCompleteListener() {
                            @Override
                            public void loadComplete(int nbPages) {
                                Utils.cancelProgressDialog(mProgressDialog);

                            }
                        })
                        .load();
            }else {
                Utils.cancelProgressDialog(mProgressDialog);
            }
        }
    }
@Override
protected void onDestroy() {
    if (inputStream!=null)
    {
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    super.onDestroy();
}

最终步骤:呼叫new DownloadFileAsync().execute(url);

nhjlsmyf

nhjlsmyf5#

我可能会迟到,但检查一次,网址是工作或不浏览器。
在加载到webView之前也尝试对其进行编码。
签名/签名URL也有效。

documentURL = URLEncoder.encode(documentURL);
if (isDocument) {
    finalUrl = "https://docs.google.com/viewerng/viewer?embedded=true&url=" + documentURL
    // below method is to open pdf with web view
    displayPdfWithWebView(finalUrl);
}

相关问题