Comment to @Zeros-N-Ones As you told , extra processing need to be done for images, I have background image for this word file, which isn't visible in pdf file, and also the formatting is getting wrecked. What to do next? I've give below my updated code and sample ss images of output word and pdf files.
private fun editWordFileAndConvertToPdf2(
context: Context, name: String, program: String, date: String,
start: String, end: String, assetsName: String, type: String
) {
try {
val assetManager = context.assets
val wordFileName = assetsName
val inputStream: InputStream = assetManager.open(wordFileName)
val outputName = "${name}_${type}_joining.pdf"
val wordOutputName = "${name}_${type}_joining.docx"
val outputDir = "/storage/emulated/0/Download/"
// Ensure permissions are granted
if (!isPermissionGranted(context)) {
requestPermission(context)
Toast.makeText(context, "Permission required for file operations", Toast.LENGTH_SHORT).show()
return
}
try {
// Read Word file
val document = XWPFDocument(inputStream)
// Replace placeholders with data
for (paragraph: XWPFParagraph in document.paragraphs) {
for (run: XWPFRun in paragraph.runs) {
val text = run.text()
println("Text: $text, Program: $program")
if (text.contains("XDATEX")) {
run.setText(text.replace("XDATEX", date), 0)
}
if (text.contains("XLAMAX")) {
run.setText(text.replace("XLAMAX", name), 0)
}
if (text.contains("XVARIXBLEX", ignoreCase = true)) {
run.setText(text.replace("XVARIXBLEX", program), 0)
}
if (text.contains("XNOXNOXXXXOXX")) {
run.setText(text.replace("XNOXNOXXXXOXX", start), 0)
}
if (text.contains("YNOXNOXXXXOXY")) {
run.setText(text.replace("YNOXNOXXXXOXY", end), 0)
}
}
}
// Save the modified Word file using FileOutputStream
val wordFile = File(outputDir, wordOutputName)
val fos = FileOutputStream(wordFile)
document.write(fos)
fos.close()
// Save the Word file to Downloads folder as well
saveWordToDownloads(context, wordFile, wordOutputName)
// Convert Word to PDF
val pdfFile = File(context.cacheDir, outputName)
convertWordToPDF(wordFile, pdfFile)
// Save PDF to Downloads folder
savePDFToDownloads(context, pdfFile, outputName)
// Delete temporary files if needed
wordFile.delete()
outputNameShare= outputName
imgShare.visibility=VISIBLE
Toast.makeText(context, "Word and PDF files saved to Downloads: $wordOutputName, $outputName", Toast.LENGTH_SHORT).show()
} catch (e: Exception) {
e.printStackTrace()
Toast.makeText(context, "Error occurred: ${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 isPermissionGranted(context: Context): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// No explicit storage permission needed for scoped storage
true
} else {
val permissionCheck = ContextCompat.checkSelfPermission(
context, Manifest.permission.WRITE_EXTERNAL_STORAGE
)
permissionCheck == PackageManager.PERMISSION_GRANTED
}
}
private fun requestPermission(context: Context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
ActivityCompat.requestPermissions(
context as Activity,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
100
)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == 100 && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission granted!", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Permission denied!", Toast.LENGTH_SHORT).show()
}
}
private fun savePDFToDownloads(context: Context, sourceFile: File, fileName: String) {
val resolver = context.contentResolver
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val values = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
put(MediaStore.MediaColumns.MIME_TYPE, "application/pdf")
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)
}
val uri = resolver.insert(MediaStore.Files.getContentUri("external"), values)
uri?.let {
resolver.openOutputStream(it).use { outputStream ->
sourceFile.inputStream().use { inputStream ->
inputStream.copyTo(outputStream!!)
}
}
}
} else {
val downloadsDir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName)
sourceFile.copyTo(downloadsDir, overwrite = true)
}
}
private fun saveWordToDownloads(context: Context, sourceFile: File, fileName: String) {
val resolver = context.contentResolver
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val values = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
put(MediaStore.MediaColumns.MIME_TYPE, "application/vnd.openxmlformats-officedocument.wordprocessingml.document") // MIME type for Word
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)
}
val uri = resolver.insert(MediaStore.Files.getContentUri("external"), values)
uri?.let {
resolver.openOutputStream(it).use { outputStream ->
sourceFile.inputStream().use { inputStream ->
inputStream.copyTo(outputStream!!)
}
}
}
} else {
// For Android versions lower than Q
val downloadsDir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName)
sourceFile.copyTo(downloadsDir, overwrite = true)
}
}
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
}
}