在go语言中使用GoPDF包把html生成PDF文件示例
在Go语言中也有挺多的GoPDF包用来html转pdf的,我这里就列出两个,比如
https://github.com/signintech/gopdf;
bitbucket.org/zombiezen/gopdf/pdf;
...
ps:
注意无法渲染HTML代码,需要自行处理
下面我使用bitbucket.org/zombiezen/gopdf/pdf包把html生成pdf
示例代码:
package main
import (
"bitbucket.org/zombiezen/gopdf/pdf"
"fmt"
"net/http"
"os"
)
func Home(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(fmt.Sprintf("<html><body><form action='http://localhost:8080/pdf' method='post'><input type='submit' value='Generate PDF'></form></body></html>")))
}
func PDF(w http.ResponseWriter, r *http.Request) {
doc := pdf.New()
canvas := doc.NewPage(pdf.A4Width, pdf.A4Height)
canvas.Translate(100, 100)
path := new(pdf.Path)
path.Move(pdf.Point{0, 0})
path.Line(pdf.Point{100, 0})
canvas.Stroke(path)
text := new(pdf.Text)
text.SetFont(pdf.Helvetica, 14)
text.Text("Hello, World!")
canvas.DrawText(text)
text2 := new(pdf.Text)
//text.SetFont(pdf.Helvetica, 14)
html := "<html><body><h1>Receipt #0001</h2><br><br><h2>Issue to You!</h2></body></html>"
text2.Text(html) // will not render ya
canvas.DrawText(text2)
canvas.Close()
//直接下载到浏览器
w.Header().Set("Content-type", "application/pdf")
err := doc.Encode(w)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
//在网络服务器上保存一个副本
pdfFile, err := os.Create("x.pdf")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
doc.Encode(pdfFile)
fmt.Println("保存至 x.pdf...")
w.Write([]byte("PDF Generated"))
}
func main() {
// http.Handler
mux := http.NewServeMux()
mux.HandleFunc("/", Home)
mux.HandleFunc("/pdf", PDF)
http.ListenAndServe(":8080", mux)
}
有兴趣的可以一试
相关文章