Skip to content
How to create PDF reports in Golang

How to create PDF reports in Golang

A report is a creator document built out of chapters. c.NewChapter numbers itself, chap.Add collects content under that heading, and drawing the chapter registers both a table of contents line and an outline entry for it.

c := creator.New()
c.AddTOC = true

chap := c.NewChapter("Introduction")

p := c.NewStyledParagraph()
p.SetText("Report body text.")
if err := chap.Add(p); err != nil {
    return err
}

if err := c.Draw(chap); err != nil {
    return err
}

return c.WriteToFile("report.pdf")

AddTOC is false out of creator.New, so a report that wants a contents page has to set it. AddOutlines is true by default, which is why the bookmark tree shows up whether or not you asked for one.

Call order is not output order. The front page and the TOC are generated at the end of Finalize and prepended to the body, so registering c.CreateFrontPage after all your chapters still puts the cover on page 1. Page numbers are only final once that assembly has happened, which is why anything that prints one belongs in the header, footer or page-finalize callback rather than in the drawing code.

chap.Add is typed. It accepts a StyledParagraph, Image, Chart, Table, Division, List, Rectangle, Ellipse, Line, Block, PageBreak or another Chapter, and returns a type check error for anything else.

Full assembly, including cover pages, running headers and custom contents pages, is in the report guides. There is also a longer write-up on the UniDoc blog.

Last updated on