Convert Word to PDF in Android Studio Kotlin

I’m doing an Android Kotlin project which will auto-generate certificates when we enter some details in the EditTexts. I have word files (.docx) in my assets folder which has some variables which will be replaced by the data entered in the EditTexts. I’m getting proper output word file, and it downloads properly. Now I need to convert that converted word to pdf in-app itself, and it must be downloaded in my phone instead of the word file.

I used these libraries for reading & editing word file –

implementation 'org.apache.poi:poi:5.2.4'
implementation 'org.apache.poi:poi-ooxml:5.2.4'

This the function that edits the original word file and downloads the new word file :

private fun editWordFile(context: Context, name: String, date: String assetsName: String) {
    
    // assetsName = "joinai.docx" This is written somewhere on the top where the function is called   

    try {
        val assetManager = applicationContext.assets
        val wordFileName = assetsName.toString()

        val inputStream: InputStream = assetManager.open(wordFileName)
        val outputDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)

        val outputName = "${name}_${date}"


        try {

            // Read Word file
            val document = XWPFDocument(inputStream)

            // Replace placeholders/variables with EditText data
            for (paragraph: XWPFParagraph in document.paragraphs) {
                for (run: XWPFRun in paragraph.runs) {
                    val text = run.text()
                    println("Text: $text, Date: $date")

                    if (text.contains("XDATEX")) {
                        run.setText(text.replace("XDATEX", date), 0)
                    }
                    if (text.contains("XLAMAX")) {
                        run.setText(text.replace("XLAMAX", name), 0)
                    }
                 
                }
            }


            // Save modified Word file
            val outputFile = File(outputDir, "${outputName}.docx")
            val fos = FileOutputStream(outputFile)
            document.write(fos)
            fos.close()

            Toast.makeText(this, "File $outputName downloaded.", Toast.LENGTH_SHORT).show()

            // Convert Word to PDF
            // You may implement PDF conversion logic here

        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            inputStream.close()
        }
    }
    catch (e: Exception) {
        e.printStackTrace()
        Toast.makeText(context, "Error occurred: ${e.message}! Contact developer", Toast.LENGTH_SHORT).show()
    }

}

I need to convert this resulting .docx to .pdf, which has good quality, and is most probably free of cost (if you are recommending any service APIs).

New contributor

Rushi Mayur is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

I think the best approach to this is using Apache POI with iText, which is an open-source pdf library. See modified code below:

// Add these dependencies to your build.gradle
// implementation 'com.itextpdf:itextpdf:5.5.13.3'
// implementation 'org.apache.poi:poi:5.2.4'
// implementation 'org.apache.poi:poi-ooxml:5.2.4'
// implementation 'org.apache.xmlgraphics:fop:2.8'

import com.itextpdf.text.Document
import com.itextpdf.text.Paragraph
import com.itextpdf.text.pdf.PdfWriter
import org.apache.poi.xwpf.usermodel.XWPFDocument
import java.io.*
import android.os.Environment
import android.content.Context
import android.widget.Toast

private fun editWordFileAndConvertToPDF(context: Context, name: String, date: String, assetsName: String) {
    try {
        val assetManager = context.applicationContext.assets
        val wordFileName = assetsName
        val inputStream: InputStream = assetManager.open(wordFileName)
        val outputDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
        val outputName = "${name}_${date}"

        try {
            // Read and modify Word file
            val document = XWPFDocument(inputStream)
            
            // Replace placeholders/variables with EditText data
            for (paragraph in document.paragraphs) {
                for (run in paragraph.runs) {
                    val text = run.text()
                    when {
                        text.contains("XDATEX") -> run.setText(text.replace("XDATEX", date), 0)
                        text.contains("XLAMAX") -> run.setText(text.replace("XLAMAX", name), 0)
                    }
                }
            }

            // First save the modified Word file temporarily
            val tempWordFile = File(context.cacheDir, "temp_${outputName}.docx")
            FileOutputStream(tempWordFile).use { fos ->
                document.write(fos)
            }

            // Convert to PDF
            val pdfFile = File(outputDir, "${outputName}.pdf")
            convertWordToPDF(tempWordFile, pdfFile)

            // Delete temporary Word file
            tempWordFile.delete()

            Toast.makeText(context, "PDF file saved: ${pdfFile.name}", Toast.LENGTH_SHORT).show()

        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(context, "Error during conversion: ${e.message}", Toast.LENGTH_SHORT).show()
        } finally {
            inputStream.close()
        }
    } catch (e: Exception) {
        e.printStackTrace()
        Toast.makeText(context, "Error occurred: ${e.message}! Contact developer", Toast.LENGTH_SHORT).show()
    }
}

private fun convertWordToPDF(wordFile: File, pdfFile: File) {
    try {
        val document = Document()
        PdfWriter.getInstance(document, FileOutputStream(pdfFile))
        document.open()

        // Read the Word document
        val docxDocument = XWPFDocument(FileInputStream(wordFile))
        
        // Convert paragraphs
        for (paragraph in docxDocument.paragraphs) {
            val text = paragraph.text
            if (text.isNotEmpty()) {
                document.add(Paragraph(text))
            }
        }

        // Convert tables
        for (table in docxDocument.tables) {
            for (row in table.rows) {
                val rowText = row.tableCells.joinToString(" | ") { it.text }
                document.add(Paragraph(rowText))
            }
        }

        document.close()
        docxDocument.close()
    } catch (e: Exception) {
        throw e
    }
}

The above solution uses iText library for pdf conversion; creates a temporary Word file in the cache directory; converts the Word content to pdf while maintaining text formatting; automatically deletes the temporary Word file; and saves only the final pdf to the Downloads folder.

To implement this:

Add the iText dependency to your build.gradle:

implementation 'com.itextpdf:itextpdf:5.5.13.3'

Replace your existing editWordFile function with the new editWordFileAndConvertToPDF function from the artifact.

Note that this basic implementation handles text and tables. If you need more advanced formatting (like images, complex layouts, or specific fonts), you might need to add additional conversion logic in the convertWordToPDF function.

Some limitations to be aware of:

  • Some complex formatting might not transfer perfectly
  • Images will need additional handling if present in your documents
  • Very large documents might need optimisation

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

Convert Word to PDF in Android Studio Kotlin

I’m doing an Android Kotlin project which will auto-generate certificates when we enter some details in the EditTexts. I have word files (.docx) in my assets folder which has some variables which will be replaced by the data entered in the EditTexts. I’m getting proper output word file, and it downloads properly. Now I need to convert that converted word to pdf in-app itself, and it must be downloaded in my phone instead of the word file.

I used these libraries for reading & editing word file –

implementation 'org.apache.poi:poi:5.2.4'
implementation 'org.apache.poi:poi-ooxml:5.2.4'

This the function that edits the original word file and downloads the new word file :

private fun editWordFile(context: Context, name: String, date: String assetsName: String) {
    
    // assetsName = "joinai.docx" This is written somewhere on the top where the function is called   

    try {
        val assetManager = applicationContext.assets
        val wordFileName = assetsName.toString()

        val inputStream: InputStream = assetManager.open(wordFileName)
        val outputDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)

        val outputName = "${name}_${date}"


        try {

            // Read Word file
            val document = XWPFDocument(inputStream)

            // Replace placeholders/variables with EditText data
            for (paragraph: XWPFParagraph in document.paragraphs) {
                for (run: XWPFRun in paragraph.runs) {
                    val text = run.text()
                    println("Text: $text, Date: $date")

                    if (text.contains("XDATEX")) {
                        run.setText(text.replace("XDATEX", date), 0)
                    }
                    if (text.contains("XLAMAX")) {
                        run.setText(text.replace("XLAMAX", name), 0)
                    }
                 
                }
            }


            // Save modified Word file
            val outputFile = File(outputDir, "${outputName}.docx")
            val fos = FileOutputStream(outputFile)
            document.write(fos)
            fos.close()

            Toast.makeText(this, "File $outputName downloaded.", Toast.LENGTH_SHORT).show()

            // Convert Word to PDF
            // You may implement PDF conversion logic here

        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            inputStream.close()
        }
    }
    catch (e: Exception) {
        e.printStackTrace()
        Toast.makeText(context, "Error occurred: ${e.message}! Contact developer", Toast.LENGTH_SHORT).show()
    }

}

I need to convert this resulting .docx to .pdf, which has good quality, and is most probably free of cost (if you are recommending any service APIs).

New contributor

Rushi Mayur is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

I think the best approach to this is using Apache POI with iText, which is an open-source pdf library. See modified code below:

// Add these dependencies to your build.gradle
// implementation 'com.itextpdf:itextpdf:5.5.13.3'
// implementation 'org.apache.poi:poi:5.2.4'
// implementation 'org.apache.poi:poi-ooxml:5.2.4'
// implementation 'org.apache.xmlgraphics:fop:2.8'

import com.itextpdf.text.Document
import com.itextpdf.text.Paragraph
import com.itextpdf.text.pdf.PdfWriter
import org.apache.poi.xwpf.usermodel.XWPFDocument
import java.io.*
import android.os.Environment
import android.content.Context
import android.widget.Toast

private fun editWordFileAndConvertToPDF(context: Context, name: String, date: String, assetsName: String) {
    try {
        val assetManager = context.applicationContext.assets
        val wordFileName = assetsName
        val inputStream: InputStream = assetManager.open(wordFileName)
        val outputDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
        val outputName = "${name}_${date}"

        try {
            // Read and modify Word file
            val document = XWPFDocument(inputStream)
            
            // Replace placeholders/variables with EditText data
            for (paragraph in document.paragraphs) {
                for (run in paragraph.runs) {
                    val text = run.text()
                    when {
                        text.contains("XDATEX") -> run.setText(text.replace("XDATEX", date), 0)
                        text.contains("XLAMAX") -> run.setText(text.replace("XLAMAX", name), 0)
                    }
                }
            }

            // First save the modified Word file temporarily
            val tempWordFile = File(context.cacheDir, "temp_${outputName}.docx")
            FileOutputStream(tempWordFile).use { fos ->
                document.write(fos)
            }

            // Convert to PDF
            val pdfFile = File(outputDir, "${outputName}.pdf")
            convertWordToPDF(tempWordFile, pdfFile)

            // Delete temporary Word file
            tempWordFile.delete()

            Toast.makeText(context, "PDF file saved: ${pdfFile.name}", Toast.LENGTH_SHORT).show()

        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(context, "Error during conversion: ${e.message}", Toast.LENGTH_SHORT).show()
        } finally {
            inputStream.close()
        }
    } catch (e: Exception) {
        e.printStackTrace()
        Toast.makeText(context, "Error occurred: ${e.message}! Contact developer", Toast.LENGTH_SHORT).show()
    }
}

private fun convertWordToPDF(wordFile: File, pdfFile: File) {
    try {
        val document = Document()
        PdfWriter.getInstance(document, FileOutputStream(pdfFile))
        document.open()

        // Read the Word document
        val docxDocument = XWPFDocument(FileInputStream(wordFile))
        
        // Convert paragraphs
        for (paragraph in docxDocument.paragraphs) {
            val text = paragraph.text
            if (text.isNotEmpty()) {
                document.add(Paragraph(text))
            }
        }

        // Convert tables
        for (table in docxDocument.tables) {
            for (row in table.rows) {
                val rowText = row.tableCells.joinToString(" | ") { it.text }
                document.add(Paragraph(rowText))
            }
        }

        document.close()
        docxDocument.close()
    } catch (e: Exception) {
        throw e
    }
}

The above solution uses iText library for pdf conversion; creates a temporary Word file in the cache directory; converts the Word content to pdf while maintaining text formatting; automatically deletes the temporary Word file; and saves only the final pdf to the Downloads folder.

To implement this:

Add the iText dependency to your build.gradle:

implementation 'com.itextpdf:itextpdf:5.5.13.3'

Replace your existing editWordFile function with the new editWordFileAndConvertToPDF function from the artifact.

Note that this basic implementation handles text and tables. If you need more advanced formatting (like images, complex layouts, or specific fonts), you might need to add additional conversion logic in the convertWordToPDF function.

Some limitations to be aware of:

  • Some complex formatting might not transfer perfectly
  • Images will need additional handling if present in your documents
  • Very large documents might need optimisation

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật