0
public void savePDF(View view) {
        //create document object
        Document doc = new Document();
        //output file path
        String outpath= Environment.getExternalStorageDirectory()+"/mypdf.pdf";
        try {
            //create pdf writer instance
            PdfWriter.getInstance(doc, new FileOutputStream(outpath));
            //open the document for writing
            doc.open();
            //add paragraph to the document
            doc.add(new Paragraph("bob"));
            //close the document
            doc.close();

            Toast.makeText(this, "Worked", Toast.LENGTH_SHORT).show();

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

I am using the above code to create a PDF file and store it on the external storage of the device. Below is a snippet of my manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.mobileappdevelopment">
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />

Upon pressing the button (which runs the savePDF function), nothing happens. No file is saved, and the toast isn't shown either. Am I doing something wrong here?

Also added the itext dependency...

    implementation 'com.itextpdf:itextg:5.5.10'

Akshat S
  • 1
  • 3
  • 1
    "nothing happens" – Are you sure about that? Have you checked your logs for those stack trace prints in the `catch` blocks? – Mike M. Apr 28 '19 at 11:32
  • @MikeM. Thanks for your reply. Yes you are correct, the logcat shows the following error -> "java.io.FileNotFoundException: /storage/emulated/0/mypdf.pdf (Permission denied)". I realise you have to implement a runtime permission if API > 23 (or marshmallow). However, I'm unsure how to do so. Any help would be appreciated. – Akshat S Apr 28 '19 at 11:51
  • https://stackoverflow.com/q/33162152 – Mike M. Apr 28 '19 at 11:59
  • the developer's site explains it well https://developer.android.com/training/permissions/requesting – Kaveri Apr 28 '19 at 12:01

1 Answers1

0

WRITE_EXTERNAL_STORAGE Starting in API level 19, this permission is not required to read/write files in your application-specific directories returned by Context.getExternalFilesDir(String) and Context.getExternalCacheDir().

https://developer.android.com/reference/android/Manifest.permission.html#WRITE_EXTERNAL_STORAGE

Inguss
  • 1