【Aspose.Word】根据模板生成证书
模板文件:
CS代码:
public ActionResult PrintCertPDF(string certInfoId, int type = 0) { try { var constructionInfoId = 0; var str = DecodeBase64(Encoding.UTF8, certInfoId.ToString()); str = str.IndexOf('\'') != -1 ? str.Substring(str.IndexOf('\'') + 1, str.Length - 2) : str; if (!int.TryParse(str, out constructionInfoId)) { return Json(new { success = false, msg = "数据错误" }, JsonRequestBehavior.AllowGet); } if (constructionInfoId <= 0) { return Json(new { success = false, msg = "数据错误" }, JsonRequestBehavior.AllowGet); } var certInfo = GrCertService.GrCertVmById(constructionInfoId); if (certInfo == null) { return Json(new { success = false, msg = "获取证书信息错误" }, JsonRequestBehavior.AllowGet); } var faceImg = FaceImgLogService.LoadAllByWhere(f => f.PersonalId == certInfo.PersonId && f.ImageType == (int)ImageType.头像 && !f.IsDelete, f => f.Id).FirstOrDefault(); if (faceImg == null) { return Json(new { success = false, msg = "请先完善头像信息" }, JsonRequestBehavior.AllowGet); } var isExist = Tool.RemoteFileExists(faceImg.FaceImgUrl); if (!isExist) { return Json(new { success = false, msg = "头像照片不存在,请先上传头像" }, JsonRequestBehavior.AllowGet); } //培训机构公章 var department = DepartmentService.Get(certInfo.DepartmentID); var areaInfo = AreaInfoService.Get(department.ProvinceId); var organInfo = GrOrganInfoService.LoadByWhere(w => w.Id == department.TrainDepartmentId); Asp.Document doc; using (var stream = System.IO.File.OpenRead(Server.MapPath("/Content/Templates/GrCert/中医药培训证书模板.docx"))) { doc = new Asp.Document(stream); } //先生成二维码照片 var qrCodeImg = GetQrCode(ConfigHelper.WwwDomain + "Login/PrintCertPDF?certInfoId=" + EncodeBase64(Encoding.UTF8, constructionInfoId.ToString())); var dicReplaceValues = new Dictionary<string, string>(); dicReplaceValues.Add("UserName", certInfo.PersonName); dicReplaceValues.Add("Byear", certInfo.TrainingStartTime == "" ? "" : Convert.ToDateTime(certInfo.TrainingStartTime).Year.ToString()); dicReplaceValues.Add("Bmonth", certInfo.TrainingStartTime == "" ? "" : Convert.ToDateTime(certInfo.TrainingStartTime).Month.ToString()); dicReplaceValues.Add("Bday", certInfo.TrainingStartTime == "" ? "" : Convert.ToDateTime(certInfo.TrainingStartTime).Day.ToString()); dicReplaceValues.Add("Eday", certInfo.TrainingEndTime == "" ? "" : Convert.ToDateTime(certInfo.TrainingEndTime).Day.ToString()); dicReplaceValues.Add("Twork", certInfo.TWorkName); dicReplaceValues.Add("CertNum", certInfo.CertNumber); dicReplaceValues.Add("PersonId", certInfo.PersonId); dicReplaceValues.Add("PhotoUrl", faceImg.FaceImgUrl); dicReplaceValues.Add("Syear", certInfo.SendCertTime == null ? "" : certInfo.SendCertTime.Value.Year.ToString()); dicReplaceValues.Add("Smonth", certInfo.SendCertTime == null ? "" : certInfo.SendCertTime.Value.Month.ToString()); dicReplaceValues.Add("Sday", certInfo.SendCertTime == null ? "" : certInfo.SendCertTime.Value.Day.ToString()); dicReplaceValues.Add("ErWeiMa", ""); dicReplaceValues.Add("GongZhang1", organInfo.CommonSealImg == null ? "" : organInfo.CommonSealImg); dicReplaceValues.Add("CertificateDepartment", certInfo.CertificateDepartment); Asp.DocumentBuilder builder = new Asp.DocumentBuilder(doc); foreach (var key in dicReplaceValues.Keys) { if (key == "PhotoUrl") { //插入图片 builder.InsertImage(dicReplaceValues[key], Asp.Drawing.RelativeHorizontalPosition.LeftMargin, 250, Asp.Drawing.RelativeVerticalPosition.TopMargin, 260, 90, 110, Asp.Drawing.WrapType.None); } else if (key == "ErWeiMa") { //插入图片 builder.InsertImage(qrCodeImg, Asp.Drawing.RelativeHorizontalPosition.LeftMargin, 370, Asp.Drawing.RelativeVerticalPosition.TopMargin, 490, 70, 70, Asp.Drawing.WrapType.None); } else if (key == "GongZhang1") { //插入图片 builder.InsertImage(dicReplaceValues[key], Asp.Drawing.RelativeHorizontalPosition.LeftMargin, 150, Asp.Drawing.RelativeVerticalPosition.TopMargin, 540, 120, 120, Asp.Drawing.WrapType.None); } else { var repStr = string.Format("${0}$", key); doc.Range.Replace(repStr, dicReplaceValues[key], false, false); } } MemoryStream ms = new MemoryStream(); doc.Save(ms, Aspose.Words.SaveFormat.Pdf); ms.Position = 0; //下载 if (type == 0) { return File(ms, "application/pdf", "证书" + "-" + new Random().Next(1000, 9999) + ".pdf"); } else//预览 { var path = "/Files/PDF/CertPdf/" + SecurityHelper.Encrypt(areaInfo.Name, ConfigHelper.EncryptKey) + "/" + SecurityHelper.Encrypt(department.DepartmentName, ConfigHelper.EncryptKey) + "/"; var pathDir = Server.MapPath(path); var fileName = SecurityHelper.Encrypt(certInfo.PersonId, ConfigHelper.EncryptKey) + "(证书).pdf"; var newPdf = Server.MapPath(path + fileName); //如果文件已存在,删除 if (System.IO.File.Exists(newPdf)) { System.IO.File.Delete(newPdf); } //文件不存在时 if (!System.IO.File.Exists(newPdf)) { //文件夹不存在时创建文件夹 if (!System.IO.Directory.Exists(pathDir)) { Directory.CreateDirectory(pathDir); } //创建PDF文件 var sr = new FileStream(newPdf, FileMode.Create); sr.Write(ms.GetBuffer(), 0, (int)ms.Length); sr.Close(); sr.Dispose(); } string base64String = ""; using (FileStream fs = new FileStream(pathDir + fileName, FileMode.Open)) { long fileSize = fs.Length; byte[] buffer = new byte[(int)fileSize]; fs.Read(buffer, 0, (int)fs.Length); base64String = Convert.ToBase64String(buffer); } //生成base64后删除原文件 if (System.IO.File.Exists(newPdf)) { System.IO.File.Delete(newPdf); } return Json(new { success = true, pdfBase64String = "data:application/pdf;base64," + base64String }); } } catch (Exception e) { return Json(new { success = false, msg = e.Message }, JsonRequestBehavior.AllowGet); } } /// <summary> /// 生成二维码 /// </summary> /// <param name="content"></param> /// <returns></returns> public byte[] GetQrCode(string content) { QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(); using (var ms = new System.IO.MemoryStream()) { var myimg = qrCodeEncoder.Encode(content, System.Text.Encoding.UTF8); //kedee 增加utf-8编码,可支持中文汉字 myimg.Save(ms, System.Drawing.Imaging.ImageFormat.Png); ms.Position = 0; return ms.ToArray(); } }
JS代码:
<button type="button" class="layui-btn layui-btn-normal layui-btn-sm" onclick="lookGrCertInfo(` + data.data[i].ID + `);">查看</button> <button type="button" class="layui-btn layui-btn-warm layui-btn-sm" onclick="downGrLoadCertInfo(`+ data.data[i].ID + `)">下载</button> var downLoadCertTimeCheck = 10; var lookCertTimeCheck = 10; //查看证书 function lookGrCertInfo(id) { if (lookCertTimeCheck == 10) { lookCertSettimeMananger(); layer.load(1); $.ajax({ url: '/Login/ShowCertInfo', type: 'post', data: { certInfoId: id }, success: function (data) { layer.closeAll('loading'); if (data.success) { layer.open({ title: "证书", type: 2, area: ['100%', '100%'], content: data.pdfBase64String }); } else { layer.msg(data.msg, { icon: 5, time: 2000 }); } }, error: function () { layer.closeAll('loading'); layer.msg('网络错误,请稍后重试', { icon: 5, time: 2000 }); } }) } else { layer.msg('请勿重复点击,请于' + (lookCertTimeCheck == 0 ? 1 : lookCertTimeCheck) + '秒后再次点击', { icon: 5 }); } } //下载证书 function downGrLoadCertInfo(id) { if (downLoadCertTimeCheck == 10) { downLoadCertSettimeMananger(); $.ajax({ url: '/Login/PrintCertPDF?certInfoId=' + encode64("'" + id + "'"), type: 'get', cache: false, success: function (res) { if (!res.success && res.msg) { layer.msg(res.msg, { icon: 5, time: 2000 }); } else { window.open("/Login/PrintCertPDF?certInfoId=" + encode64("'" + id + "'")); } } }) } else { layer.msg('请勿重复点击,请于' + (downLoadCertTimeCheck == 0 ? 1 : downLoadCertTimeCheck) + '秒后再次点击', { icon: 5 }); } }