короче, я поменял библиотеку, и только так смог выбрать русский язык

This commit is contained in:
Кашин Максим 2023-12-25 00:14:44 +04:00
parent 359d8311fb
commit 7ed6a2bf09
2 changed files with 64 additions and 37 deletions

View File

@ -96,7 +96,4 @@ dependencies {
androidTestImplementation("androidx.compose.ui:ui-test-junit4")
debugImplementation("androidx.compose.ui:ui-tooling")
debugImplementation("androidx.compose.ui:ui-test-manifest")
//PDF
implementation ("com.itextpdf:itextpdf:5.5.13")
}

View File

@ -1,8 +1,17 @@
package com.example.myapplication.database.entities.composeui
import android.annotation.SuppressLint
import android.content.ContentResolver
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Paint
import android.graphics.pdf.PdfDocument
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.BorderStroke
@ -41,6 +50,7 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
@ -58,13 +68,15 @@ import com.example.myapplication.composeui.navigation.Screen
import com.example.myapplication.database.entities.model.User
import com.example.myapplication.datastore.DataStoreManager
import com.example.myapplication.datastore.SettingData
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import com.itextpdf.text.Document
import com.itextpdf.text.Paragraph
import com.itextpdf.text.pdf.PdfWriter
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream
@SuppressLint("UnrememberedMutableState")
@Composable
fun UserProfile(
@ -240,8 +252,10 @@ fun UserProfile(
) {
Button(
onClick = {
generatePdf(context = context, fileName = "отчет.pdf")
Log.d("context", "${context}")
coroutineScope.launch {
createPdfFile(context = context, fileName = "отчет.pdf")
Log.d("context", "${context}")
}
},
modifier = Modifier
.fillMaxWidth()
@ -378,37 +392,53 @@ fun LoginScreenProfile(currentUserViewModel: CurrentUserViewModel = viewModel(fa
}
}
fun generatePdf(context: Context, fileName: String) {
// Создаем документ
val document = Document()
@OptIn(ExperimentalComposeUiApi::class)
suspend fun createPdfFile(context: Context, fileName: String) {
withContext(Dispatchers.IO) {
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
put(MediaStore.MediaColumns.MIME_TYPE, "application/pdf")
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS)
}
// Получаем публичный каталог документов
val directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
val contentResolver: ContentResolver = context.contentResolver
val uri: Uri? = contentResolver.insert(MediaStore.Files.getContentUri("external"), contentValues)
// Создаем каталог, если его нет
if (!directory.exists()) {
directory.mkdirs()
uri?.let {
try {
contentResolver.openOutputStream(uri)?.use { outputStream ->
createPdfContent(outputStream)
}
// Optional: Notify MediaStore about the new file
context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri))
} catch (e: IOException) {
e.printStackTrace()
}
}
}
// Получаем полный путь к файлу
val filePath = File(directory, fileName).absolutePath
// Указываем путь к файлу PDF
val writer = PdfWriter.getInstance(document, FileOutputStream(filePath))
// Открываем документ для записи
document.open()
// Добавляем текст "Привет, мир" в документ
document.add(Paragraph("hello! русский не работает?"))
// Закрываем документ
document.close()
// Закрываем писатель
writer.close()
// Выводим путь в журнал
Log.d("PDF Generation", "File created at: $filePath")
}
private fun createPdfContent(outputStream: OutputStream) {
val pdfDocument = PdfDocument()
val pageInfo = PdfDocument.PageInfo.Builder(595, 842, 1).create()
val page = pdfDocument.startPage(pageInfo)
val canvas = page.canvas
val paint = Paint()
paint.color = Color.BLACK
paint.textSize = 24f
val text = "Привет, мир!"
val x = (pageInfo.pageWidth - paint.measureText(text)) / 2
val y = (pageInfo.pageHeight + paint.textSize) / 2
canvas.drawText(text, x, y, paint)
pdfDocument.finishPage(page)
pdfDocument.writeTo(outputStream)
pdfDocument.close()
}