Why compression doesn't work in iText7 from Android (Kotlin)?

36 views Asked by At

I'm trying to convert several images to PDF file using iText7 (version 8.0.3) from Android (Kotlin). It works great but even if I set compression the resulting file always has the same size. In other words, compression doesn't work. I don't understand why. My document contains only images.

    fun convertUrisToPdf() {
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                try {
                    val image = Image(ImageDataFactory.create(fileHolder.imagePathList[0]))
                    val pdfFilePath = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "${filename.value}.pdf")
                    val outputStream = FileOutputStream(pdfFilePath)
                    val pdfWriter = PdfWriter(outputStream, WriterProperties().setCompressionLevel(CompressionConstants.BEST_COMPRESSION))
                    val pdfDocument = PdfDocument(pdfWriter)
                    val eventHandler = PageRotationEventHandler()
                    pdfDocument.addEventHandler(PdfDocumentEvent.START_PAGE, eventHandler)
                    eventHandler.setRotation(orientation.value)
                    val document = Document(pdfDocument, getPageSize(image))
                    setMarginsToTheDocument(document)
                    createPages(document, pdfDocument)
                    document.close()
                } catch (e: Exception) {
                    Log.d(TAG, "convertUrisToPdf: ${e.message}")
                }
            }
        }
    }
private fun createPages(document: Document, pdfDocument: PdfDocument) {
        fileHolder.imagePathList.forEach { uri ->
            val image = Image(ImageDataFactory.create(uri))
            setImageSize(image)
            pdfDocument.addNewPage(getPageSize(image))
            document.add(image)
        }
    }

Here is my code. I tried to set compression directly to pdfWriter (pdfWriter.compressionLevel = 9, for example). The value applyed, I see it when I add logs. But file size is the same.

0

There are 0 answers