Как создать PDF из JSONObject в Android? - PullRequest
0 голосов
/ 17 октября 2019

У меня есть JSONObject, и мне нужно сгенерировать PDF, где содержимое будет довольно отформатировано JSON из этого JSONObject. Как мне сгенерировать его в Android Kotlin?

Я нашел похожую работу в Github , но он не может успешно скомпилироваться.

Ответы [ 2 ]

0 голосов
/ 25 октября 2019

Создание PDF с необработанной строкой JSON в качестве содержимого

import android.graphics.Color
import android.graphics.Paint
import android.graphics.pdf.PdfDocument
import com.google.gson.GsonBuilder    

class PdfGeneratorService(){

    private val ROW_INC = 20F
    private val COL_INC = 15F

    fun jsonFormat(jsonStr: String): String {

        var indentCount = 0

        val builder = StringBuilder()
        for (c in jsonStr) {
            if (indentCount > 0 && '\n' == builder.last()) {
                for (x in 0..indentCount) builder.append("    ")
            }
            when (c) {
                '{', '[' -> {
                    builder.append(c).append("\n")
                    indentCount++
                }
                ',' -> builder.append(c).append("\n")
                '}', ']' -> {
                    builder.append("\n")
                    indentCount--
                    for (x in 0..indentCount) builder.append("    ")
                    builder.append(c)
                }
                else -> builder.append(c)
            }
        }

        return builder.toString()
    }

    private fun createPdf(textToPdf: String) {
        try {
            val gSon = GsonBuilder().setPrettyPrinting().create()
            val text = gSon.toJson(jsonFormat(textToPdf))

            val rawLines = text.split("\\n")
            val jsonLines = rawLines.map { it.replace("\\", "") }
            val maxLengthString = jsonLines.maxBy { it.length }

            val paint = Paint()
            paint.color = Color.BLACK
            paint.fontSpacing

            val pageWidth = paint.measureText(maxLengthString).toInt() + 2 * COL_INC.toInt() // 2, two side padding
            val pageHeight = (ROW_INC * rawLines.size + ROW_INC).toInt()

            val document = PdfDocument()
            val pageInfo: PdfDocument.PageInfo = PdfDocument.PageInfo.Builder(pageWidth, pageHeight, 1).create()
            val page: PdfDocument.Page = document.startPage(pageInfo)
            val canvas = page.canvas

            for (line in jsonLines) {
                canvas.drawText(line, column, row, paint)
                row += ROW_INC
            }

            document.finishPage(page)
            document.writeTo(FileOutputStream(File(PATH_TO_PDF_FILE)))
            document.close()
        }catch (e: java.lang.Exception){
            Log.e("classTag", e)
        }
    }
}

Вы можете найти статью о том, как использовать Gson

0 голосов
/ 17 октября 2019

Вот способ, которым я создаю PDF с помощью Native android PDF create PDFDocument
Я использую изображения для создания PDF, но я думаю, что вы можете получить данные JSON, используя VolleyПлюс это обновленная версия залпа Google и вызовите его в PDF

 private void PDFCreation(){
            PdfDocument document=new PdfDocument();
            PdfDocument.PageInfo pageInfo;
            PdfDocument.Page page;
            Canvas canvas;
            int i;
            for (i=0; i < list.size(); i++)  {
                pageInfo=new PdfDocument.PageInfo.Builder(992, 1432, 1).create();
                page=document.startPage(pageInfo);
                canvas=page.getCanvas();
                image=BitmapFactory.decodeFile(list.get(i));
                image=Bitmap.createScaledBitmap(image, 980, 1420, true);
                image.setDensity(DisplayMetrics.DENSITY_300);
                canvas.setDensity(DisplayMetrics.DENSITY_300);

                float rotation=0;
                try {
                    ExifInterface exifInterface=new ExifInterface(selectedPhoto);
                    int orientation=exifInterface.getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL);
                    switch (orientation) {
                        case ExifInterface.ORIENTATION_ROTATE_90: {
                            rotation=-90f;
                            break;
                        }
                        case ExifInterface.ORIENTATION_ROTATE_180: {
                            rotation=-180f;
                            break;
                        }
                        case ExifInterface.ORIENTATION_ROTATE_270: {
                            rotation=90f;
                            break;
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                Matrix matrix = new Matrix();
                matrix.postRotate(rotation);
                Bitmap.createBitmap(image, 0, 0,
                        image.getWidth(), image.getHeight(),
                        matrix, true);
                canvas.rotate(rotation);
                canvas.drawBitmap(image, 0, 0, null);
                document.finishPage(page);
            }
            @SuppressWarnings("deprecation") String directory_path=Environment.getExternalStorageDirectory().getPath() + "/mypdf/";
            File file=new File(directory_path);
            if (!file.exists()) {
                //noinspection ResultOfMethodCallIgnored
                file.mkdirs();
            }
            @SuppressLint("SimpleDateFormat") String timeStamp=(new SimpleDateFormat("yyyyMMdd_HHmmss")).format(new Date());
            String targetPdf=directory_path + timeStamp + ".pdf";
             filePath=new File(targetPdf);
            try {
                document.writeTo(new FileOutputStream(filePath));
            } catch (IOException e) {
                Log.e("main", "error " + e.toString());
                Toasty.error(this, "Error making PDF" + e.toString(), Toast.LENGTH_LONG).show();
            }
            document.close();

Вот как вытащить данные JSON залпом, это помещает данные JSON в счетчик

private void loadSpinnerData(String url) {
        RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
        StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Toasty.info(SecondActivity.this, "Please Select Category and Client", Toast.LENGTH_SHORT).show();
                try {
                    JSONObject jsonObject=new JSONObject(response);
                    if (jsonObject.getInt("success") == 1) {
                        JSONArray jsonArray=jsonObject.getJSONArray("Name");
                        for (int i=0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject1=jsonArray.getJSONObject(i);
                            String category=jsonObject1.getString("Category");
                            CategoryName.add(category);
                        }
                    }
                    spinner.setAdapter(new ArrayAdapter<>(SecondActivity.this, android.R.layout.simple_spinner_dropdown_item, CategoryName));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

Если вы измените этот фрагмент так, чтобы строка json перетаскивалась в PDF-документ, который будет отлично работать

...