DEV Community

Cover image for How to write and save a PDF file in Android using Intents
Wami Ikechukwu
Wami Ikechukwu

Posted on

How to write and save a PDF file in Android using Intents

I remembered when I wanted a user to save a pdf file and programmatically save “a decoded base64” data to it. It was quite challenging as there were limited documentations on the topic and other articles and blog posts I came across happened to be a bit outdated.

What is Base64? - Read about it here

In the code snippet below. I used implicit intent to get the file manager to show list of directories, the user can save the file and then OutputStream to write to the file in that directory.

class SaveDocumentFragment : Fragment(R.layout.fragment_save_document) {

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

// Set your button
view.findViewById<Button>(R.id.button)?.setOnClickListener {


Toast.makeText(requireContext(), "Please save the pdf", Toast.LENGTH_SHORT).show()

      //        Save the pdf using an intent
        val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
            addCategory(Intent.CATEGORY_OPENABLE)
            type = "application/pdf"
            putExtra(Intent.EXTRA_TITLE, "recovery.pdf")

        }
        startActivityForResult(intent, CREATE_PDF_FILE)      
        }    }
}


// Call the `onActivityResult` to get the directory the user saved the file

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == Activity.RESULT_OK && requestCode == CREATE_PDF_FILE) {

            var pdfPath = data?.data

            val outPutStream: OutputStream? = data?.data?.let { context?.contentResolver?.openOutputStream(it) }

// generatedPDFAsBase64 should be the data in the form of a Base64 you want to write to the file.

outPutStream?.write(Base64.decode(generatedPDFAsBase64, Base64.NO_WRAP))
            outPutStream?.flush()
            outPutStream?.close()
        }

    }

companion object {
        private const val CREATE_PDF_FILE = 190
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)