2014-10-26 70 views
-1

即時製作一個應用程序包含一些pdf文件,但我不知道我可以如何使用該應用程序 1-我應該在資源中複製我的PDF文件? (哪個文件夾?) 2-需要什麼代碼才能打開它? (哪些代碼需要在onClick方法中編寫?) 3-此過程有哪些類和方法是有用的?在應用程序中打開pdf文件

離開這個下面的代碼(它們是身體誤差忽略)

public void onCreate(Bundle savedInstanceState) { 
    setContentView(R.layout.main);} 

回答

0

如果你想從網頁視圖中打開PDF,你可以使用下面的代碼:

public class ActivityName extends Activity { 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    WebView mWebView=new WebView(MyPdfViewActivity.this); 
    mWebView.getSettings().setJavaScriptEnabled(true); 
    mWebView.getSettings().setPluginsEnabled(true); 
    mWebView.loadUrl("https://docs.google.com/gview?embedded=true&url="+LinkTo); 
    setContentView(mWebView); 
    } 
} 

如果您希望在本地打開PDF,您可以將其放置在res/raw文件夾或資產文件夾中(在以下示例中使用資產文件夾)。然後,你需要將文件在本地使用下面的代碼:

private void copyAssets() { 
    AssetManager assetManager = getAssets(); 
    String[] files = null; 
    try { 
     files = assetManager.list(""); 
    } catch (IOException e) { 
     Log.e("tag", "Failed to get asset file list.", e); 
    } 
    for(String filename : files) { 
     InputStream in = null; 
     OutputStream out = null; 
     try { 
      in = assetManager.open(filename); 
      File outFile = new File(getExternalFilesDir(null), filename); 
      out = new FileOutputStream(outFile); 
      copyFile(in, out); 
      in.close(); 
      in = null; 
      out.flush(); 
      out.close(); 
      out = null; 
     } catch(IOException e) { 
      Log.e("tag", "Failed to copy asset file: " + filename, e); 
     }  
    } 
} 
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); 
    } 
} 

然後你可以用下面的代碼來訪問PDF,再次假設用戶已經安裝了PDF瀏覽器:

public class OpenPdf extends Activity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     Button button = (Button) findViewById(R.id.OpenPdfButton); 
     button.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       File file = new File("/sdcard/example.pdf"); 

       if (file.exists()) { 
        Uri path = Uri.fromFile(file); 
        Intent intent = new Intent(Intent.ACTION_VIEW); 
        intent.setDataAndType(path, "application/pdf"); 
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

        try { 
         startActivity(intent); 
        } 
        catch (ActivityNotFoundException e) { 
         Toast.makeText(OpenPdf.this, 
          "No Application Available to View PDF", 
          Toast.LENGTH_SHORT).show(); 
        } 
       } 
      } 
     }); 
    } 
} 

如果你想從你的應用程序打開它,你可以嘗試this

相關問題