I'm creating a tool that can take a JSON file, and then create a PDF out of it using Go
Here is an example of my JSON:
[{"Name":"Ollie","Age":"25","Comment":"This is my comment"},{"Name":"Amy","Age":"28","Comment":"Another comment"},{"Name":"Joey","Age":"19","Comment":"Comment from Joey"},{"Name":"James","Age":"23","Comment":"James' comment"},{"Name":"Richard","Age":"20","Comment":"Richard has also made 24"}]
I have something that works from using CSV files, but now I want to be able to take JSON files too
The package that i'm using to create the PDFs is gofpdf
One of the issues is that I need to pass the JSON into a struct to read it, the struct has it's own custom type - because i'm using a custom type I can't pass in the values into gofpdf's functions to make the PDF
I simply want to be able to pass the values from my struct (which are declared as strings) as strings in the functions:
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"time"
"github.com/jung-kurt/gofpdf"
)
Here is my struct:
type Person struct {
Name string `json:"Name"`
Age string `json:"Age"`
Comment string `json:"Comment"`
}
func main() {
data, err := ioutil.ReadFile("csv-to-json.json")
if err != nil {
fmt.Println(err)
}
//create variable people which is array of Person structs
var People []Person
//Take the data object (json file) and place into the People array of struct
json.Unmarshal(data, &People)
fmt.Println(People[:])
pdf := NewReport()
pdf = CreateTableJSON(pdf, People[:])
if pdf.Err() {
log.Fatalf("Failed creating PDF report: %s
", pdf.Error())
}
err = SavePDFJSON(pdf)
if err != nil {
log.Fatalf("Cannot save PDF: %s|n", err)
}
}
func CreateTableJSON(pdf *gofpdf.Fpdf, table []Person) *gofpdf.Fpdf {
for _, str := range table {
BELOW IS WHERE I AM STRUGGLING. str needs to be of type string
pdf.CellFormat(20, 7, str, "1", 0, "C", false, 0, "")
pdf.Ln(-1)
}
return pdf
}
//Create function that generates a new pdf report
func NewReport() *gofpdf.Fpdf {
pdf := gofpdf.New("P", "mm", "Letter", "")
pdf.AddPage()
pdf.SetFont("Arial", "B", 28)
pdf.Cell(40, 10, "My title for the PDF (New)!")
pdf.Ln(12)
pdf.SetFont("Arial", "", 11)
pdf.Cell(40, 10, time.Now().Format("Mon Jan 2, 2006"))
pdf.Ln(12)
return pdf
}
func SavePDFJSON(pdf *gofpdf.Fpdf) error {
return pdf.OutputFileAndClose("pdf_from_json.pdf")
}
So i'm able to read the data from the JSON file and print the lines to the console, but I can't use this data in the PDF generation functions since i've had to create a custom types, and the function parameters are expecting strings. Can anyone help me out here? I want the equivalent of this:
pdf.CellFormat(20, 7, **TOSTRING(str)**, "1", 0, "C", false, 0, "")
I've been messing around for about 3 hours now without any luck
Thanks in advance