Add multiple images into a single pdf file with iText using java

前端 未结 2 897
予麋鹿
予麋鹿 2020-11-30 15:17

I have the following code but this code add only the last image into pdf.

    try {
        filePath = (filePath != null && filePath.endsWith(\".pdf\         


        
2条回答
  •  温柔的废话
    2020-11-30 16:03

    Android has the feature "PdfDocument" to achieve this,

    class Main2Activity : AppCompatActivity() {
    
    private var imgFiles: Array? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
    
        imgFiles= arrayOfNulls(2)
    
        imgFiles!![0] = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() + "/doc1.png")
        imgFiles!![1] = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() + "/doc3.png")
    
    
    
        val file = getOutputFile(File(Environment.getExternalStorageDirectory().absolutePath)
                , "/output.pdf")
    
        val fOut = FileOutputStream(file)
        val document = PdfDocument()
    
        var i = 0
        imgFiles?.forEach {
            i++
            val bitmap = BitmapFactory.decodeFile(it?.path)
            val pageInfo = PdfDocument.PageInfo.Builder(bitmap.width, bitmap.height, i).create()
            val page = document.startPage(pageInfo)
            val canvas = page?.canvas
            val paint = Paint()
            canvas?.drawPaint(paint)
            paint.color = Color.BLUE;
            canvas?.drawBitmap(bitmap, 0f, 0f, null)
            document.finishPage(page)
            bitmap.recycle()
        }
        document.writeTo(fOut)
        document.close()        
    
    }
    
    private fun getOutputFile(path: File, fileName: String): File? {
        if (!path.exists()) {
            path.mkdirs()
        }
        val file = File(path, fileName)
        try {
            if (file.exists()) {
                file.delete()
            }
            file.createNewFile()
    
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return file
    }
    

    }

    finally enable the storage permission in manifest, this should works

提交回复
热议问题