Articles in this section
Category / Section

How to export a Barcode generator as a pdf (SfBarcodeGenerator) ?

6 mins read

You can export the Syncfusion® Flutter Barcodes as a PDF document using the Syncfusion® Flutter PDF library.

 

The following steps explain how to export SfBarcodeGenerator widget as a PDF document.

 

Step 1: Create a new Flutter application project and add the following dependencies in the pubspec.yaml file to import the necessary packages for the application.

dependencies:
  syncfusion_flutter_barcodes: ^19.3.54
  syncfusion_flutter_pdf: ^19.3.54-beta

 

Step 2: Import the syncfusion_flutter_pdf, syncfusion_flutter_barcodes and other necessary dart libraries in the main.dart file.

/// Dart import
import 'dart:async';
import 'dart:io';
import 'dart:ui' as dart_ui;
 
/// Barcode import
import 'package:syncfusion_flutter_barcodes/barcodes.dart';
 
/// Pdf import
import 'package:syncfusion_flutter_pdf/pdf.dart';

 

Step 3: Create a new StatefulWidget class (say Barcode) in which the SfBarcodeGenerator widget is to be rendered and also create a global key for it using its state class. In the build method, wrap the SfBarcodeGenerator widget inside the RepainBoundary widget so that it will be helpful to get the barcode from the context as RenderRepaintBoundary object and use it to convert the rendered barcode code to image before exporting to PDF using the toImage method of RenderRepaintBoundary class.

// Global key for Barcode class
final GlobalKey<_BarcodeState > barcodeKey = GlobalKey();
 
// Barcode class to render barcode using SfBarcodeGenerator
class Barcode extends StatefulWidget {
  const Barcode({Key? key}) : super(key: key);
 
  @override
  _BarcodeState createState() => _BarcodeState();
}
 
class _ BarcodeState extends State<Barcode> {
  @override
  Widget build(BuildContext context) {
    return RepaintBoundary(
         /// Rendered a barcode using the SfBarcodeGenerator widget
        child: SfBarcodeGenerator(
            value: 'CODE128',
            showValue: true,
            symbology: Code128(module: 2)
        )
    );
  }
}

 

Step 4: Create a method named convertToImage method which will convert the rendered barcode obtained through findRenderObject method from the context to image using the toImage() method of the RenderRepaintBoundary class.

Future<dart_ui.Image> convertToImage({double pixelRatio = 1.0}) async {
    // Get the render object from context and store in the RenderRepaintBoundary object.
    final RenderRepaintBoundary boundary = context.findRenderObject()
        as RenderRepaintBoundary; 
 
    // Convert the repaint boundary as image
    final dart_ui.Image image =
        await boundary.toImage(pixelRatio: pixelRatio); 
 
    return image;
  }

 

Step 5: Create a new StatefulWidget class (say ExportBarcode) and in its build method, add the following code to render a simple Icon button which exports the rendered barcode as PDF document.

///Class to render the barcode along with a button to export as PDF document.
class ExportBarcode extends StatefulWidget {
  const ExportBarcode({Key? key}) : super(key: key);
 
  @override
  _ExportBarcodeState createState() => _ExportBarcodeState();
}
 
class _ExportBarcodeState extends State<ExportBarcode> {
  _ExportBarcodeState();
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Flutter Barcode Export'),
        ),
        body: Center(
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  SizedBox(
                    height: 300,
                    width: 300,
                    child: Barcode(
                      key: barcodeKey,
                    ),
                  ),
                  const SizedBox(
                    height: 100,
                  ),
                  Container(
                      width: 110,
                      color: Colors.green,
                      child: IconButton(
                        onPressed: () {
                          /// Snackbar messenger to indicate that the rendered barcode is being exported as PDF
                          ScaffoldMessenger.of(context)
                              .showSnackBar(const SnackBar(
                            behavior: SnackBarBehavior.floating,
                            duration: Duration(milliseconds: 2000),
                            shape: RoundedRectangleBorder(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(5))),
                            content:
                                Text('Barcode is being exported as PDF document'),
                          ));
                          _renderPdf();
                        },
                        icon: Row(
                          children: const <Widget>[
                            Icon(Icons.picture_as_pdf, color: Colors.black),
                            Text('Export to pdf'),
                          ],
                        ),
                      )),
                ]),
          ),
        ));
  }
}

 

Step 6: Add the following code to _renderPdf method to perform pdf export operation of rendered barcode on button clicked.

Future<void> _renderPdf() async {
    // Create a new PDF document.
    final PdfDocument document = PdfDocument();
    // Create a pdf bitmap for the rendered barcode image.
    final PdfBitmap bitmap = PdfBitmap(await _readImageData());
    // set the necessary page settings for the pdf document such as margin, size etc..
    document.pageSettings.margins.all = 0;
    document.pageSettings.size =
        Size(bitmap.width.toDouble(), bitmap.height.toDouble());
    // Create a PdfPage page object and assign the pdf document's pages to it.
    final PdfPage page = document.pages.add();
    // Retrieve the pdf page client size
    final Size pageSize = page.getClientSize();
    // Draw an image into graphics using the bitmap.
    page.graphics.drawImage(
        bitmap, Rect.fromLTWH(0, 0, pageSize.width, pageSize.height));
 
    // Snackbar indication for barcode export operation
    ScaffoldMessenger.of(context).hideCurrentSnackBar();
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
      behavior: SnackBarBehavior.floating,
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(5))),
      duration: Duration(milliseconds: 200),
      content: Text('Barcode has been exported as PDF document.'),
    ));
    //Save and dispose the document.
    final List<int> bytes = document.save();
    document.dispose();
}

 

Step 7: Include the following code in the _readImageData method to read the rendered barcode’s image generated using its toImage method and return the image data as list of bytes for further processing.

/// Method to read the rendered barcode image and return the image data for processing.  Future<List<int>> _readImageData() async {
    // Called the convertToImage method to retrieve the rendered barcode image using its key.
    final dart_ui.Image data =
        await barcodeKey.currentState!.convertToImage(pixelRatio: 3.0);
    final ByteData? bytes =
        await data.toByteData(format: dart_ui.ImageByteFormat.png);
    return bytes!.buffer.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes);
  }

 

Step 8: Follow the steps to save and launch the generated PDF file.

  8.1: Add the following dependencies in your pubspec.yaml file.

path_provider: ^2.0.1
open_file: ^3.1.0 #Open source library to launch the PDF file in mobile devices

 

  8.2: Import the following packages in your main.dart file.

/// Path provider library import
import 'package:path_provider/path_provider.dart';
/// open file library import
import 'package:open_file/open_file.dart';

 

  8.3: Append the following code in the _renderPdf method to open the generated PDF document in the   mobile’s default application (any PDF Viewer).

   //Get the external storage directory.
    Directory directory = (await getApplicationDocumentsDirectory());
    //Get the directory path.
    String path = directory.path;
    //Create an empty file to write the PDF data.
    File file = File('$path/output.pdf');
    //Write the PDF data.
    await file.writeAsBytes(bytes, flush: true);
    //Open the PDF document on mobile.
    OpenFile.open('$path/output.pdf');

 

Thus, on clicking the PDF export button, the SfBarcodeGenerator widget will get exported as a PDF document.

 

Barcode pdf export

 

View the sample in GitHub

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied