NetCore3.1生成模板图片
在C#中要对图片操作就要用到Graphics的类
BLL:
public MemoryStream Img(string name,string amount,string date)
{
Bitmap bitmap = new Bitmap(GetPdfTemplatePath());
Graphics g = Graphics.FromImage(bitmap);
SolidBrush solidBrush = new SolidBrush(Color.Black);
g.DrawString(name, new System.Drawing.Font("宋体", 14), solidBrush, 120, 250);
g.DrawString(amount, new System.Drawing.Font("宋体", 14), solidBrush,600,320);
g.DrawString(date, new System.Drawing.Font("宋体", 14), solidBrush, 680, 505);
MemoryStream ms = new MemoryStream();
bitmap.Save(ms, ImageFormat.Jpeg);
byte[] newByte = ms.ToArray();
return ms;
}
Controller:
public FileContentResult DownloadImg()
{
var name = Request.Params("Name");
var amount = Request.Params("Amount");
var createtime = Request.Params("CreateTime");
CertificateHelper certificateHelper = new CertificateHelper();
MemoryStream ms = certificateHelper.Img(name,amount,createtime);
return File(ms.ToArray(), @"image/jpeg");
}
前台接收:从文件流生成文件下载
在Ajax的请求中,要设置responseType: ‘blob’
downloadimg (params) {
let self = this
const data = {
Name: params.row.Name,
Amount: params.row.Amount,
CreateTime: self.formatTime(params.row.CreateTime * 1000)
}
api.downloadimg(data).then(function (res) {
self.download(res)
})
},
download (data) {
let self = this
if (!data) {
return
}
let url = window.URL.createObjectURL(new Blob([data]))
let link = document.createElement('a')
self.imgsrc = url
link.style.display = 'none'
link.href = url
link.setAttribute('download', '荣誉证书.jpeg')
document.body.appendChild(link)
link.click()
},