2011-06-27 24 views
20

Tôi sẽ hiển thị bản pdf trong đơn đăng ký của mình và bản pdf phải đi kèm với ứng dụng.Làm thế nào để mở một pdf được lưu trữ trong thư mục res/raw hoặc asset?

Cách tốt nhất để làm điều này là gì?

Tôi đã đọc rằng có thể làm điều này bằng cách thêm tệp pdf vào thư mục res/raw và đọc từ đó, nhưng tôi gặp lỗi dự án khi tôi đặt tệp pdf ở đó.

Vì vậy, tôi đã cố gắng đưa tệp pdf vào thư mục nội dung của dự án và không có lỗi.

Đây là cách tôi đã cố gắng để hiển thị pdf:

File pdfFile = new File("res/raw/file.pdf"); 
Uri path = Uri.fromFile(pdfFile); 
Intent intent = new Intent(Intent.ACTION_VIEW); 
intent.setDataAndType(path, "application/pdf"); 
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

Bất kỳ ý tưởng hoặc đề nghị?

Cảm ơn trước

Trả lời

20

Bạn sẽ có thể hiển thị nó từ raw/ hoặc assets/ nếu ứng dụng của bạn thực sự thực hiện một trình đọc PDF. Vì bạn muốn nó được hiển thị trong một ứng dụng riêng biệt (như Adobe Reader), tôi đề nghị thực hiện như sau:

  1. Lưu trữ tệp PDF trong thư mục assets/.
  2. Khi người dùng muốn xem, hãy sao chép nó ở đâu đó công khai. Xem xét openFileOutput hoặc getExternalFilesDir.
  3. Khởi chạy Intent giống như bạn đang làm bây giờ, ngoại trừ sử dụng getAbsolutePath() trên tệp mới được tạo cho dữ liệu của mục đích.

Lưu ý rằng người dùng có thể không có ứng dụng đọc PDF. Trong trường hợp này, rất hữu ích khi bắt được số ActivityNotFoundException và hiển thị thông báo thích hợp.

+5

Bạn có thể sử dụng [queryIntentActivities của PackageManager] (phương pháp http://developer.android.com/reference/android/content/pm/PackageManager.html#queryIntentActivities (android.content.Intent,% 20int)) để kiểm tra xem có hoạt động nào không có thể đáp ứng với một Mục đích đã cho. Xem [tại đây] (http://code.google.com/p/shelves/source/browse/trunk/Shelves/src/org/curiouscreature/android/shelves/scan/ScanIntent.java#) để biết ví dụ –

+0

@David Tôi biết tôi đã quên thứ gì đó! Cảm ơn bạn đã thêm điều đó. – Felix

+0

:) Tôi có cảm giác câu trả lời của bạn là giải pháp tốt nhất trừ khi các ứng dụng bên ngoài có thể truy cập tài nguyên gói. –

0

Bạn pdf ý định có vẻ tốt nhưng bạn nên thử loại này để có được những Uri của tập tin trong thư mục thô:

Uri path = Uri.parse("android.resource://<you package>/raw/<you file.pdf>"); 

(Source)

1

Tôi đã sử dụng sau định dạng để mở tài nguyên thô từ trong ứng dụng của riêng tôi. Tôi chưa thử nghiệm xem một ứng dụng khác có thể mở tài nguyên thô của bạn hay không.

Uri path = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.myPdfName); 
+1

hmm, tôi có adobe reader cài đặt trên điện thoại của tôi, nhưng tôi nhận được một ActivitynotFoundException. Bất kỳ ý tưởng? – Ikky

+0

Không thể kết hợp URI hoặc loại mime (hoặc cả hai), tiếc là tôi không biết ứng dụng Reader khớp với nhau như thế nào. Bạn có thể phải thử và không chỉ định loại mime, và thử mở một cái gì đó từ thẻ SD vì nó có thể là nó sẽ không mở ra từ tài nguyên thô của bạn cả. –

25

Bạn không thể mở các tập tin pdf trực tiếp từ tài sản folder.You đầu tiên phải viết các tập tin vào thẻ sd từ thư mục tài sản và sau đó đọc nó từ mã sd card.The là như sau: -

 @Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    File fileBrochure = new File(Environment.getExternalStorageDirectory() + "/" + "abc.pdf"); 
    if (!fileBrochure.exists()) 
    { 
     CopyAssetsbrochure(); 
    } 

    /** PDF reader code */ 
    File file = new File(Environment.getExternalStorageDirectory() + "/" + "abc.pdf");  

    Intent intent = new Intent(Intent.ACTION_VIEW); 
    intent.setDataAndType(Uri.fromFile(file),"application/pdf"); 
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    try 
    { 
     getApplicationContext().startActivity(intent); 
    } 
    catch (ActivityNotFoundException e) 
    { 
     Toast.makeText(SecondActivity.this, "NO Pdf Viewer", Toast.LENGTH_SHORT).show(); 
    } 
} 

//method to write the PDFs file to sd card 
    private void CopyAssetsbrochure() { 
     AssetManager assetManager = getAssets(); 
     String[] files = null; 
     try 
     { 
      files = assetManager.list(""); 
     } 
     catch (IOException e) 
     { 
      Log.e("tag", e.getMessage()); 
     } 
     for(int i=0; i<files.length; i++) 
     { 
      String fStr = files[i]; 
      if(fStr.equalsIgnoreCase("abc.pdf")) 
      { 
       InputStream in = null; 
       OutputStream out = null; 
       try 
       { 
        in = assetManager.open(files[i]); 
        out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + files[i]); 
        copyFile(in, out); 
        in.close(); 
        in = null; 
        out.flush(); 
        out.close(); 
        out = null; 
        break; 
       } 
       catch(Exception e) 
       { 
        Log.e("tag", e.getMessage()); 
       } 
      } 
     } 
    } 

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); 
     } 
    } 

Thats all..Enjoy !! và xin vui lòng không quên để cung cấp cho + 1.Thanks

+7

Như Lint trong phiên bản mới đề xuất .. Không mã hóa cứng '/ sdcard /'; sử dụng 'Environment.getExternalStorageDirectory(). getPath()' thay vì –

+1

Environment.getExternalStorageDirectory(). getPath() + "/" để làm ví dụ này làm việc – max4ever

+0

làm thế nào để xóa pdf sau khi người dùng đọc nó? tôi đã thử sử dụng startActivityForResult nhưng không có may mắn – max4ever

-2

ứng dụng của tôi cần phải mở một nội dung tập tin pdf trong các dữ liệu thô trên ứng dụng bên ngoài ... im viết:

public class MainActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Button button = (Button) findViewById(R.id.OpenPdfButton); 
    button.setOnClickListener(new View.OnClickListener() { 
     InputStream is = getResources().openRawResource(R.raw.filepdf); 

     @Override 
     public void onClick(View v) { 
      startpdf(); 
     } 
      private void startpdf() { 
      // TODO Auto-generated method stub 

      File file = new File("R.id.filepdf"); 

      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) { 

       } 
      } 
     } 


    }); 
} 
} 
0

Tôi có vấn đề khác nhau với câu trả lời, vì vậy tôi đã kéo một thứ gì đó hoạt động.

LAYOUT

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


    <ImageView 
     android:id="@+id/image_pdf" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_above="@+id/btn_okay" 
     android:layout_margin="5dp"/> 

    <Button 
     android:id="@+id/btn_okay" 
     android:layout_width="80dp" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" 
     android:layout_alignParentRight="true" 
     android:layout_margin="10dp" 
     android:text="@string/ok"/> 

</RelativeLayout> 

/** 
* Render a page of a PDF into ImageView 
* @param targetView 
* @throws IOException 
*/ 
private void openPDF(ImageView targetView) throws IOException { 

    //open file in assets 

    ParcelFileDescriptor fileDescriptor; 

    String FILENAME = "your.pdf"; 

    // Create file object to read and write on 
    File file = new File(getActivity().getCacheDir(), FILENAME); 
    if (!file.exists()) { 
     AssetManager assetManager = getActivity().getAssets(); 
     FileUtils.copyAsset(assetManager, FILENAME, file.getAbsolutePath()); 
    } 

    fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); 

    PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor); 

    //Display page 0 
    PdfRenderer.Page rendererPage = pdfRenderer.openPage(0); 
    int rendererPageWidth = rendererPage.getWidth(); 
    int rendererPageHeight = rendererPage.getHeight(); 
    Bitmap bitmap = Bitmap.createBitmap(
      rendererPageWidth, 
      rendererPageHeight, 
      Bitmap.Config.ARGB_8888); 
    rendererPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY); 

    targetView.setImageBitmap(bitmap); 
    rendererPage.close(); 
    pdfRenderer.close(); 
} 


public static boolean copyAsset(AssetManager assetManager, String fromAssetPath, String toPath) { 
    InputStream in = null; 
    OutputStream out = null; 
    try { 
     in = assetManager.open(fromAssetPath); 
     new File(toPath).createNewFile(); 
     out = new FileOutputStream(toPath); 
     copyFile(in, out); 
     in.close(); 
     in = null; 
     out.flush(); 
     out.close(); 
     out = null; 
     return true; 
    } catch(Exception e) { 
     e.printStackTrace(); 
     return false; 
    } 
} 

public static 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); 
    } 
} 
Các vấn đề liên quan