在go语言中使用GoPDF包把html生成PDF文件示例
Go  /  管理员 发布于 1年前   344
在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)
}
有兴趣的可以一试
原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..路人 在
php中使用hyperf框架调用讯飞星火大模型实现国内版chatgpt功能示例中评论 教程很详细,如果加个前端chatgpt对话页面就完美了..博主 在
科学上网翻墙之v2rayN-Core客户端免费公益节点使用教程中评论 @ mashrdn 多切换几个节点测试,免费ssr是没那么稳..Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号