Make a PDF using golang
Have you ever needed to make a PDF programatically? There's a library for this:
https://github.com/jung-kurt/gofpdf
package main
import (
"fmt"
"github.com/jung-kurt/gofpdf"
)
func main() {
fmt.Println("Running...")
pdf := gofpdf.New("L", "mm", "A4", "")
pdf.AddPage()
pdf.Image("photo1.jpg", 9, 9, 200, 133, false, "", 0, "")
err := pdf.OutputFileAndClose("example.pdf")
if err == nil {
fmt.Println("Done!")
} else {
fmt.Println("Error", err)
}
}
Here we added just 1 photo. But what if we have a directory with many images? Lets add them all.
package main
import (
"fmt"
"io/ioutil"
"github.com/jung-kurt/gofpdf"
)
func main() {
fmt.Println("Running...")
pdf := gofpdf.New("L", "mm", "A4", "")
files, _ := ioutil.ReadDir("images")
for _, file := range files {
pdf.AddPage()
pdf.Image(fmt.Sprintf("images/%s", file.Name()), 9, 9, 200, 133, false, "", 0, "")
}
err := pdf.OutputFileAndClose("example.pdf")
if err == nil {
fmt.Println("Done!")
} else {
fmt.Println("Error", err)
}
}
Now we have a new page for each image in the directory!