在对JSON响应进行一些数学运算后,如何在Flutter中创建PDF文件?

问题描述

您好,我已经进行了充分的头脑风暴,我想在这里寻求一些建议。.直截了当::p

这是我通过Flutter Async的Json响应正文:

{

  "success":true,"data":

 [ 
    {"id":161,"product_name":"Apple","user_id":72,"quantity":1,"price": 96
     "custom_fields":[]
    },{"id":162,"product_name":"Orange","quantity":2,"price": 85,"custom_fields":[]
    }
 ],"message":"Carts retrieved successfully"

}

我需要能够使用上面的数组在Flutter内创建PDF文件,并且PDF文件内容应类似于:

    XXXXXX

    Item    Qty  price 

  1)Apple   1    96
  2)Orange  2    170
  
  Subtotal : 266

最后,我将把这个PDF发送到我的PHP服务器(可以使用一些软件包)。如果此要求可行,我需要一些专家建议,并需要一些帮助以开始使用。

解决方法

这是json的数据类

 class ModelClass {
  bool success;
  List<Data> data;
  String message;

  ModelClass({this.success,this.data,this.message});

  ModelClass.fromJson(Map<String,dynamic> json) {
    success = json['success'];
    if (json['data'] != null) {
      data = new List<Data>();
      json['data'].forEach((v) {
        data.add(new Data.fromJson(v));
      });
    }
    message = json['message'];
  }

  Map<String,dynamic> toJson() {
    final Map<String,dynamic> data = new Map<String,dynamic>();
    data['success'] = this.success;
    if (this.data != null) {
      data['data'] = this.data.map((v) => v.toJson()).toList();
    }
    data['message'] = this.message;
    return data;
  }
}

class Data {
  int id;
  String productName;
  int userId;
  int quantity;
  int price;
  List<dynamic> customFields;

  Data(
      {this.id,this.productName,this.userId,this.quantity,this.price,this.customFields});

  Data.fromJson(Map<String,dynamic> json) {
    id = json['id'];
    productName = json['product_name'];
    userId = json['user_id'];
    quantity = json['quantity'];
    price = json['price'];
    customFields = json['custom_fields'].cast<String>();
  }

  Map<String,dynamic>();
    data['id'] = this.id;
    data['product_name'] = this.productName;
    data['user_id'] = this.userId;
    data['quantity'] = this.quantity;
    data['price'] = this.price;
    data['custom_fields'] = this.customFields;
    return data;
  }
}

现在解析模型对象中的json

ModelClass modelClass = ModelClass.fromJson(json);

现在,通过使用pdf软件包,我们可以构建pdf。

import 'dart:typed_data';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;

Future<Uint8List> generateDocument() async {
  final pw.Document doc = pw.Document();
  
  doc.addPage(pw.MultiPage(
      pageFormat:
          PdfPageFormat.letter.copyWith(marginBottom: 1.5 * PdfPageFormat.cm),crossAxisAlignment: pw.CrossAxisAlignment.start,header: (pw.Context context) {
        if (context.pageNumber == 1) {
          return null;
        }
        return pw.Container(
            alignment: pw.Alignment.centerRight,margin: const pw.EdgeInsets.only(bottom: 3.0 * PdfPageFormat.mm),padding: const pw.EdgeInsets.only(bottom: 3.0 * PdfPageFormat.mm),decoration: const pw.BoxDecoration(
                border: pw.BoxBorder(
                    bottom: true,width: 0.5,color: PdfColors.grey)),child: pw.Text('Portable Document Format',style: pw.Theme.of(context)
                    .defaultTextStyle
                    .copyWith(color: PdfColors.grey)));
      },build: (pw.Context context) => <pw.Widget>[
            pw.Table.fromTextArray(
                context: context,border: null,headerAlignment: pw.Alignment.centerLeft,data: <List<String>>[
                  <String>['Item','Qty','Price'],for (int i = 0; i < modelClass.data.length; i++)
                    <String>['${i+1}) ${modelClass.data.elementAt(i).productName}','${modelClass.data.elementAt(i).quantity}','${modelClass.data.elementAt(i).price}'],]),pw.Paragraph(text: ""),pw.Paragraph(text: "Subtotal: $total"),pw.Padding(padding: const pw.EdgeInsets.all(10)),]));

  return doc.save();
}

现在使用flutter_pdfview软件包查看此pdf文件。

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key,this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  File file;

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),),body: Center(
        child: file!=null?PDFView(
          filePath: file.path,autoSpacing: false,pageFling: false,):Container()
      ),);
  }

  @override
  void initState() {
    getPdf();
    super.initState();
  }

  void getPdf() async{
    Uint8List uint8list = await generateDocument();
    Directory output = await getTemporaryDirectory();
    file = File(output.path+"/example.pdf");
    setState(() {
      file.writeAsBytes(uint8list);
      print(file.path);
    });
  }

}

输出: Output

,
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;

 pw.Table.fromTextArray(
                context: context,// headerAlignment: pw.Alignment.centerLeft,data: <List<String>>[
                  <String>['Item'],for (int i = 0; i < element.length; i++)
                    <String>['${i+1}) ${element.elementAt(i).Item}'],

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...