Create pdf from html in golang

There is also this package wkhtmltopdf-go, which uses the libwkhtmltox library. I am not sure how stable it is though.


Installation

go get -u github.com/SebastiaanKlippert/go-wkhtmltopdf

go version go1.9.2 linux/amd64

code

   import (
        "fmt"
        "strings"
        wkhtml "github.com/SebastiaanKlippert/go-wkhtmltopdf"
    )  
    
      func main(){
                 pdfg, err :=  wkhtml.NewPDFGenerator()
               if err != nil{
                  return
              }
              htmlStr := `<html><body><h1 style="color:red;">This is an html
 from pdf to test color<h1><img src="http://api.qrserver.com/v1/create-qr-
code/?data=HelloWorld" alt="img" height="42" width="42"></img></body></html>`
            
              pdfg.AddPage(wkhtml.NewPageReader(strings.NewReader(htmlStr)))
            
   
              // Create PDF document in internal buffer
              err = pdfg.Create()
              if err != nil {
                  log.Fatal(err)
              }
            
               //Your Pdf Name
               err = pdfg.WriteFile("./Your_pdfname.pdf")
              if err != nil {
                  log.Fatal(err)
              }
            
              fmt.Println("Done")
        }

The Above code Works for Converting html to pdf in golang with proper background image and Embedded Css Style Tags

Check repo

See Pull request Documentation Improved

Recommendations (from https://wkhtmltopdf.org/status.html) :

Do not use wkhtmltopdf with any untrusted HTML – be sure to sanitize any user-supplied HTML/JS, otherwise it can lead to complete takeover of the server it is running on! Please consider using a Mandatory Access Control system like AppArmor or SELinux, see recommended AppArmor policy.

If you’re using it for report generation (i.e. with HTML you control), also consider using WeasyPrint or the commercial tool Prince – note that I’m not affiliated with either project, and do your diligence.

If you’re using it to convert a site which uses dynamic JS, consider using puppeteer or one of the many wrappers it has.


what about gopdf (https://github.com/signintech/gopdf).

It seems like you are looking for.


I don't think I understand your requirements. Since HTML is a markup language, it needs context to render (CSS and a screen size). Existing implementations I've seen generally open the page in a headless browser and create a PDF that way.

Personally, I would just use an existing package and shell out from Go. This one looks good; it's even recommended in this answer.

If you're really determined to implement it all in Go, check out this WebKit wrapper. I'm not sure what you'd use for generating PDFs, but but at least it's a start.