使用Aspose.Words生成文档

        /// <summary>
        /// 生成设计变更工程联系函
        /// </summary>
        /// <param name="DesignAlterGUID"></param>
        /// <returns></returns>
        private string GenerateDesignAlterDoc(string DesignAlterGUID)
        {

            string AlterCode, ProjectNameList, ReportDate, AlterName, ToProviderName, CCProviderNameList, CostBearedCompanyName, AlterType, AlterClass, IsReturnWork, Remarks, SgInterface, SgInterfaceTitle;
            string strInsertSql, strSql;
            string strJpgFilePath, strJpgFileName;
            Bitmap qrcode;
            string strFileName;
            string DocGUID;
            decimal DesignAlterAmount;
            object param;
            string[] fieldsName = new string[] { "AlterCode", "ProjectNameList", "ReportDate", "AlterName", "ToProviderName", "CCProviderNameList", "CostBearedCompanyName", "AlterType", "AlterClass", "IsReturnWork", "Remarks", "SgInterface", "SgInterfaceTitle" };
            object[] fieldsValue;
            try
            {
                //删除p_Documents中的记录
                strSql = "DELETE FROM dbo.p_Documents WHERE FkGUID = @DesignAlterGUID AND DocType = ‘工程联系函‘";
                param = new { DesignAlterGUID = DesignAlterGUID };
                CPQuery.From(strSql, param).ExecuteNonQuery();
                PublicMNG myPublic = new PublicMNG();
                string strGetPath = System.Web.HttpContext.Current.Server.MapPath("\\UpFiles\\");
                string strSavePath = System.Web.HttpContext.Current.Server.MapPath("\\UpFiles\\工程联系函\\");
                //判断目标文件夹是否存在,不存在则创建
                if (!Directory.Exists(strSavePath))
                {
                    Directory.CreateDirectory(strSavePath);
                }
                string strUserGUID = System.Web.HttpContext.Current.Session["UserGUID"].ToString();
                Document doc = new Document(strGetPath + "设计变更工程联系函模板.doc");
                strSql = "SELECT AlterCode, CONVERT(CHAR(10),ReportDate,120) AS ReportDate,AlterName,ToProviderNameList,CCProviderNameList,CostBearedCompanyName,AlterType,IsReturnWork,Remarks,SgInterface,ISNULL(b.DesignAlterAmount,0) AS DesignAlterAmount,dbo.fn_GetDesignAlterProjNameList(dbo.cb_DesignAlter.DesignAlterGUID) AS ProjNameList FROM dbo.cb_DesignAlter " +
                         " LEFT JOIN (SELECT DesignAlterGuid,SUM (DesignAlterAmount) AS DesignAlterAmount FROM dbo.cb_DesignAlterBudgetUse GROUP BY DesignAlterGuid) b ON dbo.cb_DesignAlter.DesignAlterGuid = b.DesignAlterGuid WHERE dbo.cb_DesignAlter.DesignAlterGUID = @DesignAlterGUID";
                DataTable dt = GetData(strSql);
                if (dt.Rows.Count > 0)
                {
                    DataRow dr = dt.Rows[0];
                    AlterCode = dr["AlterCode"].ToString();
                    ProjectNameList = dr["ProjNameList"].ToString();
                    ReportDate = dr["ReportDate"].ToString();
                    AlterName = dr["AlterName"].ToString();
                    ToProviderName = dr["ToProviderNameList"].ToString();
                    CCProviderNameList = dr["CCProviderNameList"].ToString();
                    CostBearedCompanyName = dr["CostBearedCompanyName"].ToString();

                    AlterType = "? 设计变更   □ 工程指令";

                    DesignAlterAmount = (decimal)dr["DesignAlterAmount"];
                    if (DesignAlterAmount > 0)
                    {
                        AlterClass = "? 增加 □ 减少 □ 无增减";
                    }
                    else
                    {
                        AlterClass = "□ 增加 ? 减少 □ 无增减";
                    }
                    
                    IsReturnWork = dr["IsReturnWork"].ToString();
                    if (IsReturnWork == "1")
                    {
                        IsReturnWork = "? 是 □ 否";
                    }
                    else
                    {
                        IsReturnWork = "□ 是 ? 否";
                    }
                    Remarks = dr["Remarks"].ToString();
                    SgInterface = dr["SgInterface"].ToString();
                    if (!string.IsNullOrEmpty(SgInterface))
                    {
                        SgInterfaceTitle = "施工界面划分:";
                    }
                    else
                    {
                        SgInterfaceTitle = "";
                    }

                    //1.插入文档正文
                    fieldsValue = new object[] { AlterCode, ProjectNameList, ReportDate, AlterName, ToProviderName, CCProviderNameList, CostBearedCompanyName, AlterType, AlterClass, IsReturnWork, Remarks, SgInterface, SgInterfaceTitle };
                    doc.MailMerge.Execute(fieldsName, fieldsValue);

                    //2.多线程生成文档图片
                    Thread generateJPGThread = new Thread(new ParameterizedThreadStart(GenerateAndSavePicture));
                    GenerateJPGThreadParam threadParam = new GenerateJPGThreadParam();
                    threadParam.Doc = doc.Clone();
                    threadParam.SavePath = System.Web.HttpContext.Current.Server.MapPath("\\UpFiles\\HTAlterLxh");
                    threadParam.FileName = AlterCode + ".jpg";
                    generateJPGThread.Start(threadParam);

                    //3.生成并插入二维码
                    doc = InsertQRCode(doc, AlterCode);

                    //4.插入“主办工程师:” 和 “工程部门盖章:”标题
                    fieldsName = new string[] { "HostEngineer", "EngineerDeptSeal" };
                    fieldsValue = new object[] { "主办工程师:", "工程部门盖章:" };
                    doc.MailMerge.Execute(fieldsName, fieldsValue);

                    //文档名称
                    DocGUID = Guid.NewGuid().ToString();
                    strFileName = "设计变更工程联系函" + DesignAlterGUID + ".doc";
                    //保存生成的中标通知书
                    //如果文件存在,先删除
                    if (File.Exists(strSavePath + strFileName))
                    {
                        File.Delete(strSavePath + strFileName);
                    }
                    doc.Save(strSavePath + strFileName);
                    //保存文档信息到p_Documents信息
                    strInsertSql = "INSERT INTO dbo.p_Documents " +
                                    "( DocGUID,FkGUID,DocType,DocName,FileName,Location,CreateOn,CreateBy,IsImportant,LockedBy,LockedDateTime,ModifiedBy,ModifiedDateTime,URL,jd_documentDetailType) VALUES " +
                                    " (‘" + DocGUID + "‘,‘" + DesignAlterGUID + "‘,‘工程联系函‘,‘" + strFileName + "‘,‘" + strFileName + "‘,‘/UpFiles/工程联系函/‘,GETDATE(),‘" + strUserGUID + "‘,NULL,NULL,NULL,NULL,NULL,‘‘,NULL);";
                    //更新记录未已打印
                    strInsertSql += "UPDATE dbo.cb_DesignAlter SET IsPrint = 1 WHERE DesignAlterGuid = ‘" + DesignAlterGUID + "";
                    InsertData(strInsertSql);

                    return DocGUID;
                }
                else
                {
                    return "";
                }
            }
            catch (Exception E)
            {
                return "";
            }
        }

将document文件保存成图片

     /// <summary>
        /// 根据文档备份图片
        /// </summary>
        /// <param name="Doc"></param>
        private void GenerateAndSavePicture(object param)
        {
            GenerateJPGThreadParam threadParam = (GenerateJPGThreadParam)param;
            Document doc = threadParam.Doc;
            string strSavePath = threadParam.SavePath;
            string strFileName = threadParam.FileName;
            //移除空白域
            doc.MailMerge.DeleteFields();

            //判断文件件是否存在
            if (!Directory.Exists(strSavePath))
            {
                Directory.CreateDirectory(strSavePath);
            }
            //文件已存在,先删除
            string strFullName = string.Format(@"{0}\\{1}", strSavePath, strFileName);
            if (File.Exists(strFullName))
            {
                File.Delete(strFullName);
            }

            ImageSaveOptions iso = new ImageSaveOptions(SaveFormat.Jpeg);
            iso.PrettyFormat = true;
            doc.Save(strFullName, iso);
        }

    /// <summary>
    /// 封装文档多线程的参数
    /// </summary>
    class GenerateJPGThreadParam
    {
        //文档
        private Document _doc;

        public Document Doc
        {
            get { return _doc; }
            set { _doc = value; }
        }

        //文件名
        private string _FileName;

        public string FileName
        {
            get { return _FileName; }
            set { _FileName = value; }
        }

        //保存路径
        private string _SavePath;

        public string SavePath
        {
            get { return _SavePath; }
            set { _SavePath = value; }
        }
}

生成并插入二维码

     private Document InsertQRCode(Document doc, String AlterCode)
        {
            Bitmap qrcode;
            //获取外网地址
            string strSql = "SELECT paramvalue FROM dbo.myBizParamOption WHERE ParamName = ‘cb_OutNetAddress‘";
            string strOutNetAddress = CPQuery.From(strSql).ExecuteScalar<string>();

            string strJpgFileName = string.Format(@"{0}/UpFiles/HTAlterLxh/{1}.jpg", strOutNetAddress, AlterCode);
            qrcode = GenerateQRCodeMap(strJpgFileName, 50);

            Shape shape = new Shape(doc, ShapeType.Image);
            shape.ImageData.SetImage(qrcode);
            shape.Width = 70;
            shape.Height = 70;
            shape.HorizontalAlignment = HorizontalAlignment.Left;

            DocumentBuilder builder = new DocumentBuilder(doc);
            builder.MoveToMergeField("QRCode");
            builder.InsertNode(shape);

            return doc;

        }

        /// <summary>  
        /// 生成二维码图片  
        /// </summary>  
        /// <param name="codeNumber">link</param>       
        /// <returns>二维码图片</returns>  
        private Bitmap GenerateQRCodeMap(string link, int size)
        {
            QRCodeEncoder qrEntity = new QRCodeEncoder();

            qrEntity.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;//二维码编码方式

            qrEntity.QRCodeScale = 10;//每个小方格的宽度

            qrEntity.QRCodeVersion = 4;//二维码版本号

            qrEntity.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;//纠错码等级

            System.Drawing.Bitmap srcimage;
            //动态调整二维码版本号,上限40,过长返回空白图片,编码后字符最大字节长度2953
            while (true)
            {
                try
                {
                    srcimage = qrEntity.Encode(link, System.Text.Encoding.UTF8);
                    break;
                }
                catch (IndexOutOfRangeException e)
                {
                    if (qrEntity.QRCodeVersion < 40)
                    {
                        qrEntity.QRCodeVersion++;
                    }
                    else
                    {
                        srcimage = new Bitmap(size, size);
                        break;
                    }
                }
            }
            //为生成的二维码图像裁剪白边并调整为请求的高度
            return srcimage;

        }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。