【问题标题】:getting error on implementing pdf reader in android在android中实现pdf阅读器时出错
【发布时间】:2014-10-07 20:59:55
【问题描述】:

我是 android 新手,我正在尝试从服务器读取 pdf。我找到了不同的方法并尝试了其中的大部分。我尝试使用 webview,使用 google doc,但没有适合我的东西。而且我不喜欢使用其他第三方或插件。

我发现这段代码运行良好,但它是从资产文件夹中读取的。

    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_books_view);
CopyReadAssets();
}

    private void CopyReadAssets()
    {

        AssetManager assetManager = getAssets();

        InputStream in = null;
        OutputStream out = null;
        File file = new File(getFilesDir(), "test.pdf");
        try
        {
            in = assetManager.open("test.pdf");
            out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);

            copyFile(in, out);
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
        } catch (Exception e)
        {
            Log.e("tag", e.getMessage());
        }

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(
                Uri.parse("file://" + getFilesDir() + "/test.pdf"),
                "application/pdf");

        startActivity(intent);
    }


    private void copyFile(InputStream in, OutputStream out) throws IOException
    {
        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1)
        {
            out.write(buffer, 0, read);
        }
    }

我尝试将其修改为:

public class TestActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        //Call an AsycTask so you don't lock the main UI thread 
        new RequestTask().execute(); 

    }//end onCreate

    private class RequestTask extends AsyncTask<String, String, String> 
    {
        //Background task 
        protected String doInBackground(String... uri) 
        { 
            //Stuff you do in background goes here 
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response;
            String responseString = null;
            //-------
            String fileName="test";
            String fileExtension=".pdf";
            try 
            {
            URL url = new URL("my url");
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();
            String PATH = Environment.getExternalStorageDirectory() + "/mydownload/";
            File file = new File(PATH);
            file.mkdirs();
            File outputFile = new File(file, fileName+fileExtension);
            FileOutputStream fos = new FileOutputStream(outputFile);
            InputStream is = c.getInputStream();
            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);
            }
            responseString = fos.toString();
            fos.flush();
            fos.close();
            is.close();
            }
            catch (ClientProtocolException e) 
            {
                //TODO Handle problems..
            } 
            catch (IOException e) 
            {
                //TODO Handle problems..
            }

            return responseString;
        } 
        @Override
        protected void onPostExecute(String result) 
        {
            super.onPostExecute(result);
            //Do anything with response..
            //Stuff you do after the asych task is done

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(
                    Uri.parse(result),
                    "application/pdf");

            startActivity(intent);
        }
    } //end RequestTask class

但它给了我一个祝酒词: ((不支持的文档类型))

谁能帮帮我,我花了几乎一整天的时间试图找出问题所在。

【问题讨论】:

    标签: android eclipse pdf android-asynctask


    【解决方案1】:

    您必须使用 HttpClient 对您的 pdf 文件执行 GET 请求。这是一个返回字符串缓冲区的示例,您必须在读取远程文件后重新排列以创建 PDF

     class RequestTask extends AsyncTask<String, String, String>{
    
            @Override
            protected String doInBackground(String... uri) {
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response;
                String responseString = null;
                try {
                    response = httpclient.execute(new HttpGet(uri[0]));
                    StatusLine statusLine = response.getStatusLine();
                    if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        response.getEntity().writeTo(out);
                        out.close();
                        responseString = out.toString();
                    } else{
                        //Closes the connection.
                        response.getEntity().getContent().close();
                        throw new IOException(statusLine.getReasonPhrase());
                    }
                } catch (ClientProtocolException e) {
                    //TODO Handle problems..
                } catch (IOException e) {
                    //TODO Handle problems..
                }
                return responseString;
            }
    
            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
                //Do anything with response..
            }
        }
    

    你可以打电话

       new RequestTask().execute(url);
    

    【讨论】:

    • 你能解释一下吗,我应该把这个类放在我的代码中,还是应该创建一个新类?如果我用愚蠢的问题打扰你,我很抱歉,但这是我第一次使用 AsyncTask..谢谢
    • 或者我应该把它放在 CopyReadAssets 函数中吗?我还需要调用 startactivity(intent) 吗?我很困惑:(
    • 您必须创建一个新类并调用您要检索文档的执行方法
    • 我用新代码更新了我的问题,请你看看好吗?谢谢你..
    【解决方案2】:

    我使用此代码将整体更改为更简单的方式

            //setContentView(R.layout.activity_main);
            WebView webView=new WebView(GeneralHealthEducationArBooksViewActivity.this);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.getSettings().setPluginState(PluginState.ON);
    
            //---you need this to prevent the webview from
            // launching another browser when a url
            // redirection occurs---
            webView.setWebViewClient(new Callback());
    
            String pdfURL = "your link";
            webView.loadUrl(
    "http://docs.google.com/gview?embedded=true&url=" + pdfURL);
    
            setContentView(webView);
    

    xml文件

    <?xml version="1.0" encoding="utf-8"?>
    <WebView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    
    
    </WebView>
    

    终于显示pdf了:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-19
      • 1970-01-01
      • 1970-01-01
      • 2012-07-28
      • 2012-03-13
      • 1970-01-01
      • 1970-01-01
      • 2011-07-07
      相关资源
      最近更新 更多