Word模板保存成PDF,并在前台展示

检测是否有数据,如果有数据直接在方法中调用获取证书PDF的方法“CertInfoPdf”

 /// <summary>
        /// 检测是否有证书
        /// </summary>
        /// <param name="personalId"></param>
        /// <param name="name"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public ActionResult CheckHasCert(string personalId, string name, string code)
        {
            HttpCookie cookie = Request.Cookies["ValidateCode"];
            if (cookie != null)
            {
                if (cookie.Value != code)
                {
                    return Json(new { success = false, msg = "验证码错误!" });
                }
            }
            else
            {
                return Json(new { success = false, msg = "验证码错误!" });
            }
            if (string.IsNullOrWhiteSpace(personalId))
            {
                return Json(new { success = false, msg = "数据错误" });
            }
            var certInfo = JobClient.GetCert(new JobCertSearch { PersonalId = personalId, Name = name });
            if (certInfo == null || certInfo.JobCert == null)
            {
                return Json(new { success = false, msg = "暂无证书" });
            }
            if (certInfo.FaceImage == null)
            {
                return Json(new { success = false, msg = "请先完善头像信息" });
            }
            var certVm = certInfo.JobCert;return CertInfoPdf(personalId, EncodeBase64(Encoding.UTF8, name));
        }

由于模板中有二维码,扫码二维码也要展示相同的页面,但是参数是中文时有问题,所以中文参数进行了下编码,要扫码看数据,就需要把方法的权限放开,不能进行验证“[CheckLogin(false)]”

[CheckLogin(false)]
        public ActionResult CertInfoPdf(string personalId,string name,int type = 1)
        {
            try
            {

           if (string.IsNullOrWhiteSpace(personalId))
           {
            return Json(new { success = false, msg = "数据错误" },JsonRequestBehavior.AllowGet);
           }
           var certInfo = JobClient.GetCert(new JobCertSearch { PersonalId = personalId, Name = name });
           if (certInfo == null || certInfo.JobCert == null)
           {
            return Json(new { success = false, msg = "暂无证书" }, JsonRequestBehavior.AllowGet);
           }
           if (certInfo.FaceImage == null)
           {
            return Json(new { success = false, msg = "请先完善头像信息" }, JsonRequestBehavior.AllowGet);
           }
           var certVm = certInfo.JobCert;

                name = DecodeBase64(Encoding.UTF8, name);
                name = name.IndexOf('\'') != -1 ? name.Substring(name.IndexOf('\'') + 1, name.Length - 2) : name;
                Asp.Document doc;
                using (var stream = System.IO.File.OpenRead(Server.MapPath("/Content/Templates/证书模板.docx")))
                {
                    doc = new Asp.Document(stream);
                }
                //先生成二维码照片"
                GetQrCode(ConfigHelper.WwwDomain + "Login/CertInfoPdf?name=" + EncodeBase64(Encoding.UTF8, name) + "&personalId=" + personalId+"&type=0", certVm.CertNumber);
                var qrCodeImgPath = Request.MapPath(currentPath) + "/" + certVm.CertNumber + ".png";
                var dicReplaceValues = new Dictionary<string, string>();
                dicReplaceValues.Add("Name", certVm.Name);
                dicReplaceValues.Add("PersonalId", certVm.PersonalId);
                dicReplaceValues.Add("CertNum", certVm.CertNumber);
                dicReplaceValues.Add("PhotoUrl", certInfo.FaceImage.ImageUrl);
                dicReplaceValues.Add("ErWeiMa", qrCodeImgPath);

                Asp.DocumentBuilder builder = new Asp.DocumentBuilder(doc);
                foreach (var key in dicReplaceValues.Keys)
                {
                    if (key == "PhotoUrl")
                    {
                        //插入图片
                        builder.InsertImage(dicReplaceValues[key], Asp.Drawing.RelativeHorizontalPosition.LeftMargin, 88, Asp.Drawing.RelativeVerticalPosition.TopMargin, 172, 95, 120, Asp.Drawing.WrapType.None);//147表
                    }
                    else if (key == "ErWeiMa")
                    {
                        //插入图片
                        builder.InsertImage(dicReplaceValues[key], Asp.Drawing.RelativeHorizontalPosition.LeftMargin, 82, Asp.Drawing.RelativeVerticalPosition.TopMargin, 545, 70, 70, Asp.Drawing.WrapType.None);//147表
                    }
                    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 (System.IO.File.Exists(qrCodeImgPath))
                {
                    System.IO.File.Delete(qrCodeImgPath);
                }
                //下载
                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(certVm.PersonalId, 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 }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception e)
            {
                return Json(new { success = false, msg = e.Message }, JsonRequestBehavior.AllowGet);
            }
        }

加密解密方法

 /// <summary>
        /// base64解密
        /// </summary>
        /// <param name="encode">编码,与js一致</param>
        /// <param name="result">加密源字符串</param>
        /// <returns></returns>
        public static string DecodeBase64(Encoding encode, string result)
        {
            string decode = "";
            byte[] bytes = Convert.FromBase64String(result);
            try
            {
                decode = encode.GetString(bytes);
            }
            catch
            {
                decode = result;
            }
            return decode;
        }
        /// <summary>
        /// base64加密
        /// </summary>
        /// <param name="encode">编码,与js一致</param>
        /// <param name="source">加密源字符串</param>
        /// <returns></returns>
        public static string EncodeBase64(Encoding encode, string source)
        {
            string decode = "";
            byte[] bytes = encode.GetBytes(source);
            try
            {
                decode = Convert.ToBase64String(bytes);
            }
            catch
            {
                decode = source;
            }
            return decode;
        }

生成二维码

 
 


public readonly string currentPath = @"/Content/QrCodeImg";

public void GetQrCode(string url, string certNumber)
        {
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            System.Drawing.Bitmap myimg = qrCodeEncoder.Encode(url, System.Text.Encoding.UTF8); //kedee 增加utf-8编码,可支持中文汉字  
            SaveImg(currentPath, myimg, certNumber);
            ms.Dispose();
            ms.Close();
        }

前台接收处理,接收到的字符串赋值到iframe的src上,由于我用的layui,弹出层可以根据type决定类型,type值为2就是iframe弹出层,所以直接就赋值给弹出层了

//证书查询
function SearchInfo() {
    var personalId = $.trim($("#personalId").val());
    var name = $.trim($("#name").val());
    var checkCode = $.trim($("#checkCode").val());
    layer.load(1);
    $.ajax({
        url: '/Login/CheckHasCert',
        type:'post',
        data: { 'code': checkCode, 'name': name, 'personalId': personalId },
        success: function (data) {
            ClickRemoveChangeCode();
            var item = "";
            if (data.success) {
                if (data.pdfBase64String) {
                    layer.open({
                        title: "证书",
                        type: 2,
                        area: ['100%', '100%'],
                        content: data.pdfBase64String
                    });
                }
                layer.closeAll('loading');
            }
            else {
                if (data.msg) {
                    error = data.msg;
                    layer.msg(data.msg, { icon: 5, time: 2000 });
                }
                else {
                    layer.msg('暂无数据', { icon: 5, time: 2000 });
                }
                layer.closeAll('loading');
            }
        }, error: function () {
            layer.closeAll('loading');
            ClickRemoveChangeCode();
            layer.msg("网络错误,请稍后重试", {
                icon: 5,
                time: 2000
            });
        }
    });
}

猜你喜欢

转载自www.cnblogs.com/xiaonangua/p/13396346.html