How to Convert Charts from HTML to PDF: A Step-by-Step Guide
In the digital age, presenting data visually through charts and graphs is common. However, sharing these visualizations can sometimes be challenging, especially when you need to convert HTML content, including charts, into a PDF format.
This guide will walk you through the process using UniDoc’s UniHTML and UniPDF tools, ensuring your charts are accurately rendered in a PDF.
Prerequisites
Before diving into the conversion process, ensure you have the following:
- UniDoc API Key: Obtain your API key from your UniCloud account. This key is essential for using the UniPDF SDK.
- UniPDF SDK Setup: If this is your first time using the UniPDF SDK.
- UniHTML Server: Set up a UniHTML server.
Step 1: Clone the Project Repository
First, clone the examples repository provided by UniDoc. This repository contains the necessary Go code and examples for this guide.
git clone [email protected]:unidoc/unihtml-examples.git
Navigate to the graph
folder within the cloned repository:
cd unihtml-examples/graph
Step 2: Understand the Code Structure
Here’s the main Go code you will work with, which includes importing necessary libraries and defining the main function:
package main
import (
"fmt"
"os"
"github.com/unidoc/unihtml"
"github.com/unidoc/unihtml/selector"
"github.com/unidoc/unipdf/v3/common/license"
)
func init() {
// Load your metered License API key
err := license.SetMeteredKey(os.Getenv(`UNIDOC_LICENSE_API_KEY`))
if err != nil {
panic(err)
}
}
func main() {
if len(os.Args) != 2 {
fmt.Println("Err: provided invalid arguments. No UniHTML server path provided")
os.Exit(1)
}
// Establish connection with the UniHTML Server
if err := unihtml.Connect(os.Args[1]);
err != nil {
fmt.Printf("Err: Connect failed: %v\n", err)
os.Exit(1)
}
// Read the content of the graph.html file
htmlDocument, err := unihtml.NewDocument("graph.html")
if err != nil {
fmt.Printf("Err: NewDocument failed: %v\n", err)
os.Exit(1)
}
// Wait for the highcharts-root class nodes to be visible before rendering the PDF
htmlDocument.WaitVisible(".highcharts-root", selector.ByQueryAll)
// Write the result to a PDF file
if err = htmlDocument.WriteToFile("graph.pdf");
err != nil {
fmt.Printf("Err: %v\n", err)
os.Exit(1)
}
}
Step 3: Set Up Your Environment
Ensure you have Go installed on your system. Follow the official Go installation guide if you haven’t installed it yet.
Step 4: Running the UniHTML Server
To convert your HTML with graphs to PDF, you need to have the UniHTML server running. If you are unsure how to start the server, check out this guide.
Run the server using the following command (replace <server address>
with your actual server address, e.g., localhost:8080
if running locally):
go run graph.go <server address>
This command will generate a PDF file named graph.pdf
from the graph.html
file.
Detailed Code Breakdown
1. Initialization and License Key Setup:
func init() {
err := license.SetMeteredKey(os.Getenv(`UNIDOC_LICENSE_API_KEY`))
if err != nil {
panic(err)
}
}
Ensure your API key is correctly set up to authenticate your usage of UniDoc’s services.
2. Connecting to the UniHTML Server:
if err := unihtml.Connect(os.Args[1]); err != nil {
fmt.Printf("Err: Connect failed: %v\n", err)
os.Exit(1)
}
This establishes a connection to the UniHTML server.
3. Reading the HTML File:
htmlDocument, err := unihtml.NewDocument("graph.html")
if err != nil {
fmt.Printf("Err: NewDocument failed: %v\n", err)
os.Exit(1)
}
The code reads the content of the graph.html
file to prepare it for conversion.
4. Waiting for the Chart to Render:
htmlDocument.WaitVisible(".highcharts-root", selector.ByQueryAll)
This method ensures that the necessary content (in this case, elements with the class highcharts-root
) is fully loaded and visible before rendering the PDF.
5. Writing to PDF:
if err = htmlDocument.WriteToFile("graph.pdf"); err != nil {
fmt.Printf("Err: %v\n", err)
os.Exit(1)
}
Finally, the document is written to a PDF file named graph.pdf
.
Explore further insights here:
- Integrating Charts and Graphs into PDFs using Golang PDF Library.
- Create a PDF Report with Charts and Graphs in Golang.
Final Thoughts:
By following these steps, you can efficiently convert HTML content, including complex charts, into a well-formatted PDF document. This guide utilizes UniDoc’s powerful UniHTML and UniPDF libraries, ensuring high-quality and accurate conversions.