Criação de PDF com Flutter

Tempo de leitura: 4 minutes

Ao criar um aplicativo móvel, pode ser necessário criar uma exibição de detalhes que não se ajusta ao tamanho do seu dispositivo. Nesses casos, você pode usar um pdf para visualizar seus detalhes. Vamos ver como gerar uma visualização em PDF com seus dados em flutter.

Podemos usar pacotes criados pela comunidade flutter para facilitar as coisas.

Para começar, instale os seguintes pacotes nas versões mais recentes. Essas são as versões que eu usei.

pdf: ^3.10.1
pdf_viewer_plugin: ^2.0.1
path_provider: ^2.0.14

Usando pdf_viewer_plugin, crie um PdfViewerPage para um determinado caminho da seguinte maneira.

pdf_view_page.dart

import 'package:flutter/material.dart';
import 'package:pdf_viewer_plugin/pdf_viewer_plugin.dart';

class PdfViewerPage extends StatelessWidget {
  final String path;
  const PdfViewerPage({super.key, required this.path});

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: PdfView(
        path: path,
      ),
    );
  }
}

Em seguida, você pode criar seu conteúdo em PDF. ‘package:pdf/widgets.dart’ fornecerá um conjunto de widgets para criar o conteúdo do pdf. Além de parágrafos e tabelas com conteúdo estático, você também pode gerar um pdf para os dados de uma solicitação de API. Todos os widgets de pdf/widgets não são iguais aos widgets de material. Você pode se aprofundar nesses widgets para ver o que eles podem fazer e quais são as diferenças.

report_pdf.dart

import 'package:flutter_demo_pdf/app/page/pdf_view_page.dart';
import 'package:pdf/pdf.dart';
import 'dart:io';
import 'package:pdf/widgets.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/material.dart' as material;

reportView(context) async {
  final Document pdf = Document();

  pdf.addPage(MultiPage(
      pageFormat:
      PdfPageFormat.letter.copyWith(marginBottom: 1.5 * PdfPageFormat.cm),
      crossAxisAlignment: CrossAxisAlignment.start,
      header: (Context context) {
        if (context.pageNumber == 1) {
          return SizedBox();
        }

        return Container(
            alignment: Alignment.centerRight,
            margin: const EdgeInsets.only(bottom: 3.0 * PdfPageFormat.mm),
            padding: const EdgeInsets.only(bottom: 3.0 * PdfPageFormat.mm),
            decoration: BoxDecoration(
                border:
                Border.all(width: 0.5, color: PdfColors.grey)),
            child: Text('Report',
                style: Theme.of(context)
                    .defaultTextStyle
                    .copyWith(color: PdfColors.grey)));
      },
      footer: (Context context) {
        return Container(
            alignment: Alignment.centerRight,
            margin: const EdgeInsets.only(top: 1.0 * PdfPageFormat.cm),
            child: Text('Page ${context.pageNumber} of ${context.pagesCount}',
                style: Theme.of(context)
                    .defaultTextStyle
                    .copyWith(color: PdfColors.grey)));
      },
      build: (Context context) => <Widget>[
        Header(
            level: 0,
            child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text('Report', textScaleFactor: 2),
                  PdfLogo()
                ])),
        Header(level: 1, text: 'What is Lorem Ipsum?'),
        Paragraph(
            text:
            'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.'),
        Paragraph(
            text:
            'It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using "Content here, content here", making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for "lorem ipsum" will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).'),
        Header(level: 1, text: 'Where does it come from?'),
        Paragraph(
            text:
            'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.'),
        Paragraph(
            text:
            'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.'),
        Padding(padding: const EdgeInsets.all(10)),
        Table.fromTextArray(context: context, data: const <List<String>>[
          <String>['Year', 'Ipsum', 'Lorem'],
          <String>['2000', 'Ipsum 1.0', 'Lorem 1'],
          <String>['2001', 'Ipsum 1.1', 'Lorem 2'],
          <String>['2002', 'Ipsum 1.2', 'Lorem 3'],
          <String>['2003', 'Ipsum 1.3', 'Lorem 4'],
          <String>['2004', 'Ipsum 1.4', 'Lorem 5'],
          <String>['2004', 'Ipsum 1.5', 'Lorem 6'],
          <String>['2006', 'Ipsum 1.6', 'Lorem 7'],
          <String>['2007', 'Ipsum 1.7', 'Lorem 8'],
          <String>['2008', 'Ipsum 1.7', 'Lorem 9'],
        ]),
      ]));
  //save PDF

  final String dir = (await getApplicationDocumentsDirectory()).path;
  final String path = '$dir/report.pdf';
  final File file = File(path);
  
  await file.writeAsBytes(await pdf.save());
  
  material.Navigator.of(context).push(
    material.MaterialPageRoute(
      builder: (_) => PdfViewerPage(path: path),
    ),
  );
}

Se for apenas uma página, você pode usar assim.

     pdf.addPage(Page(
      pageFormat: PdfPageFormat.a4,
      build: (Context context) {
        return Center(
          child: Text("PDF Demo"),
        ); // Center
      }));

Para salvar e abrir o pdf, adicione a seguinte linha de código dentro do reportView. E também importe material.dart para usar o Navigator. Se você instalar os pacotes acima depois de executar o projeto, será necessário executá-lo novamente, pois os pacotes não funcionarão corretamente para o recarregamento ou reinicialização a quente.

final String dir = (await getApplicationDocumentsDirectory()).path;
final String path = '$dir/report.pdf';
final File file = File(path);

await file.writeAsBytes(await pdf.save());

material.Navigator.of(context).push(
  material.MaterialPageRoute(
    builder: (_) => PdfViewerPage(path: path),
  ),
);

Chame a visualização PDF para uma função de clique e veja a visualização. Aplique alterações de conteúdo e alterações de interface do usuário à exibição.

body: Center(
  child: Container(
    margin: const EdgeInsets.only(top: 30),
    height: 40,
    child: ElevatedButton(
      style: ElevatedButton.styleFrom(
        backgroundColor: Colors.blue,
        elevation: 5,
        padding: const EdgeInsets.all(12.0),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(5.0),
        ),
      ),
      child: const Text(
        'Get Report',
        style:
            TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
      ),
      onPressed: () {
        reportView(context);
      },
    ),
  ),
),

Você terá essa visão!!!

Você pode encontrar o código completo no seguinte link.