Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create pdf from html in golang

How to create PDF files from an HTML input in Google Go? If it is not possible yet, are there any initations that aims to solve this problem?

I'm looking for a solution like TCPDF in php.

like image 260
mimrock Avatar asked Feb 17 '13 16:02

mimrock


3 Answers

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

It seems like you are looking for.

like image 152
Juan de Parras Avatar answered Nov 11 '22 10:11

Juan de Parras


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.

like image 26
muthukumar selvaraj Avatar answered Nov 11 '22 10:11

muthukumar selvaraj


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

like image 7
damonkelley Avatar answered Nov 11 '22 08:11

damonkelley