在go语言中使用GoPDF包把html生成PDF文件示例
Go  /  管理员 发布于 2个月前   105
在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)
}
有兴趣的可以一试
博主 在
2023年国务院办公厅春节放假通知:1月21日起休7天中评论 @ xiaoB 你只管努力,剩下的叫给天意;天若有情天亦老,..xiaoB 在
2023年国务院办公厅春节放假通知:1月21日起休7天中评论 会不会春节放假后又阳一次?..BUG4 在
你翻墙过吗?国内使用vpn翻墙可能会被网警抓,你需了解的事中评论 不是吧?..博主 在
go语言+beego框架中获取get,post请求的所有参数中评论 @ t1 直接在router.go文件中配就ok..Jade 在
如何在MySQL查询中获得当月记录中评论 Dear zongscan.com team, We can skyroc..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号