Search code examples
androidandroid-studiokotlinitext7

How can I create pdf using Storage Access Storage in Android studio using kotlin?


I am a novice Android/Kotlin programmer. I am doing a project to generate pdf in Android. I have tried making simple pdf documents using itextpdf:itext7 in internal app-specific location but doing so doesn't allow user to view files. So I have to create using Storage Access Framework. I created text files using SAF but pdf files seems dead-end to me

I searched on available resources but could not get any materials/or resources on this. My attempts to give it a try also failed. The app simply crashed/closed down.

Could anyone show me how it is done correctly?

Thank you.

class MainActivity : AppCompatActivity() {

    lateinit var binding: ActivityMainBinding

    var saveHandle = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
        resultData: ActivityResult ->
        val uri = resultData.data?.data
        if (resultData.resultCode == Activity.RESULT_OK){
            if (uri != null){
                WritetoPdf(uri)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //setContentView(R.layout.activity_main)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.btnCreate.setOnClickListener {
            //CreatePdf()
            val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
                type = "text/.pdf"
                addCategory(Intent.CATEGORY_OPENABLE)
            }
            saveHandle.launch(intent)
        }
    }

    fun WritetoPdf(uri: Uri) {
        var writeStream: ParcelFileDescriptor? = contentResolver.openFileDescriptor(uri, "w")
        var pdfFile = File(uri.toString())
        val pdf = PdfDocument(PdfWriter(pdfFile.toString()))
        val document = Document(pdf)
        val line = "Hello! Welcome to iTextPdf"
        document.add(Paragraph(line))
        document.close()
    }
}

Solution

  • Replace:

        var writeStream: ParcelFileDescriptor? = contentResolver.openFileDescriptor(uri, "w")
        var pdfFile = File(uri.toString())
        val pdf = PdfDocument(PdfWriter(pdfFile.toString()))
    

    with:

        var writeStream = contentResolver.openOutputStream(uri, "w")
        val pdf = PdfDocument(PdfWriter(writeStream))
    

    Or, write the PDF to a File that you control, then copy the content of the File to the location chosen by the user via SAF.