go-pdf / fpdf

A PDF document generator with high level support for text, drawing and images
MIT License
548 stars 48 forks source link

Generating PDF through an html template #57

Open sumit-popclub opened 8 months ago

sumit-popclub commented 8 months ago

I have a html template in which I will render data on the runtime and want to generate a pdf out of it. Is there any way I can do that using go fpdf.

this is my code

func usingGoFPDF() {
    now := time.Now()

    tmpl, err := template.ParseFiles(templateFileName)
    if err != nil {
        log.Fatalf("could not parse template: %v", err)
    }

    fmt.Println("template parsed", time.Since(now))

    var result bytes.Buffer

    data := AadharDetails{
        PhotoSrc:      "photo.jpg",
        FormId:        "1234567890",
        AadhaarNumber: "1234 5678 9012",
        FirstName:     "John",
        FatherName:    "Doe",
        DOB:           "01-01-2000",
        ContactPerson: "John Doe",
        Gender:        "Male",
        MobileNumber:  "1234567890",
        EmailId:       "v@gmail.com",
        Address:       "123, XYZ Street, ABC City, DEF State, 123456",
        HouseNo:       "123",
        Landmark:      "Near ABC",
        City:          "ABC",
        Street:        "XYZ",
        PostOffice:    "DEF",
        District:      "GHI",
        SubDistrict:   "JKL",
        State:         "MNO",
        Pincode:       "123456",
        Country:       "India",
    }

    fmt.Println("data set", time.Since(now))

    err = tmpl.Execute(&result, data)
    if err != nil {
        log.Fatalf("could not execute template: %v", err)
    }

    fmt.Println("template executed", time.Since(now))

    htmlData := result.String()

    // Create a PDF document
    pdf := fpdf.New("P", "mm", "A4", "")

    // Add a new page
    pdf.AddPage()

    fmt.Println(htmlData)
    pdf.Write(1.2, htmlData)

    err = pdf.OutputFileAndClose("output.pdf")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Time taken:", time.Since(now))
    fmt.Println("PDF generated successfully:", "output.pdf")

}

It's breaking with the error - panic: runtime error: index out of range [60] with length 0

sbinet commented 7 months ago

apologies for the belated answer.

do you have an as simple as possible reproducer ? (so I could play a bit with that ?)

PylotLight commented 4 months ago

apologies for the belated answer.

do you have an as simple as possible reproducer ? (so I could play a bit with that ?)

Any html page will do.. I am also searching for a weasyprint(python) replacement in Go.