kotlinandroid-jetpack-composeitext7

How to add a custom Font to Itext7 library in jetpack Compose


I want to build android app that generates pdf file, but I want to add custom font that's suitable with app purpose.

I tried to use string path "src/main/...etc" but it didn't work

Reading IText7 documentation was really painful, any solution?


Solution

  • How I use custom for for my PDF generation is as below which you can find useful.

    There are two ways

    1. You can put the font in the res/font/.. folder and use it.
    2. You can put the font in assets/.. and use it.

    The problem with the first approach is that when you apply Proguard it will not work as expected.

    Working Approach

    Don't forget to add a font in asset folder

    private fun GeneratePDF() {
            try {
                val path =
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                        .toString() + "/MyPDF"
    
                val file = File(path, "my_file.pdf")
    
                val pdfWriter = PdfWriter(file)
                val pdfDocument = PdfDocument(pdfWriter)
                val document = Document(pdfDocument)
    
                val font = PdfFontFactory.createFont(
                    "assets/regular.ttf",
                    PdfEncodings.IDENTITY_H
                )
                document.setFont(font)
                pdfDocument.defaultPageSize = PageSize.A4
                pdfDocument.addEventHandler(PdfDocumentEvent.END_PAGE, TextFooterEventHandler(document))
                
                val secondLine = Paragraph(
                    "${
                        SimpleDateFormat(
                            "dd-MM-yyyy hh:mm a",
                            Locale.getDefault()
                        ).format(Date())
                    } \n Created By : My"
                ).setBold().setFontSize(12f).setItalic()
                document.add(secondLine)
    
                val line = SolidLine(1f)
                val linebreak = LineSeparator(line)
                document.add(linebreak)
                
                document.close()
               
            } catch (e: java.lang.Exception) {
                e.printStackTrace()
            }
        }
    

    Hope it works for you. Happy Compose :)