Android 如何从 JSONObject 生成 PDF?

How to Generate PDF from JSONObject in Android?

我有一个 JSONObject,我必须生成一个 PDF,其中的内容将是 JSONObject 的原始格式 JSON。如何在 Android Kotlin 中生成它?

我在Github中找到了类似的工作,但无法成功编译。

这是我使用本机创建 PDF 的方式 android PDF 创建 PDFDocument
我正在使用图像创建 PDF,但我认为您可以使用 Volley Plus 提取 JSON 数据,它是 googles volley 的升级版本并将其调用到 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();

以下是如何使用 volley 提取 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 字符串拉入 PDFdocument 中,那将完美运行

以 Raw JSON 字符串作为内容生成 PDF

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