Как открыть PDF-файл, сохраненный в папке res / raw или assets? - PullRequest
23 голосов
/ 27 июня 2011

Я собираюсь показать 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);

Есть идеи или предложения?

Заранее спасибо

Ответы [ 6 ]

30 голосов
/ 28 декабря 2012

Вы не можете открыть файл 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. Спасибо

23 голосов
/ 27 июня 2011

Вы сможете отобразить его с raw/ или assets/, если в вашем приложении действительно реализована программа чтения PDF. Поскольку вы хотите, чтобы он отображался в отдельном приложении (например, Adobe Reader), я предлагаю сделать следующее:

  1. Сохраните файл PDF в каталоге assets/.
  2. Когда пользователь хочет его просмотреть, скопируйте его куда-нибудь public . Посмотрите на openFileOutput или getExternalFilesDir.
  3. Запустите Intent так же, как вы делаете сейчас, за исключением использования getAbsolutePath() во вновь созданном файле для данных намерения.

Помните, что у пользователя может не быть приложения для чтения PDF. В этом случае полезно перехватить ActivityNotFoundException и показать соответствующее сообщение.

1 голос
/ 27 июня 2011

Я использовал следующий формат для открытия необработанных ресурсов из моего собственного приложения. Я не проверял, может ли другое приложение открыть ваш необработанный ресурс.

Uri path = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.myPdfName);
0 голосов
/ 11 февраля 2018

У меня были различные проблемы с ответами, поэтому я собрал что-то, что работает.

ПЛАН

<?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);
    }
}
0 голосов
/ 08 ноября 2014

моим приложениям нужно открывать содержимое PDF-файла в необработанных данных во внешнем приложении ... im write:

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 голосов
/ 27 июня 2011

Ваше pdf-намерение кажется хорошим, но вы должны попробовать это, чтобы получить Uri файла в необработанной папке:

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

(Источник)

...