go-wkhtmltopdf icon indicating copy to clipboard operation
go-wkhtmltopdf copied to clipboard

Creating PDF files in a loop

Open zaky opened this issue 1 year ago • 4 comments

func main() { for _, v := range []string{"import1.pdf", "import2.pdf", "import3.pdf"} { CreatePDFFile("header.html", "footer.html", "content.html", v) } }

func CreatePDFFile(header, footer, content, output string) error { // Initialize library. if err := pdf.Init(); err != nil { log.Print("fail init", err)

	return err
}
defer pdf.Destroy()
//Insert the content inside the template
// Create object from URL.
object, err := pdf.NewObject(content)
if err != nil {
	log.Print("fail new object", err)
	return err
}
defer object.Destroy()
object.Header.CustomLocation = header
object.Footer.CustomLocation = footer
converter, err = pdf.NewConverter()
if err != nil {
	log.Print("fail new converter", err)
	return err
}

defer converter.Destroy()

converter.PaperSize = pdf.Letter

// Add created objects to the converter.
converter.Add(object)

// Convert objects and save the output PDF document.
outFile, err := os.Create(output)
if err != nil {
	log.Print("fail create", err)
	return err
}
defer outFile.Close()

// Run converter.
if err := converter.Run(outFile); err != nil {
	log.Print("fail run", err)
	return err
}
return nil

}

Runing this code will create 1 valid file, the first one and two invalid files.

zaky avatar Jul 04 '23 17:07 zaky