1. 程式人生 > 實用技巧 >Word模板儲存成PDF,並在前臺展示

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
            });
        }
    });
}