在Flutter中生成PDF

1rhkuytd  于 2023-08-07  发布在  Flutter
关注(0)|答案(2)|浏览(185)

我得到了API的文件响应


的数据
我想将其生成为PDF并使用open_filex打开
这是我曾经尝试过的

@override
  Future<Either<Failure, dynamic>> getInvoicePDF(GetInvoiceParams param) async {
    return await Factory().exceptionsGuard(() async {
      var res = await RemoteDataSourceResponseGuard.execute<dynamic>(
        _invoiceRemoteDataSource.downloadInvoicePDF(
            sessionToken: param.sessionToken,
            userId: param.userId,
            invoiceId: param.invoiceId),
      );

      await generatePDF(res);
    });
  }

  Future generatePDF(dynamic value) async {
    debugPrint("file response $value".toString());
    String dir = (await getApplicationDocumentsDirectory()).path;

    File file = File('$dir/"file".pdf');

    await file.writeAsBytes(value);

    try {
      OpenFilex.open(file.path);
    } catch (e) {
      debugPrint("error $e");
    }
  }

字符串

*InvoiceRemoteDataSource

import 'package:dio/dio.dart';
import 'package:retrofit/retrofit.dart';

part 'invoice_remote_data_source.g.dart';

@RestApi()
abstract class InvoiceRemoteDataSource {
  factory InvoiceRemoteDataSource(
    Dio dio, {
    String baseUrl,
  }) = _InvoiceRemoteDataSource;

  @POST('/download_invoice_pdf')
  Future<dynamic> downloadInvoicePDF({
    @Field("session_token") required String sessionToken,
    @Field("user_id") required String userId,
    @Field("invoice_id") required String invoiceId,
  });
}


日志中显示的值为%PDF-1.4
这里的错误

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'String' is not a subtype of type 'List<int>'


这是在日志中显示的响应部分。


suzh9iv8

suzh9iv81#

首先,您需要像这样将改进响应api更正为HttpResponse<List<int>>

@DioResponseType(ResponseType.stream)
 @POST('/download_invoice_pdf')
   Future<HttpResponse<List<int>>> downloadInvoicePDF({
   @Field("session_token") required String sessionToken,
  @Field("user_id") required String userId,
  @Field("invoice_id") required String invoiceId,
});

字符串
下面是保存文件的重写代码:

var res = await  RemoteDataSourceResponseGuard.execute<HttpResponse<List<int>>>(
    _invoiceRemoteDataSource.downloadInvoicePDF(
        sessionToken: param.sessionToken,
        userId: param.userId,
        invoiceId: param.invoiceId),
  );
  
  final bytes = res.data;
  await generatePDF(bytes);

flvtvl50

flvtvl502#

我设法以这种方式打开它。

Future<File> generatePDF(GetInvoiceParams param) async {
    var request = await HttpClient().getUrl(Uri.parse(
        "url"));
    var response = await request.close();
    var bytes = await consolidateHttpClientResponseBytes(response);
    String dir = (await getApplicationDocumentsDirectory()).path;
    File file = File('$dir/pdfName.pdf');
    await file.writeAsBytes(bytes);
    return file;
  }

 // then open the file path using openx

字符串

相关问题