Cara Cetak Atau Print Menggunakan Flutter

Cara  Cetak Atau Print Menggunakan Flutter

Sobatcoding.com - Cara cetak atau print menggunakan flutter

Pada artikel kali ini kita akan mencoba print atau cetak menggunakan flutter. Berikut langkah-langkahnya

Install Dependencies

Langkah pertama install dulu dependencies print menggunakan command berikut

flutter pub add printing

Import Packages

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

Contoh

void cetakPdf() async {
    final doc = pw.Document();

    doc.addPage(pw.Page(
        pageFormat: PdfPageFormat.a4,
        build: (pw.Context context) {
          return pw.Center(
            child: pw.Text('Hello World'),
          ); // Center
        }));

    await Printing.layoutPdf(
        onLayout: (PdfPageFormat format) async => doc.save());
}

Display Dokumen PDF 

void displayPdf() {
    final doc = pw.Document();

    doc.addPage(pw.Page(
        pageFormat: PdfPageFormat.a4,
        build: (pw.Context context) {
          return pw.Container(
            child: pw.Text('Hello Sir'),
          ); // Center
        }));

    Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => PreviewScreen(doc: doc),
        ));
}

lass PreviewScreen extends StatelessWidget {
  final pw.Document doc;

  const PreviewScreen({
    Key? key,
    required this.doc,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          onPressed: () => Navigator.pop(context),
          icon: const Icon(Icons.arrow_back_outlined),
        ),
        centerTitle: true,
        title: const Text("Preview"),
      ),
      body: PdfPreview(
        build: (format) => doc.save(),
        allowSharing: true,
        allowPrinting: true,
        initialPageFormat: PdfPageFormat.a4,
        pdfFileName: "mydoc.pdf",
      ),
    );
  }
}

 

Contoh Print Invoice PDF Menggunakan Flutter

Future<void> generateInvoice() async {
    final doc = pw.Document();
    final image = await imageFromAssetBundle('assets/images/sobatcoding.png');

    doc.addPage(pw.Page(build: (pw.Context context) {
      return pw.Column(children: [
        pw.Row(
          children: [
            pw.Image(image, width: 100, height: 100),
            pw.SizedBox(width: 15),
            pw.Column(children: [
              pw.Text("sobatcoding.com"),
              pw.Text("Belajar flutter print")
            ])
          ],
        ),
        pw.SizedBox(height: 15),
        pw.Column(children: [
          pw.Row(children: [
              pw.SizedBox(width: 80, child: pw.Text("Invoice", style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(width: 5, child: pw.Text(":", style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(child: pw.Text("KL0121556456", style: const pw.TextStyle(fontSize: 11))),
          ]),
          pw.Row(children: [
              pw.SizedBox(width: 80, child: pw.Text("Tgl", style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(width: 5, child: pw.Text(":", style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(child: pw.Text("23/09/2022 10:35:00", style: const pw.TextStyle(fontSize: 11))),
          ]),
        ]),
        pw.SizedBox(height: 15),
        pw.Column(children: [
          pw.Row(children: [
              pw.SizedBox(width: 150, child: pw.Text("ITEM BRG", style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(width: 50, child: pw.Text("QTY", style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(width: 100, child: pw.Text("HARGA", textAlign: pw.TextAlign.right, style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(width: 100, child: pw.Text("SUBTOTAL", textAlign: pw.TextAlign.right, style: const pw.TextStyle(fontSize: 11))),
          ]),
          pw.Row(children: [
              pw.SizedBox(width: 150, child: pw.Text("MINYAK KY PTH", style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(width: 50, child: pw.Text("1", style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(width: 100, child: pw.Text("13.500", textAlign: pw.TextAlign.right, style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(width: 100, child: pw.Text("13.500", textAlign: pw.TextAlign.right, style: const pw.TextStyle(fontSize: 11))),
          ]),
          pw.Row(children: [
              pw.SizedBox(width: 150, child: pw.Text("KACANG PLONG", style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(width: 50, child: pw.Text("2", style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(width: 100, child: pw.Text("10.500", textAlign: pw.TextAlign.right, style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(width: 100, child: pw.Text("21.000", textAlign: pw.TextAlign.right, style: const pw.TextStyle(fontSize: 11))),
          ]),
          pw.Row(children: [
              pw.SizedBox(width: 300, child: pw.Text("TOTAL", style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(width: 100, child: pw.Text("34.500", textAlign: pw.TextAlign.right, style: const pw.TextStyle(fontSize: 11))),
          ])
        ]),
      ]); // Center
    }));

    await Printing.layoutPdf(
        onLayout: (PdfPageFormat format) async => doc.save());
  }

Untuk full source code adalah sebagai berikut

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

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

class PrintPage extends StatefulWidget {
  const PrintPage({super.key});

  @override
  State<PrintPage> createState() => _PrintPageState();
}

class _PrintPageState extends State<PrintPage> {
  void cetakPdf() async {
    final doc = pw.Document();

    doc.addPage(pw.Page(
        pageFormat: PdfPageFormat.a4,
        build: (pw.Context context) {
          return pw.Center(
            child: pw.Text('Hello World'),
          ); // Center
        }));

    await Printing.layoutPdf(
        onLayout: (PdfPageFormat format) async => doc.save());
  }

  Future<void> generateInvoice() async {
    final doc = pw.Document();
    final image = await imageFromAssetBundle('assets/images/sobatcoding.png');

    doc.addPage(pw.Page(build: (pw.Context context) {
      return pw.Column(children: [
        pw.Row(
          children: [
            pw.Image(image, width: 100, height: 100),
            pw.SizedBox(width: 15),
            pw.Column(children: [
              pw.Text("sobatcoding.com"),
              pw.Text("Belajar flutter print")
            ])
          ],
        ),
        pw.SizedBox(height: 15),
        pw.Column(children: [
          pw.Row(children: [
              pw.SizedBox(width: 80, child: pw.Text("Invoice", style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(width: 5, child: pw.Text(":", style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(child: pw.Text("KL0121556456", style: const pw.TextStyle(fontSize: 11))),
          ]),
          pw.Row(children: [
              pw.SizedBox(width: 80, child: pw.Text("Tgl", style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(width: 5, child: pw.Text(":", style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(child: pw.Text("23/09/2022 10:35:00", style: const pw.TextStyle(fontSize: 11))),
          ]),
        ]),
        pw.SizedBox(height: 15),
        pw.Column(children: [
          pw.Row(children: [
              pw.SizedBox(width: 150, child: pw.Text("ITEM BRG", style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(width: 50, child: pw.Text("QTY", style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(width: 100, child: pw.Text("HARGA", textAlign: pw.TextAlign.right, style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(width: 100, child: pw.Text("SUBTOTAL", textAlign: pw.TextAlign.right, style: const pw.TextStyle(fontSize: 11))),
          ]),
          pw.Row(children: [
              pw.SizedBox(width: 150, child: pw.Text("MINYAK KY PTH", style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(width: 50, child: pw.Text("1", style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(width: 100, child: pw.Text("13.500", textAlign: pw.TextAlign.right, style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(width: 100, child: pw.Text("13.500", textAlign: pw.TextAlign.right, style: const pw.TextStyle(fontSize: 11))),
          ]),
          pw.Row(children: [
              pw.SizedBox(width: 150, child: pw.Text("KACANG PLONG", style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(width: 50, child: pw.Text("2", style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(width: 100, child: pw.Text("10.500", textAlign: pw.TextAlign.right, style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(width: 100, child: pw.Text("21.000", textAlign: pw.TextAlign.right, style: const pw.TextStyle(fontSize: 11))),
          ]),
          pw.Row(children: [
              pw.SizedBox(width: 300, child: pw.Text("TOTAL", style: const pw.TextStyle(fontSize: 11))),
              pw.SizedBox(width: 100, child: pw.Text("34.500", textAlign: pw.TextAlign.right, style: const pw.TextStyle(fontSize: 11))),
          ])
        ]),
      ]); // Center
    }));

    await Printing.layoutPdf(
        onLayout: (PdfPageFormat format) async => doc.save());
  }

  void displayPdf() {
    final doc = pw.Document();

    doc.addPage(pw.Page(
        pageFormat: PdfPageFormat.a4,
        build: (pw.Context context) {
          return pw.Container(
            child: pw.Text('Hello Sir'),
          ); // Center
        }));

    Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => PreviewScreen(doc: doc),
        ));
  }

  void generatePdf() async {
    const title = 'Test PDF';
    await Printing.layoutPdf(onLayout: (format) => _generatePdf(format, title));
  }

  void printExistedPdf() async {
    final pdf = await rootBundle.load('assets/files/test.pdf');
    await Printing.layoutPdf(onLayout: (_) => pdf.buffer.asUint8List());
  }

  Future<Uint8List> _generatePdf(PdfPageFormat format, String title) async {
    final pdf = pw.Document(version: PdfVersion.pdf_1_5, compress: true);
    final font = await PdfGoogleFonts.nunitoExtraLight();

    pdf.addPage(
      pw.Page(
        pageFormat: format,
        build: (context) {
          return pw.Column(
            children: [
              pw.SizedBox(
                width: double.infinity,
                child: pw.FittedBox(
                  child: pw.Text(title, style: pw.TextStyle(font: font)),
                ),
              ),
              pw.SizedBox(height: 20),
              pw.Flexible(child: pw.FlutterLogo())
            ],
          );
        },
      ),
    );

    return pdf.save();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          ElevatedButton(
              onPressed: () {
                cetakPdf();
              },
              child: const Text("Buat & Cetak PDF")),
          const SizedBox(height: 15),
          ElevatedButton(
              onPressed: () {
                generateInvoice();
              },
              child: const Text("Cetak Invoice")),
          const SizedBox(height: 15),
          ElevatedButton(onPressed: () {
            displayPdf();
          }, child: const Text("Display PDF")),
          const SizedBox(height: 15),
          ElevatedButton(
              onPressed: () {
                printExistedPdf();
              },
              child: const Text("Cetak Exist PDF")),
          const SizedBox(height: 15),
          ElevatedButton(
              onPressed: () {
                generatePdf();
              },
              child: const Text("Generate Advanced PDF"))
        ],
      )),
    );
  }
}

class PreviewScreen extends StatelessWidget {
  final pw.Document doc;

  const PreviewScreen({
    Key? key,
    required this.doc,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          onPressed: () => Navigator.pop(context),
          icon: const Icon(Icons.arrow_back_outlined),
        ),
        centerTitle: true,
        title: const Text("Preview"),
      ),
      body: PdfPreview(
        build: (format) => doc.save(),
        allowSharing: true,
        allowPrinting: true,
        initialPageFormat: PdfPageFormat.a4,
        pdfFileName: "mydoc.pdf",
      ),
    );
  }
}

flutter print preview

 

Demikian tutorial kali ini. Semoga bermanfaat.