Export to PDF in Java

ApexCharts, by default, provides a way to enable users to download individual charts in PNG or SVG by configuring the toolbar. However, when it comes to generating charts on the server, things could become a bit challenging. Imagine you want to write a CRON job to send reports with charts in them, allow users to download PDF reports in the realtime, or send these reports as an attachment to someone else; this is where server-side chart generation becomes essential. We will be learning the same throughout the tutorial. Traditionally when it comes to exporting charts on the server, we use headless browsers like Puppeteer or PhantomJS. But for this tutorial, we will be using FusionExport. Now the obvious question is:

Why FusionExport?

When there is something like Puppeteer or PhantomJS available, why use anything else? Well, you know what happened to PhantomJS – discontinued. On the other hand, FusionExport is a product actively maintained and developed by FusionCharts. Here are a few reasons why we are using FusionExport:
  1. User-friendly APIs: FusionExport provides excellent APIs focused on exporting charts and dashboards, which help you save time as well.
  2. Integrations: It offers SDKs for C#, Java, Node.js, Python, and PHP. So even if your infra doesn’t support Node.js, no need to worry about it!
  3. Support: If you are facing, any issues, you can always reach out to their support team, and you will get the answer in a matter of a few hours.
  4. Documentation: It provides excellent documentation with examples of real-world scenarios as well.
  5. Stability: FusionCharts actively develops FusionExport, and many enterprises around the world use it.
So, let’s go ahead and start with the installation of FusionExport.

Installation of FusionExport

Installation of FusionExport contains two steps:
  1. Setting up the FusionExport server
  2. Installing the SDKs in your project
Setting up the FusionExport server Download FusionExport for the choice of your platform. Once you have downloaded it, unzip the package and open the terminal to run the following command:

./fusionexport
If you are using Windows then open PowerShell and run the following command:

./fusionexport.bat
Once done, your server will start running on the port number 1337 and the console will show messages similar to the screenshot below: Console logs after starting the FusionExport server Installing the Java SDK Create a Gradle project. We have used Eclipse IDE to build a Java Gradle project. The steps to create a Gradle project using eclipse are as follows: On the Menu bar, go to File>New>Other option. A list of languages and frameworks appear, click on the folder Gradle and select the Gradle project and click on next. Give your project a name (eg. myproject) and specify a location for it. In ‘Options’ windows leave the settings default and click on Next. Once the download process is finished, click on Finish. Alternatively, to create a Gradle project without using any specific IDE, you can visit Creating New Gradle Builds page. To use the FusionExport SDK as a part of the Gradle build system, open the build.gradle file of your project and add the following to it: Maven central repository to the repositories list:

repositories {
  mavenCentral()
}
FusionExport Java SDK to the dependency list:

dependencies {
  compile "com.fusioncharts.fusionexport:fusionexport:1.0.0"
  compile group: 'javax.websocket', name: 'javax.websocket-api', version: '1.1'
  compile group: 'org.glassfish.tyrus.bundles', name: 'tyrus-standalone-client', version: '1.13.1'
  compile 'com.google.code.gson:gson:2.8.2'
  compile group: 'org.jsoup', name: 'jsoup', version: '1.7.2'
  compile group: 'org.apache.ant', name: 'ant', version: '1.8.2'
}
Refresh the project, in case the dependencies do not get installed. You can check whether the defined dependencies are installed or not in Project and External Dependencies folder.

Exporting a simple HTML to PDF

Let’s first export a simple HTML snippet to PDF before Apex Charts to give you a brief idea of how it works. Create a new file ApexChartsExport.java inside myproject/src/java/main/myproject/ and include the dependencies:

import com.fusioncharts.fusionexport.client.*; // import sdk

public class ApexChartsExport {
  public static void main(String[] args) throws Exception {
          // Instantiate the ExportConfig class and add the required configurations
          ExportConfig config = new ExportConfig();
          ExportManager manager = new ExportManager();
  }
}
As you can see above, we have imported two modules from fusionexport and instantiated them:
  1. ExportConfig: This is where you will provide all the configurations to FusionExport like file type, template, etc.
  2. ExportManager: Once you have defined the configurations, you will be passing them to ExportManager, which will further take care of exporting.
Let’s create a simple HTML called template.html file in myproject/resources/.

<html>
  <body>
    <h1>Hello World</h1>
  </body>
</html>
Now we define its path and the configurations to export in ApexChartsExport.java file.

String configPath = System.getProperty("user.dir") + "/resources/template.html";
// Provide path of the chart configuration which we have defined above.
// You can also pass the same object as serialized JSON.
config.set("templateFilePath", configPath);

// ++++++ ATTENTION - MODIFY THE EXPORT TYPE ++++++
// OPTIONS ARE: 'png' (default) | 'jpeg' | 'pdf' | 'svg' | 'html' | 'csv' | 'xls' | 'xlsx'
config.set("type", "pdf");
config.set("templateFormat", "A4");
As you can see, we are using three properties to configure:
  1. templateFilePath: This accepts the path of the HTML template which we have created.
  2. type: File format in which you want to export. We are using pdf but you can also use jpgpng and svg.
  3. templateFormat: We are setting the page format to A4. There are 7 more formats supported like A3Letter, etc.
You can check all the available options on FusionExport’s API Reference page Now, let’s export your first page:

// Call the export() method with the export config and the respective callbacks
manager.export(config, ".",  true);
As you can see above, we are passing config to the export method. By default, your exported file will be present inside a zip, hence we set the unzip flag to True so that it will not be zipped. Your final code will like:

package myproject;

import com.fusioncharts.fusionexport.client.*; // import sdk

public class ApexChartsExport {
    public static void main(String[] args) throws Exception {
        String configPath = System.getProperty("user.dir") + "/resources/template.html";

        // Instantiate the ExportConfig class and add the required configurations
        ExportConfig config = new ExportConfig();
        // Provide path of the chart configuration which we have defined above.
        // You can also pass the same object as serialized JSON.
        config.set("templateFilePath", configPath);

        // ++++++ ATTENTION - MODIFY THE EXPORT TYPE ++++++
        // OPTIONS ARE: 'png' (default) | 'jpeg' | 'pdf' | 'svg' | 'html' | 'csv' | 'xls' | 'xlsx'
        config.set("type", "pdf");
        config.set("templateFormat", "A4");
        config.set("asyncCapture", true);

        // Instantiate the ExportManager class
        ExportManager manager = new ExportManager();
        // Call the export() method with the export config and the respective callbacks
        manager.export(config, ".", true);

    }
}
Let’s run this code If the code is executed successfully, it will create a file called export.pdf in the myproject directory. If you open it, then you will get output similar to this in an A4 page format: Output after exporting HTML to PDF

Exporting ApexCharts to PDF

Now that we know how to export a simple HTML file let’s learn how to export ApexCharts. There are three important steps to perform this:
  1. Write an HTML template with JavaScript: Unlike earlier examples, we will be writing not just the HTML but also the JavaScript in the template, which will render the chart.
  2. Set up the configurations: As mentioned, we will be providing the configurations with the template to FusionExport
  3. Export!
Let’s create a simple HTML called template.html which will have the ApexCharts code as well.

<html>
    <body>
        <h1>ApexCharts Demo with FusionExport</h1>
        <div id="chart"></div>
        <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
        <script>
            var options = {
                chart: { type: 'line' },
                series: [{
                    name: 'sales',
                    data: [10,70,40,50,49,60,70,91,125]
                }],
                xaxis: {
                    categories: [1991,1992,1993,1994,1995,1996,1997,1998,1999]
                }
            }
            var chart = new ApexCharts(document.querySelector("#chart"), options);
    
            chart.render();
        </script>
    </body>
</html>
There are a few things happening in the code:
  1. We have added ApexCharts library from CDN
  2. We are rendering a simple line chart in the script tag
  3. Since we won’t be rendering it as a webpage in the browser, we have skipped head and meta tags as well.
If you open this file in a browser, you will find a line chart being rendering with a header on the top. We will be passing this FusionExport with similar configurations mentioned earlier. Behind the scene, FusionExport also comes with a headless browser that will take this template and render it in the headless browser. After this, it will apply various options provided via the configuration, followed by generating the final exported file. Now, let’s go back to ApexChartsExport.java and add the following code to read the HTML template and pass it to FusionExport:

String configPath = System.getProperty("user.dir") + "/resources/template.html";
ExportConfig config = new ExportConfig();
// Provide path of the chart configuration which we have defined above.
// You can also pass the same object as serialized JSON.
config.set("templateFilePath", configPath);
// ++++++ ATTENTION - MODIFY THE EXPORT TYPE ++++++
// OPTIONS ARE: 'png' (default) | 'jpeg' | 'pdf' | 'svg' | 'html' | 'csv' | 'xls' | 'xlsx'
config.set("type", "pdf");
config.set("templateFormat", "A4");
config.set("asyncCapture", true);
  1. We have added a property called asyncCapture which waits till the charts are loaded. It is extremely handy when you have charts with animations.
  2. We have kept the rest of the configurations the same.
Your final code should look like this:

package myproject;

import com.fusioncharts.fusionexport.client.*; // import sdk

public class ApexChartsExport {
public static void main(String[] args) throws Exception {
String configPath = System.getProperty("user.dir") + "/resources/template.html";

        // Instantiate the ExportConfig class and add the required configurations
        ExportConfig config = new ExportConfig();
        // Provide path of the chart configuration which we have defined above.
        // You can also pass the same object as serialized JSON.
        config.set("templateFilePath", configPath);
        // ++++++ ATTENTION - MODIFY THE EXPORT TYPE ++++++
        // OPTIONS ARE: 'png' (default) | 'jpeg' | 'pdf' | 'svg' | 'html' | 'csv' | 'xls' | 'xlsx'
        config.set("type", "pdf");
        config.set("templateFormat", "A4");
       
        config.set("asyncCapture", true);

        // Instantiate the ExportManager class
        ExportManager manager = new ExportManager();
        // Call the export() method with the export config and the respective callbacks
        manager.export(config, ".",  true);
Run the ApexChartsExport.java file as Java application and you will have a file named export.pdf in the myproject the directory which will look like this: Output after exporting HTML to PDF with ApexCharts

Making it pretty

Now that you have exported your first chart. Let’s make it pretty by adding some styles:

body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
    padding: 1em;
}
h1 { text-align: center; }
#chart { margin-top: 1em; }
We will be adding the above code snippet in the head. In the above code, we are doing the following things:
  1. Replaced the default serif font with system font which means in case of latest macOS, you will see San Fransisco
  2. We have added padding across the page
  3. Made the header center-aligned and added some margin between header and chart
Also, let’s remove the hamburger menu from the chart because it is completely irrelevant in this case.

chart: {
    type: 'line',
    toolbar: { tools: { download: false } }
}
Once, you have made the changes your file will look like this: Output after exporting HTML to PDF with ApexCharts That’s all folks. This is how you export a single chart made in ApexCharts on the server. Feel free to download the source code on Github. If you have any feedback or found any issues, submit an issue on the repository.

What’s next?

Now that you know how to export a single chart, you can similarly add more charts in the PDF. You can even add your CSS to customize the look. Furthermore, you can use a similar way to write CRON jobs to send emails with PDF attachments or even allow users to download dashboards in realtime. For more such demos check our dashboards built with ApexCharts and FusionExport.