diff --git a/app/src/main/java/com/example/myapplication/api/item/RestItemRepository.kt b/app/src/main/java/com/example/myapplication/api/item/RestItemRepository.kt index 453a43e..7d4bcdc 100644 --- a/app/src/main/java/com/example/myapplication/api/item/RestItemRepository.kt +++ b/app/src/main/java/com/example/myapplication/api/item/RestItemRepository.kt @@ -1,5 +1,15 @@ package com.example.myapplication.api.item +import android.content.ContentResolver +import android.content.ContentValues +import android.content.Context +import android.content.Intent +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.pdf.PdfDocument +import android.net.Uri +import android.os.Environment +import android.provider.MediaStore import com.example.myapplication.api.MyServerService import com.example.myapplication.api.report.ReportRemote import com.example.myapplication.database.entities.model.Item @@ -7,6 +17,10 @@ import com.example.myapplication.database.entities.repository.OfflineRentItemRep import com.example.myapplication.database.entities.repository.OfflineItemRepository import com.example.myapplication.database.entities.repository.OfflineUserItemRepository import com.example.myapplication.database.entities.repository.ItemRepository +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.io.IOException +import java.io.OutputStream class RestItemRepository( private val service: MyServerService, @@ -53,4 +67,87 @@ class RestItemRepository( { return service.getReportInfo(fromDate,toDate) } + + + suspend fun createPdfFile(context: Context, fileName: String, reportData: List) { + 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 contentResolver: ContentResolver = context.contentResolver + val uri: Uri? = contentResolver.insert(MediaStore.Files.getContentUri("external"), contentValues) + + uri?.let { + try { + contentResolver.openOutputStream(uri)?.use { outputStream -> + createPdfContent(outputStream, reportData) + } + + // Optional: Notify MediaStore about the new file + context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri)) + } catch (e: IOException) { + e.printStackTrace() + } + } + } + } + + private fun createPdfContent(outputStream: OutputStream, reportData: List) { + 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.textSize = 16f // Уменьшаем размер шрифта для лучшей видимости + paint.isAntiAlias = true + + // Отображаем заголовок + val title = "Отчет" + val xTitle = (pageInfo.pageWidth - paint.measureText(title)) / 2 + val yTitle = 40f + canvas.drawText(title, xTitle, yTitle, paint) + + // Отображаем данные в виде таблицы + val tableStartY = yTitle + 80f + val columnWidths = floatArrayOf(0.5f, 1.5f, 1f, 1.5f, 1f) // Увеличиваем ширину столбцов + val rowHeight = 30f // Увеличиваем высоту строки + + drawTableRow(canvas, arrayOf("ID", "Дата проверки", "Вес", "Количество", "ID велосипеда"), columnWidths, tableStartY, paint) + + for ((index, report) in reportData.withIndex()) { + val row = arrayOf( + report.id.toString(), + report.dateTime.toString(), + report.weight.toString(), + report.maxCount.toString(), + report.bikeId.toString() + ) + drawTableRow(canvas, row, columnWidths, tableStartY + (index + 1) * rowHeight, paint) + } + + pdfDocument.finishPage(page) + + pdfDocument.writeTo(outputStream) + pdfDocument.close() + } + + private fun drawTableRow( + canvas: Canvas, + row: Array, + columnWidths: FloatArray, + y: Float, + paint: Paint + ) { + var x = 40f + for (i in row.indices) { + val text = row[i] + canvas.drawText(text, x, y, paint) + x += columnWidths[i] * 80 // Увеличиваем ширину столбцов + } + } } \ No newline at end of file diff --git a/app/src/main/java/com/example/myapplication/database/entities/composeui/ReportPage.kt b/app/src/main/java/com/example/myapplication/database/entities/composeui/ReportPage.kt index 6ec1958..ac3443e 100644 --- a/app/src/main/java/com/example/myapplication/database/entities/composeui/ReportPage.kt +++ b/app/src/main/java/com/example/myapplication/database/entities/composeui/ReportPage.kt @@ -131,7 +131,7 @@ fun ReportPage (navController: NavController?, viewModel: ReportViewModel = view Button( onClick = {coroutineScope.launch { //viewModel.getReport() - createPdfFile(context = context, fileName = "отчет.pdf",reportData = reportResultPageState.resReport) + viewModel.generatePdfFile(context = context, fileName = "отчет.pdf",reportData = reportResultPageState.resReport) } }, enabled = viewModel.reportPageUiState.isEntryValid, modifier = Modifier @@ -194,85 +194,4 @@ fun TableScreen(reportData: List) { } } -suspend fun createPdfFile(context: Context, fileName: String, reportData: List) { - 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 contentResolver: ContentResolver = context.contentResolver - val uri: Uri? = contentResolver.insert(MediaStore.Files.getContentUri("external"), contentValues) - - uri?.let { - try { - contentResolver.openOutputStream(uri)?.use { outputStream -> - createPdfContent(outputStream, reportData) - } - - // Optional: Notify MediaStore about the new file - context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri)) - } catch (e: IOException) { - e.printStackTrace() - } - } - } -} - -private fun createPdfContent(outputStream: OutputStream, reportData: List) { - 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.textSize = 16f // Уменьшаем размер шрифта для лучшей видимости - paint.isAntiAlias = true - - // Отображаем заголовок - val title = "Отчет" - val xTitle = (pageInfo.pageWidth - paint.measureText(title)) / 2 - val yTitle = 40f - canvas.drawText(title, xTitle, yTitle, paint) - - // Отображаем данные в виде таблицы - val tableStartY = yTitle + 80f - val columnWidths = floatArrayOf(0.5f, 1.5f, 1f, 1.5f, 1f) // Увеличиваем ширину столбцов - val rowHeight = 30f // Увеличиваем высоту строки - - drawTableRow(canvas, arrayOf("ID", "Дата проверки", "Вес", "Количество", "ID велосипеда"), columnWidths, tableStartY, paint) - - for ((index, report) in reportData.withIndex()) { - val row = arrayOf( - report.id.toString(), - report.dateTime.toString(), - report.weight.toString(), - report.maxCount.toString(), - report.bikeId.toString() - ) - drawTableRow(canvas, row, columnWidths, tableStartY + (index + 1) * rowHeight, paint) - } - - pdfDocument.finishPage(page) - - pdfDocument.writeTo(outputStream) - pdfDocument.close() -} - -private fun drawTableRow( - canvas: Canvas, - row: Array, - columnWidths: FloatArray, - y: Float, - paint: Paint -) { - var x = 40f - for (i in row.indices) { - val text = row[i] - canvas.drawText(text, x, y, paint) - x += columnWidths[i] * 80 // Увеличиваем ширину столбцов - } -} diff --git a/app/src/main/java/com/example/myapplication/database/entities/composeui/ReportViewModel.kt b/app/src/main/java/com/example/myapplication/database/entities/composeui/ReportViewModel.kt index 2d1ebea..ee5e031 100644 --- a/app/src/main/java/com/example/myapplication/database/entities/composeui/ReportViewModel.kt +++ b/app/src/main/java/com/example/myapplication/database/entities/composeui/ReportViewModel.kt @@ -1,5 +1,6 @@ package com.example.myapplication.database.entities.composeui +import android.content.Context import android.util.Log import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -40,6 +41,10 @@ class ReportViewModel(private val itemRespository: RestItemRepository): ViewMode val res = itemRespository.getReport(startDateQueryParam, endDateQueryParam) reportResultPageUiState = ReportResultPageUiState(res) } + + suspend fun generatePdfFile(context: Context, fileName: String, reportData: List) { + itemRespository.createPdfFile(context, fileName, reportData) + } } data class ReportDetails(