Articles in this section
Category / Section

How to export Flutter Spark bar charts as a pdf (SfSparkBarChart)?

4 mins read

)(aFlutter You can export the Syncfusion Flutter Spark Chart as a PDF document using the Syncfusion Flutter PDF library.

 

The following steps explain how to export the SfSparkBarChart 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_charts: ^19.3.48
  syncfusion_flutter_pdf: ^19.3.48-beta

 

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

/// Dart import
import 'dart:async';
import 'dart:io';
import 'dart:ui' as dart_ui;
 
/// Chart import
import 'package:syncfusion_flutter_charts/sparkcharts.dart';
 
/// Pdf import
import 'package:syncfusion_flutter_pdf/pdf.dart';

 

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

// Global key for SparkBarChart class
final GlobalKey<_SparkBarChartState> chartKey = GlobalKey();
 
// SparkBarChart class to render the SfSparkBarChart
class SparkBarChart extends StatefulWidget {
  const SparkBarChart({Key? key}) : super(key: key);
 
  @override
  _SparkBarChartState createState() => _SparkBarChartState();
}
 
class _SparkBarChartState extends State<SparkBarChart> {
  @override
  Widget build(BuildContext context) {
    return RepaintBoundary(
      child: SfSparkBarChart(
        axisLineWidth: 0,
        data: const <double>[ 
             5, 6, 5, 7, 4, 3, 9, 5, 6, 5, 7, 8, 4, 5, 3, 4, 11, 10, 2, 12, 4, 7,  6, 8
        ],
        highPointColor: Colors.red,
        lowPointColor: Colors.red,
        firstPointColor: Colors.orange,
        lastPointColor: Colors.orange,
      ),
    );
  }

 

Step 4: Create a method named convertToImage which will convert the rendered Spark bar chart obtained 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 ExportSparkChart) and in its build method, add the following code to render a simple Icon button which exports the Spark bar chart as PDF document in its onPressed event.

///Class to render the Spark bar chart along with a button to export as PDF document.
class ExportSparkChart extends StatefulWidget {
  const ExportSparkChart({Key? key}) : super(key: key);
 
  @override
  _ExportSparkChartState createState() => _ExportSparkChartState();
}
 
class _ExportSparkChartState extends State<ExportSparkChart> {
  _ExportSparkChartState();
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Flutter Spark Chart Export'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
            Expanded(
                // Renders the SfSparkBarChart
                child: SparkBarChart(
                    // set the key for the SparkBarChart class
                    key: chartKey,
                )
            ),
            const SizedBox(
              height: 50,
            ),
            Container(
                width: 110,
                color: Colors.green,
                child: IconButton(
                  onPressed: () {
                    // Snackbar messenger to indicate that the spark chart 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('Spark Chart is being exported as PDF document'),
                    ));
                    /// Method which perform the pdf export operation
                    _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 spark bar chart on button clicked.

Future<void> _renderPdf() async {
    // Create a new PDF document.
    final PdfDocument document = PdfDocument();
    // Create a pdf bitmap for the rendered spark chart 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 chart 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('Spark Chart 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 spark bar chart’s image generated using its toImage method and return the image data as list of bytes for further processing.

/// Method to read the rendered spark bar chart image and return the image data for processing.
  Future<List<int>> _readImageData() async {
    // Called the convertToImage method to retrieve the rendered spark bar chart image using its key.
    final dart_ui.Image data =
        await chartKey.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 rendered Spark bar chart will get exported as a PDF document.

 

Chart, bar chart, histogram

Description automatically generated

 

View the sample in GitHub

Conclusion
I hope you enjoyed learning about
 how to export Flutter Spark bar chart as a pdf (SfSparkBarChart).

You can refer to our Flutter Spark bar feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Flutter Spark bar example to understand how to create and manipulate data.

For current customers, you can check out our Document Processing Libraries from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-trac, or feedback portal. We are always happy to assist you!

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