簡體   English   中英

如何打開存儲在res / raw或assets文件夾中的pdf?

[英]How to open a pdf stored either in res/raw or assets folder?

我將在我的應用程序中顯示pdf,並且pdf必須與應用程序捆綁在一起。

有什么好辦法呢?

我已經讀過可以通過將pdf文件添加到res / raw文件夾並從那里讀取它來實現這一點,但是當我將pdf文件放在那里時我得到了項目錯誤。

所以我試着把pdf文件放在項目的資產文件夾中,它沒有給出任何錯誤。

這是我試圖顯示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);

任何想法或建議?

提前致謝

您無法直接assets文件夾打開pdf文件。您首先必須將文件從assets文件夾寫入SD卡,然后從SD卡讀取它。代碼如下: -

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

多數民眾贊成......享受! 請不要忘記給予1.謝謝

如果您的應用程序實際實現了PDF閱讀器,您將能夠從raw/assets/顯示它。 由於您希望它顯示在單獨的應用程序(例如Adobe Reader)中,我建議您執行以下操作:

  1. 將PDF文件存儲在assets/目錄中。
  2. 當用戶想要查看它時,將其復制到公共場所 查看openFileOutputgetExternalFilesDir
  3. 就像你現在一樣啟動Intent ,除了在新創建的文件中使用getAbsolutePath()作為intent的數據。

請注意,用戶可能沒有PDF閱讀應用程序。 在這種情況下,捕獲ActivityNotFoundException並顯示適當的消息很有用。

我使用以下格式從我自己的應用程序中打開原始資源。 我還沒有測試另一個應用程序是否可以打開您的原始資源。

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

你的pdf意圖似乎不錯,但你應該嘗試這個來獲取原始文件夾中的文件的Uri:

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

(資源)

我的答案有各種各樣的問題,所以我把一些有效的東西放在一起。

布局

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

我的應用程序需要在外部應用程序的原始數據中打開pdf文件內容...我寫道:

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

                }
            }
        }


    });
}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM