在go語言中使用github.com/signintech/gopdf實(shí)現(xiàn)生成pdf文件功能
Go  /  管理員 發(fā)布于 4個(gè)月前   462
最近公司項(xiàng)目中有需求:實(shí)現(xiàn)支付訂單時(shí)根據(jù)訂單數(shù)據(jù)形成pdf文件并以郵件附件方式發(fā)送給下單客戶;
這段時(shí)間項(xiàng)目有點(diǎn)忙,轉(zhuǎn)go后很久都沒有寫技術(shù)博客了, 博客的谷歌廣告也少的可憐!
快到下班點(diǎn)了, 廢話不多說 直接放代碼:
根據(jù)訂單id生成pdf文件, 里面包括讀取數(shù)據(jù)庫表單數(shù)據(jù)
\utils\goodstech\pdf.go
package goodstech
import (
"fmt"
"log"
"strconv"
"time"
"zongscan-go/model"
"zongscan-go/service"
"zongscan-go/utils"
"github.com/signintech/gopdf"
)
// 生成pdf ( 發(fā)送訂單郵件附件模板)
func GeneratePdf(orderid uint) (string, error) {
pdf := gopdf.GoPdf{}
pdf.Start(gopdf.Config{PageSize: *gopdf.PageSizeA3})
pdf.AddPage()
err := pdf.AddTTFFont("wts11", "./resource/static/arial.ttf")
if err != nil {
log.Print(err.Error())
return "", err
}
err = pdf.SetFont("wts11", "", 13)
if err != nil {
log.Print(err.Error())
return "", err
}
//查詢數(shù)據(jù)庫,用表格顯示數(shù)據(jù)
oservice := service.NewOrderService()
order := model.Order{}
order.ID = orderid
err = oservice.GetById(&order)
if err != nil {
return "orderpdf", nil
}
//pdf.SetTextColor(0x00, 0x00, 0xff)
//添加表格的標(biāo)題
pdf.SetX(50)
pdf.SetY(50)
//居中Center
alignOption := gopdf.CellOption{Align: gopdf.Center | gopdf.Middle, Border: gopdf.Left | gopdf.Right | gopdf.Bottom | gopdf.Top}
//右對(duì)齊Right
rightOption := gopdf.CellOption{Align: gopdf.Right | gopdf.Middle, Border: gopdf.Left | gopdf.Right | gopdf.Bottom | gopdf.Top}
//左對(duì)齊
leftOption := gopdf.CellOption{Align: gopdf.Left | gopdf.Middle, Border: gopdf.Left | gopdf.Right | gopdf.Bottom | gopdf.Top}
pdf.CellWithOption(&gopdf.Rect{
W: 650,
H: 30,
}, "xxx Co., Ltd ", rightOption)
pdf.SetX(50)
pdf.SetY(80)
pdf.CellWithOption(&gopdf.Rect{
W: 650,
H: 30,
}, "Order details information", alignOption)
pdf.SetX(50)
pdf.SetY(110)
pdf.CellWithOption(&gopdf.Rect{
W: 650,
H: 30,
}, " Order No.: "+*order.OrderNo, leftOption)
pdf.SetX(50)
pdf.SetY(140)
pdf.CellWithOption(&gopdf.Rect{
W: 650,
H: 30,
}, " Consignee: "+*order.Consignee+" Email: "+*order.Email+" Phone: "+order.User.PhoneCode+"-"+order.User.Mobile, leftOption)
pdf.SetX(50)
pdf.SetY(170)
pdf.CellWithOption(&gopdf.Rect{
W: 650,
H: 30,
}, " Address: "+*order.Detail, leftOption)
// 使用 time.Unix 創(chuàng)建 time.Time 對(duì)象
tdate := time.Unix(int64(order.CreatedAt), 0)
pdf.SetX(50)
pdf.SetY(200)
pdf.CellWithOption(&gopdf.Rect{
W: 650,
H: 30,
}, "Date: "+utils.TimeFormatStr(&tdate)+" ", rightOption)
pdf.SetX(50)
pdf.SetY(230)
pdf.CellWithOption(&gopdf.Rect{
W: 650,
H: 30,
}, " Sub order list", leftOption)
//設(shè)置表格表頭的字體
err = pdf.SetFont("wts11", "", 12)
//pdf.SetTextColor(0xa8, 0xa8, 0xa8)
if err != nil {
log.Print(err.Error())
return "", err
}
//生成表格的表頭
pdf.SetX(50)
pdf.SetY(260)
pdf.CellWithOption(&gopdf.Rect{
W: 250,
H: 40,
}, " Describe", leftOption)
pdf.SetX(300)
pdf.SetY(260)
pdf.CellWithOption(&gopdf.Rect{
W: 50,
H: 40,
}, " Quantity", leftOption)
pdf.SetX(350)
pdf.SetY(260)
pdf.CellWithOption(&gopdf.Rect{
W: 200,
H: 40,
}, " Image", leftOption)
pdf.SetX(550)
pdf.SetY(260)
pdf.CellWithOption(&gopdf.Rect{
W: 100,
H: 40,
}, " Price", leftOption)
pdf.SetX(650)
pdf.SetY(260)
pdf.CellWithOption(&gopdf.Rect{
W: 50,
H: 40,
}, " Total", leftOption)
//生成表格的內(nèi)容
//pdf.SetTextColor(0x00, 0x00, 0x00)
//得到商品列表
var newcurY float64
for i, v := range order.OrderList {
curY := 300 + i*50
pdf.SetX(50)
pdf.SetY(float64(curY))
// pdf.CellWithOption(&gopdf.Rect{
// W: 250,
// H: 40,
// }, " "+*v.ProductName+" "+*v.SpData, leftOption)
//pdf.MultiCell(&gopdf.Rect{W: 250, H: 50}, text)
//數(shù)據(jù)轉(zhuǎn)換 1:Way 101陸運(yùn),201海運(yùn),301空運(yùn) 2:WayMode 101cmb|201weight 計(jì)算
text := " " + *v.ProductName + " " + *v.SpData
if *v.LogisticsPriceId > 0 {
text = " Logistics CBM:" + fmt.Sprintf("%.2f", v.Cbm) + " Weight:" + fmt.Sprintf("%.2f", v.Weight)
}
pdf.MultiCellWithOption(&gopdf.Rect{W: 250, H: 50}, text, gopdf.CellOption{Align: gopdf.Center | gopdf.Middle, Border: gopdf.Left | 0 | 0 | 0})
pdf.SetX(300)
pdf.SetY(float64(curY))
pdf.CellWithOption(&gopdf.Rect{
W: 50,
H: 50,
}, " "+strconv.Itoa(int(v.PCS)), leftOption)
// //一個(gè)圖片的字節(jié)數(shù)組 //?x-oss-process=style/w128 //?x-oss-process=image/resize,p_50
// imageBytes, _, _ := utils.FetchImageAsByte("https://oss.zongscan.com/image/3e33601b487fbb3e7896637a3ca6d419.jpeg?x-oss-process=style/w128")
// // 解碼圖像
// img, _, err := image.Decode(ioutil.NopCloser(bytes.NewReader(imageBytes)))
// if err != nil {
// log.Fatalf("Failed to decode image: %v", err)
// }
// pdf.ImageFrom(img, 350, float64(curY), &gopdf.Rect{W: 80, H: 40})
//下載圖片
pathimg, _ := utils.DownloadToOSS(*v.ProductImg + "?x-oss-process=style/w128")
pdf.Image("./captcha/"+pathimg, 350+5, float64(curY)+5, &gopdf.Rect{W: 60, H: 40}) //print image
fmt.Println("i:", i, *v.ProductImg, "pathimg:", pathimg)
pdf.SetX(550)
pdf.SetY(float64(curY))
pdf.CellWithOption(&gopdf.Rect{
W: 100,
H: 50,
}, " "+fmt.Sprintf("%.2f", float64(v.Price)/100), leftOption)
pdf.SetX(650)
pdf.SetY(float64(curY))
pdf.CellWithOption(&gopdf.Rect{
W: 50,
H: 50,
}, " "+fmt.Sprintf("%.2f", float64(v.Total)/100), leftOption)
//表格尾部高度
newcurY = float64(curY)
}
//尾部
pdf.SetX(50)
pdf.SetY(newcurY + 50)
pdf.CellWithOption(&gopdf.Rect{
W: 650,
H: 30,
}, "Total "+order.OrderList[0].CurrencyTo+" : "+fmt.Sprintf("%.2f", float64(order.Total)/100)+" ", rightOption)
pdf.SetX(50)
pdf.SetY(newcurY + 50 + 30)
pdf.CellWithOption(&gopdf.Rect{
W: 650,
H: 30,
}, "Tax : 0"+" ", rightOption)
pdf.SetX(50)
pdf.SetY(newcurY + 50 + 30 + 30)
pdf.CellWithOption(&gopdf.Rect{
W: 650,
H: 30,
}, " Contact us - China : [email protected]", leftOption)
pdf.SetX(50)
pdf.SetY(newcurY + 50 + 30 + 30 + 30)
pdf.CellWithOption(&gopdf.Rect{
W: 650,
H: 30,
}, " Address: No. 2505, North Centr", leftOption)
pdf.WritePdf("./captcha/" + *order.OrderNo + ".pdf")
return "scpdf", nil
}
從oss下載圖片
// 下載oss圖片
func DownloadToOSS(imageURL string) (string, error) {
// 解析URL
parsedURL, err := url.Parse(imageURL)
if err != nil {
fmt.Printf("Error parsing the URL: %v\n", err)
return "", err
}
// 提取路徑部分
path := parsedURL.Path
// 從路徑中提取文件名
//fileName := filepath.Base(path)
// 提取文件后綴(包括點(diǎn))
//ext := filepath.Ext(fileName)
//先判斷路徑圖片是否存在 存在直接返回
// 使用 os.Stat 獲取文件信息
if _, err := os.Stat("./captcha/" + path); err == nil {
// 沒有錯(cuò)誤,文件存在
fmt.Println("文件存在:", "./captcha/"+path)
return path, nil
}
// 發(fā)送HTTP GET請(qǐng)求
resp, err := http.Get(imageURL)
if err != nil {
fmt.Printf("Error fetching the image: %v\n", err)
return "", err
}
defer resp.Body.Close()
// 檢查HTTP響應(yīng)狀態(tài)碼
if resp.StatusCode != http.StatusOK {
fmt.Printf("Error: unable to fetch image, status code: %d\n", resp.StatusCode)
return "", err
}
// 創(chuàng)建一個(gè)文件來保存下載的圖片
outFile, err := os.Create("./captcha/" + path)
if err != nil {
fmt.Printf("Error creating the file: %v\n", err)
return "", err
}
defer outFile.Close()
// 將響應(yīng)體復(fù)制到文件中
_, err = io.Copy(outFile, resp.Body)
if err != nil {
fmt.Printf("Error saving the image: %v\n", err)
return "", err
}
return path, nil
}
配置路由
調(diào)用
package v1
import (
"xx/utils/goodstech"
"github.com/gin-gonic/gin"
)
func GetTestPdf(c *gin.Context) {
//測(cè)試
s, err := goodstech.GeneratePdf(4874)
fmt.Println("s:", s, err)
resp.OkWithData(param, c)
}
效果
下班!
123 在
Clash for Windows作者刪庫跑路了,github已404中評(píng)論 按理說只要你在國內(nèi),所有的流量進(jìn)出都在監(jiān)控范圍內(nèi),不管你怎么隱藏也沒用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最簡單的方法中評(píng)論 好久好久都沒看友情鏈接申請(qǐng)了,今天剛看,已經(jīng)添加。..博主 在
佛跳墻vpn軟件不會(huì)用?上不了網(wǎng)?佛跳墻vpn常見問題以及解決辦法中評(píng)論 @1111老鐵這個(gè)不行了,可以看看近期評(píng)論的其他文章..1111 在
佛跳墻vpn軟件不會(huì)用?上不了網(wǎng)?佛跳墻vpn常見問題以及解決辦法中評(píng)論 網(wǎng)站不能打開,博主百忙中能否發(fā)個(gè)APP下載鏈接,佛跳墻或極光..路人 在
php中使用hyperf框架調(diào)用訊飛星火大模型實(shí)現(xiàn)國內(nèi)版chatgpt功能示例中評(píng)論 教程很詳細(xì),如果加個(gè)前端chatgpt對(duì)話頁面就完美了..
Copyright·? 2019 侯體宗版權(quán)所有·
粵ICP備20027696號(hào)