October 22, 2024
Chicago 12, Melborne City, USA
pdf

Open a recent PDF created in Android


I’m using Android Studio to make a simple app to create some PDF files to store some data. I wanto just to make an intent for the generated PDF auto opens for the user.

Here’s just the canvas drawing sonme text and saving the PDF on Downloads. Working fine

canvas.drawText(text ,x ,y, paint);
        document.finishPage(page);
        File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        String fileName = "document.pdf";
        File file = new File(downloadsDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            document.writeTo(fos);
            document.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        showPdf();

Here’s my attempt to open the generated file

public void showPdf() {
        try {

            File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            String fileName = "document.pdf";
            File file = new File(downloadsDir, fileName);

            Uri path = Uri.fromFile(file);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(path, "application/pdf");
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

The app runs fine, no crashes. But nothing happens after the PDF generation.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video