我的 Flutter“生成 PDF”按钮不起作用 [已关闭]

问题描述 投票:0回答:1

我正在开发一个 Flutter 应用程序,我需要在按下按钮时生成 PDF。但是,“生成 PDF”按钮未按预期运行。我在控制台中遇到以下错误:

这是我的错误控制台:

E/flutter(7975):[错误:flutter/runtime/dart_vm_initializer.cc(41)] 未处理的异常:RangeError(索引):索引超出范围:否 索引有效:0 E/flutter ( 7975): #0 Uint8List.[] (dart:typed_data-patch/typed_data_patch.dart:2271:7) E/flutter ( 7975): #1 输入缓冲区。[] (包:image/src/util/input_buffer.dart:44:39) E/flutter (7975): #2 JpegData.验证 (包:image/src/formats/jpeg/jpeg_data.dart:64:17) E/flutter ( 第7975章):#3 (包:image/src/formats/jpeg_decoder.dart:18:50) E/flutter (7975): #4 findDecoderForData (包:image/src/formats/formats.dart:116:11) E/flutter (7975): #5 新的 MemoryImage (包:pdf/src/widgets/image_provider.dart:101:24) E/flutter(7975):#6 CetakinvoicePage._generatePDF。 (包:smta/cetakinvoicepage.dart:421:22) E/flutter ( 第7975章):#7页面.postProcess (包:pdf/src/widgets/page.dart:142:21)E/flutter(7975):#8
Document.save(包:pdf/src/widgets/document.dart:130:14)E/flutter (7975):#9 CetakinvoicePage._generatePDF (包:smta/cetakinvoicepage.dart:442:39)E/flutter(7975): E/颤动(7975):

这是我的代码:

import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:path_provider/path_provider.dart';
import 'package:open_file/open_file.dart';
import 'package:flutter/services.dart' show rootBundle;

class CetakinvoicePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: SafeArea(
          child: SingleChildScrollView(
            child: Column(
              children: [
                // Your existing content here...
                Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 20.0),
                        child: Column(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              SizedBox(height: 10.0,),
                              Padding(
                                padding: EdgeInsets.symmetric(horizontal: 10.0),
                                child: Row(
                                  children: [
                                    Image.asset(
                                      'assets/images/logosgntulisan.png',
                                      width: 120,
                                    ),
                                    Spacer(),
                                    Column(
                                      children: [
                                        Image.asset(
                                          'assets/images/barcodedummy.png',
                                          width: 150,
                                        ),
                                        SizedBox(height: 5.0,),
                                        const Text(
                                          'SG10202312060001',
                                          style: TextStyle(
                                            fontSize: 16,
                                            color: Colors.black,
                                            fontWeight: FontWeight.w400,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                              ),
                              Padding(
                                padding: EdgeInsets.symmetric(horizontal: 5.0),
                                child: Container(
                                  width: double.infinity,
                                  child: const Divider(
                                    color: Colors.black,
                                    thickness: 1.0,
                                  ),
                                ),
                              ),
                              Column(
                                children: [
                                  const Text(
                                    'PT SINERGI GULA NUSANTARA',
                                    style: TextStyle(
                                      fontSize: 16,
                                      color: Colors.black,
                                      fontWeight: FontWeight.w500,
                                    ),
                                  ),
                                ],
                              ),
                            ]
                        ),
                      ),
                    ]
                ),
                // Button to trigger PDF generation
                SizedBox(height: 10.0,),
                ElevatedButton(
                  onPressed: () {
                    _generatePDF(context);
                  },
                  child: Text('Generate PDF'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // Function to generate PDF
  Future<void> _generatePDF(BuildContext context) async {
    final pdf = pw.Document();


    // Add content to the PDF
    pdf.addPage(pw.Page(
      pageFormat: PdfPageFormat.a4,
      build: (pw.Context context) {
        return pw.Row(
          children: [
            pw.Column(
              crossAxisAlignment: pw.CrossAxisAlignment.start,
              children: [
              ],
            ),
            pw.Column(
              crossAxisAlignment: pw.CrossAxisAlignment.start,
              mainAxisAlignment: pw.MainAxisAlignment.end,
              children: [
                pw.Text(
                  'Waktu Masuk',
                  style: pw.TextStyle(
                    fontSize: 14,
                    color: PdfColors.black,
                    fontWeight: pw.FontWeight.bold,
                  ),
                ),
                pw.SizedBox(height: 5.0),
                pw.Text(
                  '14-12/2023 19.00',
                  style: pw.TextStyle(
                    fontSize: 14,
                    color: PdfColors.black,
                    fontWeight: pw.FontWeight.normal,
                  ),
                ),
                pw.SizedBox(height: 10.0),
                pw.Image(
                  pw.MemoryImage(
                    // Convert your image to bytes (you might need to change this part)
                    // For example: (await rootBundle.load('assets/images/truktebugambar.jpg')).buffer.asUint8List()
                    Uint8List.fromList([/* your image bytes go here */]),
                  ),
                  height: 100,
                  width: 120,
                ),
                pw.SizedBox(height: 20.0),
              ],
            ),
          ],
        );
      },
    ));

    // Get the application documents directory
    final directory = await getApplicationDocumentsDirectory();

    // Create the PDF file
    final file = File('${directory.path}/example.pdf');
    await file.writeAsBytes(await pdf.save());

    // Open the PDF using a PDF viewer
    OpenFile.open(file.path);
  }
}

我尝试通过包含生成 PDF 所需的代码来解决此问题,但似乎存在与 MemoryImage 相关的错误。我怀疑这与加载 PDF 图像有关,但我不确定如何解决它。

任何有关解决此问题的帮助或指导将不胜感激。

flutter dart pdf flutter-dependencies
1个回答
2
投票

您的错误消息似乎引用了内存图像(可能是您尝试在不带任何参数的 pdf 方法中创建的图像)。请参阅代码块中的注释:

/* 你的图像字节放在这里 */

尝试注释你的 pw.Image() 块,直到你在 Uint8List.fromList() 中添加一些内容,或者将你的 pw.MemoryImage 更改为如下所示:

pw.MemoryImage(
      (await rootBundle.load('images/mylogo.webp'))
          .buffer
          .asUint8List(),
    )
© www.soinside.com 2019 - 2024. All rights reserved.