Created
May 29, 2023 07:38
-
-
Save azamss/4c0dbea4c7c79af97f54e827f7a8ff5d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pdf := fpdf.New("P", "mm", "A4", "") | |
type countryType struct { | |
nameStr, capitalStr, areaStr, popStr string | |
} | |
countryList := make([]countryType, 0, 8) | |
header := []string{"Country", "Capital", "Area (sq km)", "Pop. (thousands)"} | |
template := pdf.CreateTemplate(func(tpl *fpdf.Tpl) { | |
tpl.Image(example.ImageFile("logo.png"), 6, 6, 30, 0, false, "", 0, "") | |
tpl.SetFont("Arial", "B", 16) | |
loadData := func(fileStr string) { | |
fl, err := os.Open(fileStr) | |
if err == nil { | |
scanner := bufio.NewScanner(fl) | |
var c countryType | |
for scanner.Scan() { | |
// Austria;Vienna;83859;8075 | |
lineStr := scanner.Text() | |
list := strings.Split(lineStr, ";") | |
if len(list) == 4 { | |
c.nameStr = list[0] | |
c.capitalStr = list[1] | |
c.areaStr = list[2] | |
c.popStr = list[3] | |
countryList = append(countryList, c) | |
} else { | |
err = fmt.Errorf("error tokenizing %s", lineStr) | |
} | |
} | |
fl.Close() | |
if len(countryList) == 0 { | |
err = fmt.Errorf("error loading data from %s", fileStr) | |
} | |
} | |
if err != nil { | |
pdf.SetError(err) | |
} | |
} | |
// Simple table | |
basicTable := func() { | |
left := (210.0 - 4*40) / 2 | |
tpl.SetX(left) | |
for _, str := range header { | |
tpl.CellFormat(40, 7, str, "1", 0, "", false, 0, "") | |
} | |
tpl.Ln(-1) | |
for _, c := range countryList { | |
tpl.SetX(left) | |
tpl.CellFormat(40, 6, c.nameStr, "1", 0, "", false, 0, "") | |
tpl.CellFormat(40, 6, c.capitalStr, "1", 0, "", false, 0, "") | |
tpl.CellFormat(40, 6, c.areaStr, "1", 0, "", false, 0, "") | |
tpl.CellFormat(40, 6, c.popStr, "1", 0, "", false, 0, "") | |
tpl.Ln(-1) | |
} | |
} | |
loadData(example.TextFile("./countries.txt")) | |
tpl.SetFont("Arial", "", 14) | |
basicTable() | |
}) | |
pdf.AddPage() | |
pdf.UseTemplate(template) | |
fileStr := example.Filename("Fpdf_CellFormat_tables") | |
err := pdf.OutputFileAndClose(fileStr) | |
example.SummaryCompare(err, fileStr) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment