goframe下载文件(pdf/execl)

package controller

import (
	"bytes"
	"context"
	"fmt"
	"github.com/gogf/gf/v2/encoding/gurl"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/jung-kurt/gofpdf"
	"github.com/xuri/excelize/v2"
	"log"
	"strconv"
	"strings"
	"tender/internal/app/desk/dao"
	desk_entity "tender/internal/app/desk/model/entity"
	"tender/internal/app/system/model/entity"
)

// 招投标批量下载
var (
	Download = DownloadController{}
)

type DownloadController struct {
	BaseController
}

type DownRes struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

func (c *DownloadController) DownloadFile(r *ghttp.Request) {
	// GetJson解析当前请求内容为JSON格式,并返回JSON对象。
	//注意,请求内容是从request BODY读取的,而不是从FORM的任何字段读取的。
	//reqdata, _ := r.GetJson()
	url, _ := gurl.Decode(r.RequestURI)
	p := strings.Split(url, "=")
	var ids []string
	if len(p) > 1 {
		ids = strings.Split(p[1], ",")
		log.Println("r.URL.RawQuery", p[1], ids, url)
	}
	res := []*entity.BiddingInformation{}
	m := g.DB("配置文件的数据分组名称").Schema("数据库").Model("表")
	m = m.WhereIn("id", ids)
	err := g.Try(r.Context(), func(ctx context.Context) {
		err := m.Scan(&res)
		if err != nil {
			log.Println(err)
			// r.Response.Write(&DownRes{Code: 50, Message: "查询数据失败"})
			return
		}
	})
	if err != nil {
		// r.Response.Write(&DownRes{Code: 50, Message: "查询数据失败"})
		return
	}
	f := excelize.NewFile()
	f.SetCellStr("sheet1", "A"+strconv.Itoa(1), "标题")
	f.SetCellStr("sheet1", "B"+strconv.Itoa(1), "城市")
	f.SetCellValue("sheet1", "C"+strconv.Itoa(1), "类型")
	f.SetCellStr("sheet1", "D"+strconv.Itoa(1), "时间")
	f.SetCellValue("sheet1", "E"+strconv.Itoa(1), "内容")
	for i := 0; i < len(res); i++ {
		log.Println(res[i].Title)
		f.SetCellStr("sheet1", "A"+strconv.Itoa(i+2), res[i].Title)
		f.SetCellStr("sheet1", "B"+strconv.Itoa(i+2), res[i].City)
		f.SetCellValue("sheet1", "C"+strconv.Itoa(i+2), res[i].IndustryClassification)
		f.SetCellStr("sheet1", "D"+strconv.Itoa(i+2), res[i].ReleaseTime)
		f.SetCellValue("sheet1", "E"+strconv.Itoa(i+2), res[i].AnnouncementContent)
	}
	// 写内存 文件大的容易崩
	buff, _ := f.WriteToBuffer()
	header := r.Response.Header()
	header.Add("Content-Type", "application/octet-stream")
	header.Add("Content-Disposition", "attachment;filename="+"tender.xlsx")
	r.Response.Write(buff.Bytes())
}

// 下载单个招标信息/知识 pdf
func (c *DownloadController) WritePdf(title string, date string, content string, page int) []byte {
	pdf := gofpdf.New("P", "mm", "A4", "./resource/ttf/")
	titleStr := title
	// pdf.SetFont("dejavu", "", 14)
	pdf.AddUTF8Font("PingFang", "", "PingFang Heavy.ttf")
	pdf.SetTitle(titleStr, false)
	//pdf.SetAuthor("Jules Verne", false)
	pdf.SetHeaderFunc(func() {
		// Arial bold 15
		pdf.SetFont("PingFang", "", 15)
		// Calculate width of title and position
		wd := pdf.GetStringWidth(titleStr) + 6
		pdf.SetX((210 - wd) / 2)
		// Colors of frame, background and text
		pdf.SetDrawColor(0, 80, 180)
		pdf.SetFillColor(230, 230, 0)
		pdf.SetTextColor(220, 50, 50)
		// Thickness of frame (1 mm)
		pdf.SetLineWidth(1)
		// Title
		pdf.CellFormat(wd, 9, titleStr, "1", 1, "C", true, 0, "")
		// Line break
		pdf.Ln(10)
	})
	pdf.SetFooterFunc(func() {
		// Position at 1.5 cm from bottom
		pdf.SetY(-15)
		// Arial italic 8
		pdf.SetFont("PingFang", "", 8)
		// Text color in gray
		pdf.SetTextColor(128, 128, 128)
		// Page number
		pdf.CellFormat(0, 10, fmt.Sprintf("Page %d", pdf.PageNo()),
			"", 0, "C", false, 0, "")
	})
	chapterTitle := func(chapNum int, titleStr string) {
		// 	// Arial 12
		pdf.SetFont("PingFang", "", 12)
		// Background color
		pdf.SetFillColor(200, 220, 255)
		// Title
		pdf.CellFormat(0, 6, fmt.Sprintf("发布时间 : %s", titleStr),
			"", 1, "L", true, 0, "")
		// Line break
		pdf.Ln(4)
	}
	chapterBody := func(txtStr string) {
		// Read text file
		//txtStr, err := ioutil.ReadFile(fileStr)
		//if err != nil {
		//	pdf.SetError(err)
		//}
		// Times 12
		pdf.SetFont("PingFang", "", 12)
		// Output justified text
		pdf.MultiCell(0, 5, string(txtStr), "", "", false)
		// Line break
		pdf.Ln(-1)
		// Mention in italics
		pdf.SetFont("PingFang", "", 0)
		pdf.Cell(0, 5, "(end of excerpt)")
	}
	printChapter := func(chapNum int, titleStr, fileStr string) {
		pdf.AddPage()
		chapterTitle(chapNum, titleStr)
		chapterBody(fileStr)
	}
	printChapter(page, date, content)
	// err := pdf.OutputFileAndClose("./test.pdf")
	var buff bytes.Buffer
	err := pdf.Output(&buff)
	//log.Println(buf.Bytes())
	if err != nil {
		log.Println("Error generating PDF: ", err)
	}
	return buff.Bytes()
}

// 单个pdf
func (c *DownloadController) DownloadFilePdf(r *ghttp.Request) {
	// GetJson解析当前请求内容为JSON格式,并返回JSON对象。
	//注意,请求内容是从request BODY读取的,而不是从FORM的任何字段读取的。
	//reqdata, _ := r.GetJson()
	url, _ := gurl.Decode(r.RequestURI)
	p := strings.Split(url, "=")
	var ids []string
	if len(p) > 1 {
		ids = strings.Split(p[1], ",")
		log.Println("r.URL.RawQuery", p[1], ids, url)
	}
	res := (*entity.BiddingInformation)(nil)
	m := g.DB("配置文件的数据分组名称").Schema("数据库").Model("表")
	m = m.WhereIn("id", ids)
	err := g.Try(r.Context(), func(ctx context.Context) {
		err := m.Limit(1).Scan(&res)
		if err != nil {
			log.Println(err)
			// r.Response.Write(&DownRes{Code: 50, Message: "查询数据失败"})
			return
		}
	})
	if err != nil {
		// r.Response.Write(&DownRes{Code: 50, Message: "查询数据失败"})
		return
	}
	var buff []byte
	if res != nil {
		buff = c.WritePdf(res.Title, res.ReleaseTime, res.AnnouncementContent, 1)
	}
	header := r.Response.Header()
	header.Add("Content-Type", "application/octet-stream")
	header.Add("Content-Disposition", "attachment;filename="+"tender.pdf")
	r.Response.Write(buff)
}

func (c *DownloadController) DownloadKnowledgeFile(r *ghttp.Request) {
	// reqdata, _ := r.GetJson()

	url, _ := gurl.Decode(r.RequestURI)
	p := strings.Split(url, "=")
	var ids []string
	if len(p) > 1 {
		ids = strings.Split(p[1], ",")
		log.Println("r.URL.RawQuery", p[1], ids, url)
	}
	res := []*desk_entity.MemberKnowledge{}
	m := dao.MemberKnowledge.Ctx(r.Context())
	m = m.WhereIn("id", ids)
	err := g.Try(r.Context(), func(ctx context.Context) {
		err := m.Scan(&res)
		if err != nil {
			log.Println(err)
			// r.Response.Write(&DownRes{Code: 50, Message: "查询数据失败"})
			return
		}
	})
	if err != nil {
		// r.Response.Write(&DownRes{Code: 50, Message: "查询数据失败"})
		return
	}
	f := excelize.NewFile()
	f.SetCellStr("sheet1", "A"+strconv.Itoa(1), "标题")
	f.SetCellValue("sheet1", "B"+strconv.Itoa(1), "类型")
	f.SetCellStr("sheet1", "C"+strconv.Itoa(1), "时间")
	f.SetCellValue("sheet1", "D"+strconv.Itoa(1), "内容")
	for i := 0; i < len(res); i++ {
		f.SetCellStr("sheet1", "A"+strconv.Itoa(i+2), res[i].Title)
		f.SetCellValue("sheet1", "B"+strconv.Itoa(i+2), res[i].SecondaryClassification)
		f.SetCellStr("sheet1", "C"+strconv.Itoa(i+2), res[i].CreatedAt.Format("2006-01-02 15:04:05"))
		f.SetCellValue("sheet1", "D"+strconv.Itoa(i+2), res[i].Content)
	}
	// 写内存 文件大的容易崩
	buff, _ := f.WriteToBuffer()
	header := r.Response.Header()
	header.Add("Content-Type", "application/octet-stream")
	header.Add("Content-Disposition", "attachment;filename="+"knowledge.xlsx")
	r.Response.Write(buff.Bytes())
}

// 单个pdf
func (c *DownloadController) DownloadKnowledgeFilePdf(r *ghttp.Request) {
	// reqdata, _ := r.GetJson()

	url, _ := gurl.Decode(r.RequestURI)
	p := strings.Split(url, "=")
	var ids []string
	if len(p) > 1 {
		ids = strings.Split(p[1], ",")
		log.Println("r.URL.RawQuery", p[1], ids, url)
	}
	res := (*desk_entity.MemberKnowledge)(nil)
	m := dao.MemberKnowledge.Ctx(r.Context())
	m = m.WhereIn("id", ids)
	err := g.Try(r.Context(), func(ctx context.Context) {
		err := m.Limit(1).Scan(&res)
		if err != nil {
			log.Println(err)
			// r.Response.Write(&DownRes{Code: 50, Message: "查询数据失败"})
			return
		}
	})
	if err != nil {
		// r.Response.Write(&DownRes{Code: 50, Message: "查询数据失败"})
		return
	}
	var buff []byte
	if res != nil {
		buff = c.WritePdf(res.Title, res.CreatedAt.Format("2006-01-02 15:04:05"), res.Content, 1)
	}
	header := r.Response.Header()
	header.Add("Content-Type", "application/octet-stream")
	header.Add("Content-Disposition", "attachment;filename="+"knowledge.pdf")
	r.Response.Write(buff)
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值