public ActionResult CreatePdf(string ids) { Result <int> resultInfo = new Result <int>(); List <long> idList = ids.SplitString(",").ToLongList(); string pathUrl = ""; using (ClientSiteClientProxy proxy = new ClientSiteClientProxy(ProxyEx(Request))) { string path = ConfigurationManager.AppSettings["PDFPathUrl"]; string fileName = path + "甲供物资申请单" + DateTime.Now.ToString("yyyymmddhhMMssfff"); if (!Directory.Exists(fileName)) { DirectoryInfo directoryInfo = new DirectoryInfo(fileName); directoryInfo.Create(); } string pdfPath = ""; foreach (var item in idList) { var result = proxy.GetTzSupplyMaterialApplyModel(item).Data; if (result != null) { string pdfName = ""; pdfPath = ""; //物资信息 string html32 = ""; int index = 0; foreach (var temp in result.TzSupMatApplyList) { index++; html32 += "<tr class='tab-conten'><td style='border: 1px solid #D9D8D8;padding: 2px;height: 40px;'>" + index + "</td><td style='border: 1px solid #D9D8D8;padding: 2px;height: 40px;'>" + temp.SupMatManagement + "</td><td style='border: 1px solid #D9D8D8;padding: 2px;height: 40px;'> " + temp.ProductName + "</td><td style='border: 1px solid #D9D8D8;padding: 2px;height: 40px;'>" + temp.Specification + "</td><td style='border: 1px solid #D9D8D8;padding: 2px;height: 40px;'>" + temp.UnitPrice.ToString("0.00") + "</td><td style='border: 1px solid #D9D8D8;padding: 2px;height: 40px;'>" + temp.Number.ToString("0.00") + "</td><td style='border: 1px solid #D9D8D8;padding: 2px;height: 40px;'>" + temp.Money.ToString("0.00") + "</td><td style='border: 1px solid #D9D8D8;padding: 2px'>" + temp.SupplierName + "</td><td style='border: 1px solid #D9D8D8;padding: 2px;height: 40px;'>" + temp.Remark + "</td></tr>"; } //---读html模板页面到stringbuilder对象里---- string[] format = new string[20];//定义和htmlyem标记数目一致的数组 StringBuilder htmltext = new StringBuilder(); try { string htmlPath = "~/HtmlTemp.html"; htmlPath = Server.MapPath(htmlPath); using (StreamReader sr = new StreamReader(htmlPath)) { String line; while ((line = sr.ReadLine()) != null) { htmltext.Append(line); } sr.Close(); } format[0] = result.ApplyTitle; format[1] = result.ApplyUserName; format[2] = result.SupApplyTime.ToString("yyyy-mm-dd"); format[3] = result.ApplyDepartment; format[4] = result.ContractCode; format[5] = result.ContractNumber; format[6] = result.ArrivalContacts; format[7] = result.ArrivalContactsTel; format[8] = result.ProjectName; format[9] = result.ApprovalNo; format[10] = html32; format[11] = result.TotleMoney.ToString("0.00"); format[12] = result.SupplierContacts; format[13] = result.SupplierTel; format[14] = result.SupplierAddress; format[15] = result.ApprovalName; format[16] = result.ApprovalDep; format[17] = result.StateName; format[18] = result.OperateTime.ToString("yyyy-mm-dd"); format[19] = result.SignNameUrl; //----------替换htm里的标记为你想加的内容 for (int i = 0; i < 20; i++) { htmltext.Replace("$htmlformat[" + i + "]", format[i]); } string html = htmltext.ToString(); pdfName = result.ProjectName; pdfPath = fileName + "/" + pdfName + ".pdf"; PDFHelper.ExportPDF(pdfPath, html); } catch { resultInfo.Flag = EResultFlag.Failure; } } } if (idList.Count == 1) { pathUrl = pdfPath; } else { string fileNamepath = System.IO.Path.GetFileName(fileName); string paths = fileName; //using (ZipFile zip = ZipFile.Create(paths)) //{ // zip.BeginUpdate(); // zip.CommitUpdate(); //} pathUrl = paths + ".zip"; Utility.CreateZip(fileName, pathUrl); } string pathName = System.IO.Path.GetFileName(pathUrl); return(Json(new { Flag = resultInfo.Flag, fileName = pathName, download = pathUrl//文件下载链接 })); } }
public async Task <object> PostFile(FileModel fileModel) { try { string result = ""; if (fileModel != null) { string Base64String = fileModel.Base64String.Replace("data:image/png;base64,", ""); byte[] FileContent = Convert.FromBase64String(Base64String); string ImageFilePath = AppDomain.CurrentDomain.BaseDirectory + "UploadFile\\Images\\ChangeImages\\"; string PdfFilePath = AppDomain.CurrentDomain.BaseDirectory + "UploadFile\\PDF\\"; string FileName = Path.GetFileName(fileModel.FileName.Substring(0, fileModel.FileName.Length - 4)); string Err = ""; bool upres = WriteFile(ImageFilePath, FileContent, FileName + ".png", out Err); if (upres) { //清除文件 File.Delete(PdfFilePath + FileName + ".PDF"); //生成PDF PDFHelper.ConvertJpgToPdf(ImageFilePath + FileName + ".png", PdfFilePath + FileName + ".PDF"); //上盯盘 string fileName = PdfFilePath + FileName + ".PDF"; var uploadFileModel = new UploadMediaRequestModel() { FileName = fileName, MediaType = UploadMediaType.File }; DingTalkManager dingTalkManager = new DingTalkManager(); string UploadFileResult = await dingTalkManager.UploadFile(uploadFileModel); FileSendModel fileSendModel = JsonConvert.DeserializeObject <FileSendModel>(UploadFileResult); //替换数据库MediaId using (DDContext context = new DDContext()) { Tasks tasks = context.Tasks.Where(t => t.TaskId.ToString() == fileModel.TaskId && t.NodeId == 0).First(); tasks.MediaIdPDF = tasks.MediaIdPDF.Replace(fileModel.OldMediaId, fileSendModel.Media_Id); result = tasks.MediaIdPDF; context.Entry <Tasks>(tasks).State = System.Data.Entity.EntityState.Modified; context.SaveChanges(); } } else { result = "上传文件写入失败:" + Err; } } else { result = "上传的文件信息不存在!"; } return(new ErrorModel() { errorCode = 0, errorMessage = "保存成功", Content = result }); } catch (Exception ex) { throw ex; } }
private static void Main(string[] args) { Task.Run(() => { try { // initialize settings Init(); Console.WriteLine($"Processor is now running..."); ConnectionFactory factory = new ConnectionFactory(); factory.UserName = ApplicationSettings.RabbitMQUsername; factory.Password = ApplicationSettings.RabbitMQPassword; factory.HostName = ApplicationSettings.RabbitMQHostname; factory.Port = ApplicationSettings.RabbitMQPort; factory.RequestedHeartbeat = 60; factory.DispatchConsumersAsync = true; var connection = factory.CreateConnection(); var channel = connection.CreateModel(); channel.QueueDeclare(queue: ApplicationSettings.DispatchQueueName, durable: true, exclusive: false, autoDelete: false, arguments: null); channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false); var consumer = new AsyncEventingBasicConsumer(channel); consumer.Received += async(model, ea) => { DispatchResponse response = new DispatchResponse { IsSucceded = true, ResultId = (int)DispatchResponseEnum.Success }; // forced-to-disposal Report report = null; PDFHelper pdfHelper = null; MongoDBHelper mongoDBHelper = null; SendGridHelper sendGridHelper = null; try { byte[] body = ea.Body; var message = Encoding.UTF8.GetString(body); var decrypted = string.Empty; decrypted = NETCore.Encrypt.EncryptProvider.AESDecrypt(message, secret); var obj_decrypted = JsonConvert.DeserializeObject <DispatchMessage>(decrypted); //operation id string guid = Guid.NewGuid().ToString(); // PDF string pdf = string.Empty; pdfHelper = new PDFHelper(); pdf = pdfHelper.Create(guid, converter, obj_decrypted); Console.WriteLine($">> PDF generated successfully"); // MongoDB report = new Report(); report.fullname = obj_decrypted.Fullname; report.email = obj_decrypted.Email; mongoDBHelper = new MongoDBHelper(mongoDBConnectionInfo); await mongoDBHelper.RegisterReportAsync(report); Console.WriteLine($">> Record saved successfully"); // SendGrid sendGridHelper = new SendGridHelper(); await sendGridHelper.SendReportEmailAsync(obj_decrypted.Email, obj_decrypted.Fullname, pdf); Console.WriteLine($">> Email: {obj_decrypted.Email} sent successfully"); channel.BasicAck(ea.DeliveryTag, false); Console.WriteLine($">> Acknowledgement completed, delivery tag: {ea.DeliveryTag}"); } catch (Exception ex) { if (ex is BusinessException) { response.IsSucceded = false; response.ResultId = ((BusinessException)ex).ResultId; string message = EnumDescription.GetEnumDescription((DispatchResponseEnum)response.ResultId); Console.WriteLine($">> Message information: {message}"); } else { Console.WriteLine($">> Exception: {ex.Message}, StackTrace: {ex.StackTrace}"); if (ex.InnerException != null) { Console.WriteLine($">> Inner Exception Message: {ex.InnerException.Message}, Inner Exception StackTrace: {ex.InnerException.StackTrace}"); } } } finally { report = null; pdfHelper.Dispose(); mongoDBHelper.Dispose(); sendGridHelper.Dispose(); } }; string consumerTag = channel.BasicConsume(ApplicationSettings.DispatchQueueName, false, consumer); } catch (Exception ex) { Console.WriteLine($">> Exception: {ex.Message}, StackTrace: {ex.StackTrace}"); if (ex.InnerException != null) { Console.WriteLine($">> Inner Exception Message: {ex.InnerException.Message}, Inner Exception StackTrace: {ex.InnerException.StackTrace}"); } } }); // handle Control+C or Control+Break Console.CancelKeyPress += (o, e) => { Console.WriteLine("Exit"); // allow the manin thread to continue and exit... waitHandle.Set(); }; // wait waitHandle.WaitOne(); }
protected void btnpl_Click(object sender, EventArgs e) { try { PDFHelper _pdfhelper = new PDFHelper(); _pdfhelper.GeneratePDF(ViewState["EstNum"].ToString(), "Y"); DataSet dsGridResults = this.GetEmailLog(); this.PopulateDataGrid(dsGridResults, grdEmailLog); } catch (Exception) { throw; } }
public async Task <object> PrintAndSend([FromBody] PrintModel printAndSendModel) { try { string TaskId = printAndSendModel.TaskId; string UserId = printAndSendModel.UserId; PDFHelper pdfHelper = new PDFHelper(); using (DDContext context = new DDContext()) { //获取表单信息 Tasks tasks = context.Tasks.Where(t => t.TaskId.ToString() == TaskId && t.NodeId == 0).First(); string FlowId = tasks.FlowId.ToString(); //判断流程是否已结束 List <Tasks> tasksList = context.Tasks.Where(t => t.TaskId.ToString() == TaskId && t.State == 0 && t.IsSend == false).ToList(); if (tasksList.Count > 0) { return(new NewErrorModel() { error = new Error(1, "流程尚未结束", "") { }, }); } List <OfficeSuppliesPurchase> OfficeSuppliesPurchaseList = context.OfficeSuppliesPurchase.Where(u => u.TaskId == TaskId && u.IsDelete != true).ToList(); var SelectGoDownList = from g in OfficeSuppliesPurchaseList select new { g.CodeNo, g.Name, g.Standard, g.Unit, g.Count, g.Price }; DataTable dtSourse = DtLinqOperators.CopyToDataTable(SelectGoDownList); //ClassChangeHelper.ToDataTable(SelectPurchaseList); List <NodeInfo> NodeInfoList = context.NodeInfo.Where(u => u.FlowId == FlowId && u.NodeId != 0 && u.IsSend != true && u.NodeName != "结束").ToList(); foreach (NodeInfo nodeInfo in NodeInfoList) { if (string.IsNullOrEmpty(nodeInfo.NodePeople)) { string strNodePeople = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyMan; string ApplyTime = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyTime; nodeInfo.NodePeople = strNodePeople + " " + ApplyTime; } else { Tasks tasksNew = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First(); nodeInfo.NodePeople = nodeInfo.NodePeople + " " + tasksNew.ApplyTime + " " + tasksNew.Remark; } } DataTable dtApproveView = ClassChangeHelper.ToDataTable(NodeInfoList); string FlowName = context.Flows.Where(f => f.FlowId.ToString() == FlowId).First().FlowName.ToString(); //绘制BOM表单PDF List <string> contentList = new List <string>() { "序号", "物料编码", "物料名称", "规格型号", "单位", "数量", "预计单价" }; float[] contentWithList = new float[] { 50, 90, 90, 90, 60, 60, 60 }; float sum = 0; foreach (var item in OfficeSuppliesPurchaseList) { sum += (float.Parse(item.Price) * float.Parse(item.Count)); } Dictionary <string, string> keyValuePairs = new Dictionary <string, string>(); keyValuePairs.Add("总价", sum.ToString()); string path = pdfHelper.GeneratePDF(FlowName, TaskId, tasks.ApplyMan, tasks.Dept, tasks.ApplyTime, null, null, "2", 300, 650, contentList, contentWithList, dtSourse, dtApproveView, null, keyValuePairs); string RelativePath = "~/UploadFile/PDF/" + Path.GetFileName(path); List <string> newPaths = new List <string>(); RelativePath = AppDomain.CurrentDomain.BaseDirectory + RelativePath.Substring(2, RelativePath.Length - 2).Replace('/', '\\'); newPaths.Add(RelativePath); string SavePath = string.Format(@"{0}\UploadFile\Ionic\{1}.zip", AppDomain.CurrentDomain.BaseDirectory, FlowName + DateTime.Now.ToString("yyyyMMddHHmmss")); //文件压缩打包 IonicHelper.CompressMulti(newPaths, SavePath, false); //上传盯盘获取MediaId SavePath = string.Format(@"~\UploadFile\Ionic\{0}", Path.GetFileName(SavePath)); DingTalkServersController dingTalkServersController = new DingTalkServersController(); var resultUploadMedia = await dingTalkServersController.UploadMedia(SavePath); //推送用户 FileSendModel fileSendModel = JsonConvert.DeserializeObject <FileSendModel>(resultUploadMedia); fileSendModel.UserId = UserId; var result = await dingTalkServersController.SendFileMessage(fileSendModel); return(new NewErrorModel() { error = new Error(0, result, "") { }, }); } } catch (Exception ex) { throw ex; } }
public void CreateReport() { Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator = "."; logger.Info(string.Format("GetMostreFerma|CreateReport")); LocalReport report = new LocalReport(); byte[] file; string mimeType, encoding, fileExtension; string[] streams; Warning[] warnings; long reportNumber; ReportManager rManager = new ReportManager(ctx); Report dalReport = rManager.GetOrCreateReport(FCCLReportType.Crotalii, ObjectId , DropDownList1.SelectedItem.Text, TestDate, PrintDate, long.TryParse(TextBox3.Text, out reportNumber) ? (long?)reportNumber : null); TextBox3.Text = dalReport.ReportNumber.ToString(); ReportDataSource rds = new ReportDataSource(); rds.Name = "MostreFabrica"; List <MostreFabrica> mostre = MostreFabrica.GetMostreFerma(DropDownList1.SelectedValue, DateTime.Parse(TextBox1.Text)); logger.Info(string.Format("GetMostreFerma|mostre cnt:{0}", mostre.Count)); rds.Value = mostre; DateTime datatestare = DateTime.Parse(TextBox1.Text); DateTime datatmin = datatestare; DateTime datatmax = datatestare; string datatesttitlu = datatestare.ToShortDateString(); DateTime datapmin = DateTime.MaxValue; DateTime datapmax = DateTime.MinValue; string dataprimtitlu; string nrcomanda = ""; string combi = mostre[0].Combi; foreach (MostreFabrica mf in mostre) { DateTime datamin = mf.DataTestare; DateTime datamax = mf.DataTestareFinala; if (mf.NrComanda.Trim() != "") { nrcomanda = mf.NrComanda.Trim(); } if (DateTime.Compare(datamin, datatmin) < 0) { datatmin = datamin; } if (DateTime.Compare(datamax, datatmax) > 0) { datatmax = datamax; } if (DateTime.Compare(mf.DataPrimirii, datapmin) < 0) { datapmin = mf.DataPrimirii; } if (DateTime.Compare(mf.DataPrimirii, datapmax) > 0) { datapmax = mf.DataPrimirii; } } if (datatmin != datatmax) { datatesttitlu = datatmin.ToShortDateString() + " - " + datatmax.ToShortDateString(); } if (datapmin != datapmax) { dataprimtitlu = datapmin.ToShortDateString() + " si " + datapmax.ToShortDateString(); } else { dataprimtitlu = datapmin.ToShortDateString(); } rds.Value = mostre; report.DataSources.Clear(); report.DataSources.Add(rds); report.ReportPath = "ReportCrotalii.rdlc"; report.Refresh(); string fermaid = DropDownList1.SelectedValue; string fermaname = DropDownList1.Items[DropDownList1.SelectedIndex].ToString(); // read fabrica SqlConnection cnn = new SqlConnection( ConfigurationManager.ConnectionStrings ["fccl2ConnectionString"].ConnectionString); SqlCommand cmd = new SqlCommand(); cmd.Connection = cnn; cmd.CommandText = "SELECT Ferme_CCL.Cod,Ferme_CCL.Strada,Ferme_CCL.Numar,Ferme_CCL.Oras,Judete.Denloc " + "FROM Ferme_CCL,Judete WHERE Ferme_CCL.ID=" + fermaid + " AND Ferme_CCL.Judet=Judete.ID"; cnn.Open(); SqlDataReader reader = cmd.ExecuteReader(); reader.Read(); string fermastrada = Convert.ToString(reader["Strada"]); string fermanumar = Convert.ToString(reader["Numar"]); string fermaoras = Convert.ToString(reader["Oras"]); string fermajudet = Convert.ToString(reader["Denloc"]); string fermacod = Convert.ToString(reader["Cod"]); reader.Close(); cnn.Close(); cmd.CommandText = "SELECT Fabrici.Nume, Ferme_CCL.FabricaID from Ferme_CCL, Fabrici " + " WHERE Ferme_CCL.ID =" + fermaid + " AND Ferme_CCL.FabricaID = Fabrici.ID"; cnn.Open(); reader = cmd.ExecuteReader(); reader.Read(); string asocid = Convert.ToString(reader["FabricaID"]); string asocnume = Convert.ToString(reader["Nume"]); reader.Close(); cnn.Close(); FermaName.Text = fermaname; FermaCod.Text = fermacod; FermaId.Text = "" + fermaid; string datab = TextBox2.Text; string nrb = dalReport.ReportNumber.ToString(); //set report parameters string laborator = ddlLaborator.Items[ddlLaborator.SelectedIndex].ToString(); string responsabil = ddlResponsabil.Items[ddlResponsabil.SelectedIndex].ToString(); ReportParameter pAsocnume = new ReportParameter("asocnume", asocnume); ReportParameter pNrcomanda = new ReportParameter("nrcomanda", nrcomanda); ReportParameter pDatatestare = new ReportParameter("datatestare", datatesttitlu); ReportParameter pDataprimirii = new ReportParameter("dataprimirii", dataprimtitlu); ReportParameter pCombi = new ReportParameter("combi", combi); ReportParameter pDatab = new ReportParameter("datab", TextBox2.Text); ReportParameter pNrb = new ReportParameter("nrb", nrb); ReportParameter pFermanume = new ReportParameter("fabricanume", fermaname); ReportParameter pFermastrada = new ReportParameter("fabricastrada", fermastrada); ReportParameter pFermanumar = new ReportParameter("fabricanumar", fermanumar); ReportParameter pFermaoras = new ReportParameter("fabricaoras", fermaoras); ReportParameter pFermajudet = new ReportParameter("fabricajudet", fermajudet); ReportParameter pLaborator = new ReportParameter("laborator", laborator); ReportParameter pResponsabil = new ReportParameter("responsabil", responsabil); ReportParameter pVersiune = new ReportParameter("Versiune", new SettingManager(StaticDataHelper.FCCLDbContext).GetValueByName("ReportCrotalii")); ReportParameter[] p = { pDatatestare, pDataprimirii, pCombi, pNrcomanda, pDatab, pNrb, pFermanume, pFermastrada, pFermanumar, pFermaoras, pFermajudet, pAsocnume, pLaborator , pResponsabil, pVersiune }; report.SetParameters(p); file = report.Render("PDF", StaticData.DEVICE_INFO_PDF, out mimeType, out encoding, out fileExtension, out streams, out warnings); string httppath = StaticDataHelper.SettingsManager.CaleRapoarteHttp; string filepath = StaticDataHelper.SettingsManager.CaleRapoarte; fermaname = replace_special_car_null(fermaname); string nrcom = nrcomanda.Replace("/", "_"); nrcom = nrcom.Replace(".", ""); string raport_name = "Raport" + nrcom + "-" + fermaname + "_" + fermacod + "-" + datatestare.ToShortDateString().Replace("/", "") + ".pdf"; string raport_excel = "Raport" + nrcom + "-" + fermaname + "_" + fermacod + "-" + datatestare.ToShortDateString().Replace("/", "") + ".xls"; string path_raport_http = "http://" + Request.ServerVariables.Get("HTTP_HOST") + "/" + httppath; string pdf_link = path_raport_http + @"Ferme/" + raport_name; string pdf_file = filepath + @"Ferme/" + raport_name; // writefile string excel_link = path_raport_http + @"Ferme/" + raport_excel; string excel_file = filepath + @"Ferme/" + raport_excel; // Trace.Write(pdf_file); File.WriteAllBytes(pdf_file, file); logger.Info(string.Format("GetMostreFerma|pdf done")); dalReport.SampleCount = mostre.Count; dalReport.PageCount = PDFHelper.GetNumberOfPdfPages(pdf_file); rManager.Save(dalReport); ctx.SaveChanges(); logger.Info(string.Format("GetMostreFerma|saved report")); // raport excel LocalReport rapexcel = new LocalReport(); ReportDataSource rdse = new ReportDataSource(); rdse.Name = "MostreFabrica"; rdse.Value = mostre; rapexcel.DataSources.Clear(); rapexcel.DataSources.Add(rdse); rapexcel.ReportPath = "ReportCrotalii.rdlc"; rapexcel.SetParameters(p); rapexcel.Refresh(); rapexcel.SetParameters(new ReportParameter("BkImage", "")); byte[] file_xls = rapexcel.Render("EXCEL", StaticData.DEVICE_INFO_XLS, out mimeType, out encoding, out fileExtension, out streams, out warnings); // end raport excel File.WriteAllBytes(excel_file, file_xls); logger.Info(string.Format("GetMostreFerma|excel done")); int firstyear; if (int.TryParse(ConfigurationManager.AppSettings["firstyear"], out firstyear)) { // test rep. portal SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString); SqlCommand cmda = new SqlCommand("Select aspnet_Users.UserName from aspnet_users join usersinformation on aspnet_Users.userid = usersinformation.userid where usersinformation.asocid=" + asocid, connection); connection.Open(); string username = ""; using (SqlDataReader rdr = cmda.ExecuteReader()) { if (rdr.Read()) { username = rdr["UserName"].ToString(); } rdr.Close(); } connection.Close(); if (username.Length > 0) { try { MembershipUser User = Membership.Providers["PortalProvider"].GetUser(username, false); Username.Text = User.UserName; //Start generating from test date for (int year = firstyear; year <= DateTime.Now.Year; year++) { logger.Info(string.Format("GetMostreFerma|ext call year:{0}", year)); CreateReportExt(year); } } catch { } } } string raport_csv = "CSV_Registru_" + datatestare.ToShortDateString().Replace("/", "") + "_" + fermaid + "_" + fermaname + ".csv"; string csv_link = path_raport_http + @"Registru/" + raport_csv; string csv_file = filepath + @"Registru/" + raport_csv; logger.Info(string.Format("CreateReportExt|write csv file {0}", csv_file)); CreateExcelFile(mostre, csv_file); logger.Info(string.Format("GetMostreFerma|processing done")); pdflink.Visible = true; pdflink.NavigateUrl = pdf_link; pdflink.Text = raport_name; xlslink.Visible = true; xlslink.NavigateUrl = excel_link; xlslink.Text = raport_excel; csvlink.Visible = true; csvlink.NavigateUrl = csv_link; csvlink.Text = raport_csv; }
public bool ConvertToPDF(DocumentSettings settings, string outputFileName) { MsoTriState msoTriState; bool flag; try { string tempPath = Path.GetTempPath(); Guid guid = Guid.NewGuid(); string str = Path.Combine(tempPath, string.Concat("aquaforest\\pdftoolkit\\", guid.ToString(), "\\", Path.GetFileName(this.filePath))); PDFHelper.CheckOutputFolder(Path.GetDirectoryName(str)); System.IO.File.Copy(this.filePath, str); string str1 = str; object missing = Type.Missing; object obj = Type.Missing; object missing1 = Type.Missing; object obj1 = this.password; object obj2 = this.password; object missing2 = Type.Missing; object obj3 = this.password; object obj4 = this.password; object missing3 = Type.Missing; object missing4 = Type.Missing; object missing5 = Type.Missing; object openAndRepair = settings.OpenAndRepair; object obj5 = Type.Missing; object missing6 = Type.Missing; object obj6 = Type.Missing; Application applicationClass = new ApplicationClass(); Presentation pageOrientation = applicationClass.Presentations.Open(str1, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse); msoTriState = (!this.FrameSlides ? MsoTriState.msoFalse : MsoTriState.msoTrue); if (settings.orientatinIset) { pageOrientation.PageSetup.SlideOrientation = (MsoOrientation)settings.PageOrientation; } if ((settings.PageHeight <= 0f ? false : settings.PageWidth > 0f)) { pageOrientation.PageSetup.SlideHeight = settings.PageHeight; pageOrientation.PageSetup.SlideWidth = settings.PageWidth; } else if (this.slideSizeIsSet) { pageOrientation.PageSetup.SlideSize = (PpSlideSizeType)this.SlideSize; } if (!settings.ConvertHyperLinks) { object obj7 = 1; foreach (Slide slide in pageOrientation.Slides) { while (slide.Hyperlinks.Count > 0) { foreach (Hyperlink hyperlink in slide.Hyperlinks) { hyperlink.Delete(); } } } } AquaforestPDFOptimizeFor optimizeFor = settings.OptimizeFor; AquaforestPrintHandoutOrder powerPointHandoutOrder = this.PowerPointHandoutOrder; bool bitmapNonEmbeddableFonts = this.BitmapNonEmbeddableFonts; pageOrientation.ExportAsFixedFormat(outputFileName, PpFixedFormatType.ppFixedFormatTypePDF, (PpFixedFormatIntent)optimizeFor, msoTriState, (PpPrintHandoutOrder)powerPointHandoutOrder, PpPrintOutputType.ppPrintOutputSlides, MsoTriState.msoFalse, null, PpPrintRangeType.ppPrintAll, "", settings.IncludeDocumentProperty, true, true, bitmapNonEmbeddableFonts, settings.PDFA1a, Type.Missing); pageOrientation.Close(); applicationClass.Quit(); if (System.IO.File.Exists(outputFileName)) { PDFHelper.DisplayTrialPopupIfNecessary(); PDDocument pDDocument = PDDocument.load(new java.io.File(outputFileName)); PDFHelper.AddTrialStampIfNecessary(pDDocument, false); pDDocument.save(outputFileName); pDDocument.close(); } PDFHelper.EmptyDirectory(Path.GetDirectoryName(str)); flag = true; } catch (Exception exception1) { Exception exception = exception1; throw new AquaforestOfficeException(exception.Message, exception); } return(flag); }
public bool ConvertToPDF(DocumentSettings settings, string outputFileName) { bool docStructureTags; bool bitmapNonEmbeddableFonts; bool flag; try { string tempPath = Path.GetTempPath(); Guid guid = Guid.NewGuid(); string str = Path.Combine(tempPath, string.Concat("aquaforest\\pdftoolkit\\", guid.ToString(), "\\", Path.GetFileName(this.filePath))); PDFHelper.CheckOutputFolder(Path.GetDirectoryName(str)); System.IO.File.Copy(this.filePath, str); string str1 = str; object missing = Type.Missing; bool flag1 = false; bool flag2 = false; object obj = this.password; object obj1 = this.password; object missing1 = Type.Missing; object obj2 = this.password; object obj3 = this.password; object missing2 = Type.Missing; object missing3 = Type.Missing; object missing4 = Type.Missing; object openAndRepair = settings.OpenAndRepair; object obj4 = Type.Missing; object missing5 = Type.Missing; object obj5 = Type.Missing; Application applicationClass = new ApplicationClass(); Document marginLeft = applicationClass.Open(str1, flag1, flag2, PbSaveOptions.pbDoNotSaveChanges); if (settings.MarginLeft > 0f) { marginLeft.PageSetup.LeftMargin = settings.MarginLeft; } if (settings.MarginTop > 0f) { marginLeft.PageSetup.TopMargin = settings.MarginTop; } if (!settings.ConvertHyperLinks) { foreach (Page page in marginLeft.Pages) { foreach (Shape shape in page.Shapes) { shape.Hyperlink.Delete(); } } } if ((settings.FromPage <= 0 ? true : settings.ToPage <= 0)) { bitmapNonEmbeddableFonts = this.BitmapNonEmbeddableFonts; docStructureTags = this.DocStructureTags; marginLeft.ExportAsFixedFormat(PbFixedFormatType.pbFixedFormatTypePDF, outputFileName, PbFixedFormatIntent.pbIntentPrinting, settings.IncludeDocumentProperty, -1, -1, -1, -1, -1, -1, -1, true, PbPrintStyle.pbPrintStyleDefault, docStructureTags, bitmapNonEmbeddableFonts, settings.PDFA1a, Type.Missing); } else { bool bitmapNonEmbeddableFonts1 = this.BitmapNonEmbeddableFonts; docStructureTags = this.DocStructureTags; bool includeDocumentProperty = settings.IncludeDocumentProperty; bitmapNonEmbeddableFonts = settings.PDFA1a; marginLeft.ExportAsFixedFormat(PbFixedFormatType.pbFixedFormatTypePDF, outputFileName, PbFixedFormatIntent.pbIntentPrinting, includeDocumentProperty, -1, -1, -1, -1, settings.FromPage, settings.ToPage, -1, true, PbPrintStyle.pbPrintStyleDefault, docStructureTags, bitmapNonEmbeddableFonts1, bitmapNonEmbeddableFonts, Type.Missing); } marginLeft.Close(); applicationClass.Quit(); if (System.IO.File.Exists(outputFileName)) { PDFHelper.DisplayTrialPopupIfNecessary(); PDDocument pDDocument = PDDocument.load(new java.io.File(outputFileName)); PDFHelper.AddTrialStampIfNecessary(pDDocument, false); pDDocument.save(outputFileName); pDDocument.close(); } PDFHelper.EmptyDirectory(Path.GetDirectoryName(str1)); flag = true; } catch (Exception exception1) { Exception exception = exception1; throw new AquaforestOfficeException(exception.Message, exception); } return(flag); }
/// <summary> /// 顯示查詢結果 /// </summary> protected void ShowQryResult() { //初始 DivQryResult.Visible = true; UserInfo oUser = UserInfo.getUserInfo(); //顯示欄位 Dictionary <string, string> dicDisplay = new Dictionary <string, string>(); dicDisplay.Clear(); dicDisplay.Add("UserID", "員編"); dicDisplay.Add("UserName", "姓名"); dicDisplay.Add("CompName", "公司"); dicDisplay.Add("DeptName", "單位@L200"); dicDisplay.Add("UserKindName", "類別"); dicDisplay.Add("UserStatusName", "狀態"); dicDisplay.Add("UserTel", "電話"); dicDisplay.Add("UserMail", "信箱"); ucGridView_Fix.ucDataDisplayDefinition = dicDisplay; //===== GridView_Roll ===== //示範欄位捲動功能 ucGridView_Roll.ucDBName = _DBName; ucGridView_Roll.ucDataQrySQL = _QryResultSQL; ucGridView_Roll.ucDataKeyList = _PKList; ucGridView_Roll.ucDataDisplayDefinition = dicDisplay; ucGridView_Roll.ucSortEnabled = true; ucGridView_Roll.ucDisplayOnly = true; ucGridView_Roll.ucSelectRowEnabled = true; //可整列選取 ucGridView_Roll.ucFreezeHeaderEnabled = true; //凍結表頭(會自動強制資料不折行) ucGridView_Roll.ucFreezeColQty = 3; //凍結欄位(若不設定則只鎖定表頭) ucGridView_Roll.ucPageSize = 30; //方便示範表頭鎖定效果 ucGridView_Roll.Refresh(true); //===== GridView Fix ===== //設定全域 PDF 版面(Optional) PDFHelper oPDF = PDFHelper.getPDFHelper(true); oPDF.PageSize = PDFHelper.PDFPageSize.A3; //紙張 oPDF.IsLandscapePage = true; //橫印 oPDF.FontName = PDFHelper.PDFFont.Kai; //字體 //設定 PDF 匯出參數 ucGridView_Fix.ucExportPdfEnabled = true; ucGridView_Fix.ucExportPdfTitle = "員工基本資料"; ucGridView_Fix.ucExportPdfWaterMark = oUser.DefaultWatermarkText; ucGridView_Fix.ucExportPdfWaterMarkTextSize = 72; //設定 OpenXml 匯出參數 ucGridView_Fix.ucExportOpenXmlEnabled = true; ucGridView_Fix.ucExportOpenXmlPassword = Util.getRandomCode(); //亂數產生密碼 ucGridView_Fix.ucExportOpenXmlHeader = "部門員工資料表"; //表頭 2017.03.21 ucGridView_Fix.ucExportOpenXmlFooter = " ●員工資料有密碼保護\n ●僅供內部使用"; //表尾 2017.03.21 ucGridView_Fix.ucDBName = _DBName; ucGridView_Fix.ucDataQrySQL = _QryResultSQL; ucGridView_Fix.ucDataKeyList = _PKList; ucGridView_Fix.ucSortEnabled = true; //表頭欄位合併 ucGridView_Fix.ucHeaderColSpanQtyList = "3,5"; ucGridView_Fix.ucHeaderColSpanCaptionList = "識 別,一 般 資 訊"; ucGridView_Fix.ucCmdBtnHorizontalAlign = HorizontalAlign.Center; //按鈕水平對齊 2016.07.28 新增 ucGridView_Fix.ucSelectEnabled = true; ucGridView_Fix.ucSelectRowEnabled = true; //可整列選取 ucGridView_Fix.ucPageSize = 100; //每頁筆數 ucGridView_Fix.ucDataGroupKey = "DeptName"; //設定群組 ucGridView_Fix.Refresh(true); }
public async Task <NewErrorModel> PrintAndSend([FromBody] PrintAndSendModel printAndSendModel) { try { string TaskId = printAndSendModel.TaskId; string UserId = printAndSendModel.UserId; PDFHelper pdfHelper = new PDFHelper(); using (DDContext context = new DDContext()) { //获取表单信息 Tasks tasks = context.Tasks.Where(t => t.TaskId.ToString() == TaskId && t.NodeId == 0).First(); string FlowId = tasks.FlowId.ToString(); //判断流程是否已结束 List <Tasks> tasksList = context.Tasks.Where(t => t.TaskId.ToString() == TaskId && t.State == 0 && t.IsSend == false).ToList(); if (tasksList.Count > 0) { return(new NewErrorModel { error = new Error(1, "流程尚未结束", "") { }, }); } MaterialRelease ct = context.MaterialRelease.Where(u => u.TaskId == TaskId).FirstOrDefault(); Dictionary <string, string> keyValuePairs = new Dictionary <string, string>(); keyValuePairs.Add("单位名称", ct.Company); keyValuePairs.Add("车牌号", ct.CarNo); keyValuePairs.Add("联系方式", ct.Tel); keyValuePairs.Add("物品名称", ct.Name); keyValuePairs.Add("数量", ct.Count); keyValuePairs.Add("单位", ct.Unit); keyValuePairs.Add("放行理由", ct.Cause); keyValuePairs.Add("放行日期", ct.Date); List <NodeInfo> NodeInfoList = context.NodeInfo.Where(u => u.FlowId == FlowId && u.NodeId != 0 && u.IsSend != true && u.NodeName != "结束").ToList(); foreach (NodeInfo nodeInfo in NodeInfoList) { if (string.IsNullOrEmpty(nodeInfo.NodePeople)) { string strNodePeople = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyMan; string ApplyTime = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyTime; nodeInfo.NodePeople = strNodePeople + " " + ApplyTime; } else { string ApplyTime = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyTime; nodeInfo.NodePeople = nodeInfo.NodePeople + " " + ApplyTime; } } DataTable dtApproveView = ClassChangeHelper.ToDataTable(NodeInfoList); string FlowName = context.Flows.Where(f => f.FlowId.ToString() == FlowId).First().FlowName.ToString(); string path = pdfHelper.GeneratePDF(FlowName, TaskId, tasks.ApplyMan, tasks.Dept, tasks.ApplyTime, null, null, "2", 300, 650, null, null, null, dtApproveView, keyValuePairs); string RelativePath = "~/UploadFile/PDF/" + Path.GetFileName(path); List <string> newPaths = new List <string>(); RelativePath = AppDomain.CurrentDomain.BaseDirectory + RelativePath.Substring(2, RelativePath.Length - 2).Replace('/', '\\'); newPaths.Add(RelativePath); string SavePath = string.Format(@"{0}\UploadFile\Ionic\{1}.zip", AppDomain.CurrentDomain.BaseDirectory, FlowName + DateTime.Now.ToString("yyyyMMddHHmmss")); //文件压缩打包 IonicHelper.CompressMulti(newPaths, SavePath, false); //上传盯盘获取MediaId DingTalkServersController otherController = new DingTalkServersController(); SavePath = string.Format(@"~\UploadFile\Ionic\{0}", Path.GetFileName(SavePath)); var resultUploadMedia = await otherController.UploadMedia(SavePath); //推送用户 FileSendModel fileSendModel = JsonConvert.DeserializeObject <FileSendModel>(resultUploadMedia); fileSendModel.UserId = UserId; var result = await otherController.SendFileMessage(fileSendModel); return(new NewErrorModel() { error = new Error(0, "已推送至钉钉!", "") { }, }); } } catch (Exception ex) { throw ex; } }
private void Button1_Click(object sender, EventArgs e) { string password = PDFHelper.MakeReadOnly("C:/Users/Chelsea/Documents/input1.pdf", "C:/Users/Chelsea/Documents/testfinalrandom1234.pdf"); }
public async Task <object> GetPrintPDF(string TaskId, string UserId) { try { PDFHelper pdfHelper = new PDFHelper(); using (DDContext context = new DDContext()) { //获取表单信息 Tasks tasks = context.Tasks.Where(t => t.TaskId.ToString() == TaskId && t.NodeId == 0).First(); string FlowId = tasks.FlowId.ToString(); //判断流程是否已结束 List <Tasks> tasksList = context.Tasks.Where(t => t.TaskId.ToString() == TaskId && t.State == 0 && t.IsSend == false).ToList(); if (tasksList.Count > 0) { return(JsonConvert.SerializeObject(new NewErrorModel { error = new Error(1, "流程尚未结束", "") { }, })); } List <GiftTable> giftTables = context.GiftTable.Where(u => u.TaskId == TaskId).ToList(); var giftTableList = from g in giftTables select new { g.GiftName, g.GiftCount }; List <NodeInfo> NodeInfoList = context.NodeInfo.Where(u => u.FlowId == FlowId && u.NodeId != 0 && u.IsSend != true && u.NodeName != "结束").ToList(); //绘制BOM表单PDF List <string> contentList = new List <string>() { "序号", "礼品名称", "数量" }; float[] contentWithList = new float[] { 50, 500, 100 }; //Dictionary<string, string> keyValuePairs = new Dictionary<string, string>(); //keyValuePairs.Add("用途及使用说明", tasks.Remark); foreach (NodeInfo nodeInfo in NodeInfoList) { if (string.IsNullOrEmpty(nodeInfo.NodePeople)) { string strNodePeople = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyMan; string ApplyTime = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyTime; nodeInfo.NodePeople = strNodePeople + " " + ApplyTime; } else { string ApplyTime = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyTime; nodeInfo.NodePeople = nodeInfo.NodePeople + " " + ApplyTime; } } DataTable dtApproveView = ClassChangeHelper.ToDataTable(NodeInfoList); DataTable dtGiftTables = DtLinqOperators.CopyToDataTable(giftTableList); string FlowName = context.Flows.Where(f => f.FlowId.ToString() == FlowId).First().FlowName.ToString(); string path = pdfHelper.GeneratePDF(FlowName, TaskId, tasks.ApplyMan, tasks.Dept, tasks.ApplyTime, null, null, "2", 300, 650, contentList, contentWithList, dtGiftTables, dtApproveView, null); string RelativePath = "~/UploadFile/PDF/" + Path.GetFileName(path); List <string> newPaths = new List <string>(); RelativePath = AppDomain.CurrentDomain.BaseDirectory + RelativePath.Substring(2, RelativePath.Length - 2).Replace('/', '\\'); newPaths.Add(RelativePath); string SavePath = string.Format(@"{0}\UploadFile\Ionic\{1}.zip", AppDomain.CurrentDomain.BaseDirectory, FlowName + DateTime.Now.ToString("yyyyMMddHHmmss")); //文件压缩打包 IonicHelper.CompressMulti(newPaths, SavePath, false); //上传盯盘获取MediaId SavePath = string.Format(@"~\UploadFile\Ionic\{0}", Path.GetFileName(SavePath)); DingTalkServersController dingTalkServersController = new DingTalkServersController(); var resultUploadMedia = await dingTalkServersController.UploadMedia(SavePath); //推送用户 FileSendModel fileSendModel = JsonConvert.DeserializeObject <FileSendModel>(resultUploadMedia); fileSendModel.UserId = UserId; var result = await dingTalkServersController.SendFileMessage(fileSendModel); return(result); } } catch (Exception ex) { throw ex; } }
public void ExportPurchaseOrderToPDF(Guid purchaseOrderId, Stream stream) { var model = ViewPurchaseOrdersDetails(purchaseOrderId); var document = PDFHelper.NewDocument(); document.WithDocumentInfo("PURCHASE ORDER", "COUNTRY OFFICE, UGANDA", "DRC"); var section = document.AddSection(); section.AddLogo(); section.AddVerticalSpacing("0.3cm"); section.AddHeading("PURCHASE ORDER", (heading, paragraph) => { heading.Width = "16cm"; heading.Height = "0.8cm"; paragraph.Format.Alignment = ParagraphAlignment.Center; var font = paragraph.Format.Font.Clone(); font.Size = 22.PixelsToUnitPoints(); font.Bold = true; paragraph.Format.Font = font; }); section.AddHeading("Date: {0}".F(model.POEntiy.PreparedOn.Value.ToShortDateString()), (textFrame, paragraph) => { textFrame.Width = Unit.FromCentimeter(14.0); textFrame.Height = "0.8cm"; }); var orderRequestTable = section.AddNewTable(new[] { "Purchase Order Number:", "Order Request Ref No.:", "Payment Terms:" }, new Unit[] { 1.76.Inches(), 1.88.Inches(), 1.69.Inches() }, row => { row.Shading.Color = PDFHelper.SkyCloudyBlueColor; row.Format.Font.Bold = true; row.Format.Alignment = ParagraphAlignment.Left; }, (cell, paragraph, columnIndex) => { cell.Format.Alignment = ParagraphAlignment.Left; }); orderRequestTable.AddNewRow(new[] { model.POEntiy.RefNumber, model.POEntiy.OrderRequest.RefNumber, model.paymentTerm }, row => { row.Height = 0.29.Inches(); row.Format.Font.Bold = true; }, (cell, paragraph, columnIndex) => { if (columnIndex == 0) { var font = cell.Format.Font.Clone(); cell.Format.Font = font; font.Color = PDFHelper.RedColor; } }); orderRequestTable.AddNewRow(new[] { "Quotation Ref.:", "Shipping/Delivery Terms:", "Latest Delivery Date:" }, row => { row.Shading.Color = PDFHelper.SkyCloudyBlueColor; row.Format.Font.Bold = true; row.Format.Alignment = ParagraphAlignment.Left; }, (cell, paragraph, columIndex) => { cell.Format.Alignment = ParagraphAlignment.Left; }); orderRequestTable.AddNewRow(new[] { model.POEntiy.QuotationRef, model.shippingTerm, model.POEntiy.LatestDeliveryDate.ToString("dd/MM/yyyy") }, row => { row.Height = 0.29.Inches(); row.Format.Font.Bold = true; }, (cell, paragraph, columnIndex) => { if (columnIndex == 1) { var font = cell.Format.Font.Clone(); cell.Format.Font = font; font.Color = PDFHelper.RedColor; } }); orderRequestTable.AddNewRow(new[] { "To Supplier:", "Delivery Address:", "DRC Internal use only:" }, row => { row.Shading.Color = PDFHelper.SkyCloudyBlueColor; row.Format.Font.Bold = true; row.Format.Alignment = ParagraphAlignment.Left; }, (cell, paragraph, columIndex) => { cell.Format.Alignment = ParagraphAlignment.Left; }); orderRequestTable.AddNewRow(new[] { model.supplier, model.POEntiy.Location.Name, "" }, row => { row.Height = 0.29.Inches(); row.Format.Font.Bold = true; }); section.AddVerticalSpacing("0.3cm"); var poItemsTable = section.AddNewTable( new[] { "No.", "Description", "Unit", "Qty", "Unit Price", "Total Price", "BL", "PN", "Remarks", }, new Unit[] { 0.33.Inches(), 2.25.Inches(), 0.44.Inches(), 0.56.Inches(), 0.75.Inches(), 0.75.Inches(), 0.44.Inches(), 0.63.Inches(), 1.13.Inches() }, row => { row.Shading.Color = PDFHelper.SkyCloudyBlueColor; row.Format.Font.Bold = true; }); poItemsTable.AddNewRows( model.POItems.Select((p, i) => new object[] { i + 1, p.EntityPOItem.OrderRequestItem.Item.Name, p.Unitmessue, p.Qunatity, p.EntityPOItem.UnitPrice.ToString("##,##0.00"), p.EntityPOItem.TotalPrice.ToString("##,##0.00"), p.BudgetLine, p.ProjectNo, p.EntityPOItem.Remarks }).ToArray()); poItemsTable.AddNewRow(new object[] { "Currency of Purchase Order", "", "", model.Currency, "Total", model.TotalAmount.FormatMoney(), "PO Value", "", "" }, null, (cell, paragraph, columnIndex) => { if (columnIndex < 1) { cell.MergeRight = 2; cell.Format.Alignment = ParagraphAlignment.Right; } if (columnIndex == 6) { cell.MergeRight = 2; cell.Format.Alignment = ParagraphAlignment.Left; } if (columnIndex < 3 || columnIndex == 4 || columnIndex > 5) { cell.Shading.Color = PDFHelper.SkyCloudyBlueColor; } }); //poItemsTable.AddNewRows(new object[][]{ new object[]{ "Currency of Purchase Order", "", "", model.Currency, "Total", model.TotalAmount.FormatMoney(), "PO Value", "", "" }, //new object[]{"Master Budget Currency","","",model.MBCurrency,"Total",model.MBValue.FormatMoney(), "PO Value", "", "" }}, // null, // (cell, paragraph, rowIndex, columnIndex) => // { // if (columnIndex < 1) { cell.MergeRight = 2; cell.Format.Alignment = ParagraphAlignment.Right; } // if (columnIndex == 6) { cell.MergeRight = 2; cell.Format.Alignment = ParagraphAlignment.Left; } // if (columnIndex < 3 || columnIndex == 4 || columnIndex > 5) // { // cell.Shading.Color = (rowIndex == 0) ? PDFHelper.SkyCloudyBlueColor : PDFHelper.GreenishGrayColor; // } // }); section.AddVerticalSpacing("0.3cm"); var authorizationTable = section.AddNewTable( new[] { "Authorization", "Authorized Requestor or Unit", "Finance Review/Approval of BL/PN", "Authorized by Manager/CD" }, new Unit[] { 0.95.Inches(), 2.0.Inches(), 2.13.Inches(), 2.19.Inches() }, null, (cell, paragraph, columnIndex) => { if (columnIndex == 0) { var font = paragraph.Format.Font.Clone(); font.Underline = Underline.Single; paragraph.Format.Font = font; } }); authorizationTable.AddNewRows( new[] { new object[] { "Name", "{0} {1}".F(model.StaffEntity.Person.FirstName, model.StaffEntity.Person.OtherNames), model.ReviewdBy, model.AuthorizdBy }, new object[] { "Title", model.StaffEntity.Designation.Name, model.ReviewTitle, model.AuthorizTitle }, new object[] { "Date", model.POEntiy.PreparedOn.Value.ToString("dd/MM/yyyy h:mm tt"), model.ReveiwDate, model.AuthorizDate }, new object[] { "Signature", "", "", "" } }, null, (cell, paragraph, rowIndex, columnIndex) => { if (rowIndex == 3 && columnIndex == 1) { cell.MergeRight = 2; } }); section.AddVerticalSpacing("0.3cm"); var instructionsTbale = section.AddNewTable(new[] { "General Instructions:", "Additional Instructions:" }, new Unit[] { 3.635.Inches(), 3.635.Inches() }, row => { row.Table.Borders.Visible = false; }, (cell, paragraph, columnIndex) => { var font = paragraph.Format.Font.Clone(); paragraph.Format.Font = font; font.Bold = true; font.Underline = Underline.Single; }); instructionsTbale.AddNewRow(new[] { "Please retain this original and return the copy duly signed and dated as evidence of your acceptance of this order.", "Please refer to above mentioned Purchase Order number in all correspondence concerning the order." }, row => row.Table.SetEdge(0, 0, 2, 2, Edge.Box, BorderStyle.Single, new Unit(0.5, UnitType.Point), Color.Empty)); section.AddVerticalSpacing("0.3cm"); section.AddHeading("Documentation Required from Supplier", (textFrame, paragraph) => { var font = paragraph.Format.Font.Clone(); paragraph.Format.Font = font; font.Color = PDFHelper.BlueColor; textFrame.Width = Unit.FromCentimeter(14.0); textFrame.Height = "0.8cm"; }); var documentationRequiredFromSupplierTable = section.AddTable(); documentationRequiredFromSupplierTable.AddColumn(1.8175.Inches()); documentationRequiredFromSupplierTable.AddColumn(1.8175.Inches()); documentationRequiredFromSupplierTable.AddColumn(1.8175.Inches()); documentationRequiredFromSupplierTable.AddColumn(1.8175.Inches()); documentationRequiredFromSupplierTable.AddNewRows( new[] { new object[] { "Pro-Forma Invoice", "Commercial Invoice", "Waybill/Airbill", "Packing List" }, new object[] { "Delivery Note", "Manuals", "Certificates", "" }, }, (row, index) => { row.VerticalAlignment = VerticalAlignment.Top; }, (cell, paragraph, rowIndex, columnIndex) => { cell.Format.Alignment = ParagraphAlignment.Left; paragraph.Format.Alignment = ParagraphAlignment.Left; string imageUrl; if ((rowIndex == 0 && (columnIndex == 0 || columnIndex == 2)) || (rowIndex == 1 && (columnIndex == 0 || columnIndex == 1))) { imageUrl = "/Content/reports/checked.gif"; } else { imageUrl = "/Content/reports/unchecked.gif"; } var image = new Image(HttpContext.Current.Server.MapPath(imageUrl)); image.WrapFormat.Style = WrapStyle.None; cell.Elements.InsertObject(0, image); paragraph.Format.LeftIndent = 18.PixelsToUnitPoints(); }); section.AddVerticalSpacing("0.3cm"); //section = document.AddNewSection(); section.AddHeading("Terms and Conditions", (textFrame, paragraph) => { var font = paragraph.Format.Font.Clone(); paragraph.Format.Font = font; font.Color = PDFHelper.BlueColor; textFrame.Width = Unit.FromCentimeter(14.0); textFrame.Height = "0.8cm"; }); var textWidth = document.DefaultPageSetup.PageWidth; textWidth -= document.DefaultPageSetup.LeftMargin; textWidth -= document.DefaultPageSetup.RightMargin; section.AddTextBlock(@"Receipt of the signed PO acknowledgement copy, supplier's written confirmation of order shall constitute acceptance of the order by the supplier, including all terms and conditions herein contained. Acceptance is limited to the terms herein stated or incorporated by reference and any additional or different terms or conditions proposed by the supplier are rejected unless expressly approved in writing by an authorised representative of the DRC/DDG. Prices on this purchase order are fixed and unalterable unless a replacement order is forwarded. All packages, Delivery Noted, Invoices and Shipping documents should indicate this unique purchase order number. All items must be delivered as stated in this purchase order. This Purchase Order supersedes all prior oral or written agreements, if any, between the parties and constitutes the entire agreement in respect of this purchase. In reference to your offer, we hereby place the following order, subject to the terms described herein and Danish Refugee Council General Conditions for Purchase Orders that are incorporated by reference, to supply the item(s) and quantities(s) written in the PO. "); section.AddVerticalSpacing("0.3cm"); section.AddHeading("Guarantee/Warranty", (textFrame, paragraph) => { var font = paragraph.Format.Font.Clone(); paragraph.Format.Font = font; font.Color = PDFHelper.BlueColor; textFrame.Width = textWidth; textFrame.Height = "0.8cm"; }); section.AddTextBlock(@"The supplier warrants that all items furnished hereunder are new and unused unless otherwise stated in PO. The supplier warrants that all the items furnished hereunder shall conform fully to all requirements of this order, shall conform to approved samples, if any, submitted against this requirement, shall be fit for the use for which they are intended, and shall be free from defects in material, workmanship and/or design."); section.AddVerticalSpacing("0.3cm"); section.AddHeading("Pre-financing Guarantee", (textFrame, paragraph) => { var font = paragraph.Format.Font.Clone(); paragraph.Format.Font = font; font.Color = PDFHelper.BlueColor; textFrame.Width = Unit.FromCentimeter(14.0); textFrame.Height = "0.8cm"; }); var prefinancingTimeFrame = section.AddTextFrame(); var prefinancingTimeFrameImage = new Image(HttpContext.Current.Server.MapPath("/Content/reports/unchecked.gif")); prefinancingTimeFrameImage.WrapFormat.Style = WrapStyle.None; prefinancingTimeFrame.Add(prefinancingTimeFrameImage); var prefinancingTimeFrameParagraph = prefinancingTimeFrame.AddParagraph( @" The supplier is required to establish a pre-financing guarantee through a first class bank of 50 percent of the total value of this order."); prefinancingTimeFrameParagraph.Format.LeftIndent = 18.PixelsToUnitPoints(); prefinancingTimeFrameParagraph.Format.Font = PDFHelper.CallibriFont11.Clone(); prefinancingTimeFrame.Width = textWidth; section.AddVerticalSpacing("0.3cm"); document.WriteAsPDFToStream(stream); }
/// Methods #region Methods /// <summary> /// Gets the data asynchronously /// </summary> private void GetDataAsync() { CancellationTokenSource source = new CancellationTokenSource(); // main auxiliary task to perform subtasks and notify system when everything is done Task t = new Task(() => { // task to update printers list Task t1 = new Task(() => { SetStatus("Update Printers"); // update printers if (!UpdatePrinters()) { source.Cancel(false); } SetStatus(); }); // task to convert PS to PDF and determine colors Task t2 = new Task(() => { // get colors // set status PDFFileName = PSFileName + ".pdf"; SetStatus("Convert to PDF"); GhostScriptHelper.ConvertPStoPDF(PSFileName, PDFFileName); SetStatus("Determine colors"); FileHasColor = PDFHelper.HasColor(PDFFileName); OnColorDetermined(EventArgs.Empty); SetStatus(); }); // task to get metadata from PS file Task t3 = new Task(() => { // get postscript data SetStatus("Get Print Data"); GetPSData(PSFileName); OnColorDetermined(EventArgs.Empty); SetStatus(); }); t1.Start(); t2.Start(); t3.Start(); // wait until every auxiliary task is completed Task.WaitAll(new Task[] { t1, t2, t3 }, source.Token); LogHelper.LogDebug("Task.WaitAll"); if (PostScriptMetaData != null) { PostScriptMetaData.HasColor = FileHasColor; } SetStatus("Set Printers"); // change printers ChangePrinters(); // release controls IsControlsEnabled = true; LogHelper.LogDebug("ReadyToPrint Before"); SetPrinterByVirtualPrinterSelected(); SetStatus("Ready to Print"); // notify system about readiness OnReadyToPrint(EventArgs.Empty); }); t.Start(); }
public async Task <object> PrintAndSend([FromBody] PrintModel printAndSendModel) { try { string TaskId = printAndSendModel.TaskId; string UserId = printAndSendModel.UserId; PDFHelper pdfHelper = new PDFHelper(); using (DDContext context = new DDContext()) { //获取表单信息 Tasks tasks = context.Tasks.Where(t => t.TaskId.ToString() == TaskId && t.NodeId == 0).First(); string FlowId = tasks.FlowId.ToString(); //判断流程是否已结束 List <Tasks> tasksList = context.Tasks.Where(t => t.TaskId.ToString() == TaskId && t.State == 0 && t.IsSend == false).ToList(); if (tasksList.Count > 0) { return(new NewErrorModel() { error = new Error(1, "流程尚未结束", "") { }, }); } CreateProject createProject = context.CreateProject.Where(u => u.TaskId == TaskId).First(); List <NodeInfo> NodeInfoList = context.NodeInfo.Where(u => u.FlowId == FlowId && u.NodeId != 0 && u.IsSend != true && u.NodeName != "结束").ToList(); foreach (NodeInfo nodeInfo in NodeInfoList) { if (string.IsNullOrEmpty(nodeInfo.NodePeople)) { string strNodePeople = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyMan; string ApplyTime = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyTime; nodeInfo.NodePeople = strNodePeople + " " + ApplyTime; } else { string ApplyTime = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyTime; nodeInfo.NodePeople = nodeInfo.NodePeople + " " + ApplyTime; } } DataTable dtApproveView = ClassChangeHelper.ToDataTable(NodeInfoList); string FlowName = context.Flows.Where(f => f.FlowId.ToString() == FlowId).First().FlowName.ToString(); Dictionary <string, string> keyValuePairs = new Dictionary <string, string>(); keyValuePairs.Add("项目名称", createProject.ProjectName); keyValuePairs.Add("项目编号", createProject.ProjectId); keyValuePairs.Add("承担部门", createProject.DeptName); keyValuePairs.Add("公司名称", createProject.CompanyName); keyValuePairs.Add("合作单位", string.IsNullOrEmpty(createProject.Customer)?"无": createProject.Customer); keyValuePairs.Add("项目类型", createProject.ProjectType + "-" + createProject.ProjectSmallType); keyValuePairs.Add("项目负责人", createProject.ResponsibleMan); keyValuePairs.Add("项目组成员", createProject.TeamMembers); keyValuePairs.Add("是否评审", createProject.IsReview == true ? "是" : "否"); string path = pdfHelper.GeneratePDF(FlowName, TaskId, tasks.ApplyMan, tasks.Dept, tasks.ApplyTime, null, null, "2", 300, 650, null, null, null, dtApproveView, null, keyValuePairs); string RelativePath = "~/UploadFile/PDF/" + Path.GetFileName(path); List <string> newPaths = new List <string>(); RelativePath = AppDomain.CurrentDomain.BaseDirectory + RelativePath.Substring(2, RelativePath.Length - 2).Replace('/', '\\'); newPaths.Add(RelativePath); string SavePath = string.Format(@"{0}\UploadFile\Ionic\{1}.zip", AppDomain.CurrentDomain.BaseDirectory, FlowName + DateTime.Now.ToString("yyyyMMddHHmmss")); //文件压缩打包 IonicHelper.CompressMulti(newPaths, SavePath, false); //上传盯盘获取MediaId SavePath = string.Format(@"~\UploadFile\Ionic\{0}", Path.GetFileName(SavePath)); DingTalkServersController dingTalkServersController = new DingTalkServersController(); var resultUploadMedia = await dingTalkServersController.UploadMedia(SavePath); //推送用户 FileSendModel fileSendModel = JsonConvert.DeserializeObject <FileSendModel>(resultUploadMedia); fileSendModel.UserId = UserId; var result = await dingTalkServersController.SendFileMessage(fileSendModel); return(new NewErrorModel() { error = new Error(0, result, "") { }, }); } } catch (Exception ex) { throw ex; } }
public async Task <NewErrorModel> PrintPDF(DDContext context, string ApplyManId, string TaskId, string UserId) { try { //获取表单信息 Tasks tasks = context.Tasks.Where(t => t.TaskId.ToString() == TaskId && t.NodeId == 0).First(); string FlowId = tasks.FlowId.ToString(); string ProjectId = tasks.ProjectId; //项目或合同Id PDFHelper pdfHelper = new PDFHelper(); List <PurchaseTable> purchaseTableList = context.PurchaseTable.Where(u => u.TaskId == TaskId).ToList(); var SelectPurchaseListOne = from p in purchaseTableList where p.PurchaseManId == ApplyManId select new { p.CodeNo, p.Name, p.Standard, p.Price, //预计价格 p.Unit, p.Count, p.UrgentDate, //需用日期 p.SendPosition, //送货地点 p.Purpose, p.Mark }; DataTable dtSourse = DtLinqOperators.CopyToDataTable(SelectPurchaseListOne); List <NodeInfo> NodeInfoList = context.NodeInfo.Where(u => u.FlowId == FlowId && u.NodeId != 0 && u.IsSend != true && u.NodeName != "结束").ToList(); foreach (NodeInfo nodeInfo in NodeInfoList) { //临时用作备注 nodeInfo.PreNodeId = context.Tasks.Where(t => t.TaskId.ToString() == tasks.TaskId.ToString() && t.NodeId == nodeInfo.NodeId).FirstOrDefault().Remark; if (!string.IsNullOrEmpty(nodeInfo.NodePeople)) { if (nodeInfo.NodePeople.Length > 3) { nodeInfo.NodePeople = nodeInfo.NodePeople.Substring(0, 3); } } if (nodeInfo.NodeName.ToString() == "采购员采购") { nodeInfo.NodePeople = ""; } if (string.IsNullOrEmpty(nodeInfo.NodePeople)) { string strNodePeople = ""; string ApplyTime = ""; if (nodeInfo.NodeName.ToString() == "采购员采购") { strNodePeople = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId && q.ApplyManId == ApplyManId).First().ApplyMan; ApplyTime = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId && q.ApplyManId == ApplyManId).First().ApplyTime; } else { strNodePeople = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyMan; ApplyTime = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyTime; } nodeInfo.NodePeople = strNodePeople + " " + ApplyTime; } else { string ApplyTime = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyTime; nodeInfo.NodePeople = nodeInfo.NodePeople + " " + ApplyTime; } } DataTable dtApproveView = ClassChangeHelper.ToDataTable(NodeInfoList); NodeInfoList.Clear(); string FlowName = context.Flows.Where(f => f.FlowId.ToString() == FlowId).First().FlowName.ToString(); string ProjectName = ""; string ProjectNo = ""; if (FlowId == "24") //零部件 { ProjectInfo projectInfo = context.ProjectInfo.Where(p => p.ProjectId == ProjectId).First(); ProjectName = projectInfo.ProjectName; ProjectNo = projectInfo.ProjectId; } else { Models.DingModels.Contract contract = context.Contract.Where(p => p.ContractNo == ProjectId).First(); ProjectName = contract.ContractName; ProjectNo = contract.ContractNo; } //绘制BOM表单PDF List <string> contentList = new List <string>() { "序号", "物料编码", "物料名称", "规格型号", "预计单价", "单位", "数量", "需用日期", "送货地点", "用途", "备注" }; float[] contentWithList = new float[] { 50, 60, 60, 100, 40, 40, 40, 60, 40, 40, 60 }; string Name = ""; if (FlowId == "24") //零部件采购 { Name = "项目"; } else { if (FlowId == "26") //成品采购 { Name = "合同"; } } string path = pdfHelper.GeneratePDF(FlowName, TaskId, tasks.ApplyMan, tasks.Dept, tasks.ApplyTime, Name, ProjectName, ProjectNo, "2", 300, 650, contentList, contentWithList, dtSourse, dtApproveView, null); string RelativePath = "~/UploadFile/PDF/" + Path.GetFileName(path); List <string> newPaths = new List <string>(); RelativePath = AppDomain.CurrentDomain.BaseDirectory + RelativePath.Substring(2, RelativePath.Length - 2).Replace('/', '\\'); newPaths.Add(RelativePath); string SavePath = string.Format(@"{0}\UploadFile\Ionic\{1}.zip", AppDomain.CurrentDomain.BaseDirectory, FlowName + DateTime.Now.ToString("yyyyMMddHHmmss")); //文件压缩打包 IonicHelper.CompressMulti(newPaths, SavePath, false); //上传盯盘获取MediaId SavePath = string.Format(@"~\UploadFile\Ionic\{0}", Path.GetFileName(SavePath)); DingTalkServersController dingTalkServersController = new DingTalkServersController(); var resultUploadMedia = await dingTalkServersController.UploadMedia(SavePath); //推送用户 FileSendModel fileSendModel = JsonConvert.DeserializeObject <FileSendModel>(resultUploadMedia); fileSendModel.UserId = UserId; var result = await dingTalkServersController.SendFileMessage(fileSendModel); return(new NewErrorModel() { data = result, error = new Error(0, "推送成功!", "") { }, }); } catch (Exception ex) { return(new NewErrorModel() { error = new Error(2, ex.Message, "") { }, }); } }
public async Task <object> GetPrintPDF([FromBody] PrintAndSendModel printAndSendModel) { try { string TaskId = printAndSendModel.TaskId; string UserId = printAndSendModel.UserId; PDFHelper pdfHelper = new PDFHelper(); using (DDContext context = new DDContext()) { //获取表单信息 Tasks tasks = context.Tasks.Where(t => t.TaskId.ToString() == TaskId && t.NodeId == 0).First(); string FlowId = tasks.FlowId.ToString(); //判断流程是否已结束 List <Tasks> tasksList = context.Tasks.Where(t => t.TaskId.ToString() == TaskId && t.State == 0 && t.IsSend == false).ToList(); if (tasksList.Count > 0) { return(JsonConvert.SerializeObject(new NewErrorModel { error = new Error(1, "流程尚未结束", "") { }, })); } CarTable ct = context.CarTable.Where(u => u.TaskId == TaskId).FirstOrDefault(); if (printAndSendModel.IsPublic) { ct.CarId = context.Car.Where(c => c.Id.ToString() == ct.CarId).FirstOrDefault().CarNumber; } Dictionary <string, string> keyValuePairs = new Dictionary <string, string>(); if (printAndSendModel.IsPublic) { keyValuePairs.Add("驾驶人", ct.DrivingMan); keyValuePairs.Add("车牌号", ct.CarId); keyValuePairs.Add("同行人数", ct.PeerNumber); keyValuePairs.Add("用车事由", ct.MainContent); keyValuePairs.Add("计划行车路线", ct.PlantTravelWay); keyValuePairs.Add("实际行车路线", ct.FactTravelWay); keyValuePairs.Add("出发时间", ct.StartTime.ToString()); keyValuePairs.Add("归来时间", ct.EndTime.ToString()); keyValuePairs.Add("实际行驶公里数", ct.FactKilometre); keyValuePairs.Add("总行驶公里数", ct.UseKilometres); } else { keyValuePairs.Add("驾驶人", ct.DrivingMan); keyValuePairs.Add("同行人数", ct.PeerNumber); keyValuePairs.Add("用车事由", ct.MainContent); keyValuePairs.Add("计划行车路线", ct.PlantTravelWay); keyValuePairs.Add("实际行车路线", ct.FactTravelWay); keyValuePairs.Add("出发时间", ct.StartTime.ToString()); keyValuePairs.Add("归来时间", ct.EndTime.ToString()); keyValuePairs.Add("总行驶公里数", ct.UseKilometres); } List <NodeInfo> NodeInfoList = context.NodeInfo.Where(u => u.FlowId == FlowId && u.NodeId != 0 && u.IsSend != true && u.NodeName != "结束").ToList(); foreach (NodeInfo nodeInfo in NodeInfoList) { if (string.IsNullOrEmpty(nodeInfo.NodePeople)) { string strNodePeople = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyMan; string ApplyTime = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyTime; nodeInfo.NodePeople = strNodePeople + " " + ApplyTime; } else { string ApplyTime = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyTime; nodeInfo.NodePeople = nodeInfo.NodePeople + " " + ApplyTime; } } DataTable dtApproveView = ClassChangeHelper.ToDataTable(NodeInfoList); string FlowName = context.Flows.Where(f => f.FlowId.ToString() == FlowId).First().FlowName.ToString(); string path = pdfHelper.GeneratePDF(FlowName, TaskId, tasks.ApplyMan, tasks.Dept, tasks.ApplyTime, null, null, "2", 300, 650, null, null, null, dtApproveView, keyValuePairs); string RelativePath = "~/UploadFile/PDF/" + Path.GetFileName(path); List <string> newPaths = new List <string>(); RelativePath = AppDomain.CurrentDomain.BaseDirectory + RelativePath.Substring(2, RelativePath.Length - 2).Replace('/', '\\'); newPaths.Add(RelativePath); string SavePath = string.Format(@"{0}\UploadFile\Ionic\{1}.zip", AppDomain.CurrentDomain.BaseDirectory, FlowName + DateTime.Now.ToString("yyyyMMddHHmmss")); //文件压缩打包 IonicHelper.CompressMulti(newPaths, SavePath, false); //上传盯盘获取MediaId SavePath = string.Format(@"~\UploadFile\Ionic\{0}", Path.GetFileName(SavePath)); DingTalkServersController dingTalkServersController = new DingTalkServersController(); var resultUploadMedia = await dingTalkServersController.UploadMedia(SavePath); //推送用户 FileSendModel fileSendModel = JsonConvert.DeserializeObject <FileSendModel>(resultUploadMedia); fileSendModel.UserId = UserId; var result = await dingTalkServersController.SendFileMessage(fileSendModel); return(result); } } catch (Exception ex) { throw ex; } }
public async Task <NewErrorModel> PrintAndSend([FromBody] PrintAndSendModel printAndSendModel) { try { string TaskId = printAndSendModel.TaskId; string UserId = printAndSendModel.UserId; PDFHelper pdfHelper = new PDFHelper(); using (DDContext context = new DDContext()) { //获取表单信息 Tasks tasks = context.Tasks.Where(t => t.TaskId.ToString() == TaskId && t.NodeId == 0).First(); string FlowId = tasks.FlowId.ToString(); //判断流程是否已结束 List <Tasks> tasksList = context.Tasks.Where(t => t.TaskId.ToString() == TaskId && t.State == 0 && t.IsSend == false).ToList(); if (tasksList.Count > 0) { return(new NewErrorModel() { error = new Error(1, "流程未结束!", "") { }, }); } TechnicalSupport technicalSupport = context.TechnicalSupport.Where(u => u.TaskId == TaskId).First(); string ProjectId = technicalSupport.ProjectNo; List <NodeInfo> NodeInfoList = context.NodeInfo.Where(u => u.FlowId == FlowId && u.NodeId != 0 && u.IsSend != true && u.NodeName != "结束").ToList(); foreach (NodeInfo nodeInfo in NodeInfoList) { if (string.IsNullOrEmpty(nodeInfo.NodePeople)) { string strNodePeople = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyMan; string ApplyTime = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyTime; nodeInfo.NodePeople = strNodePeople + " " + ApplyTime; } else { string ApplyTime = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyTime; nodeInfo.NodePeople = nodeInfo.NodePeople + " " + ApplyTime; } } DataTable dtApproveView = ClassChangeHelper.ToDataTable(NodeInfoList); string FlowName = context.Flows.Where(f => f.FlowId.ToString() == FlowId).First().FlowName.ToString(); ProjectInfo projectInfo = context.ProjectInfo.Where(p => p.ProjectId == ProjectId).First(); string ProjectName = projectInfo.ProjectName; string ProjectNo = projectInfo.ProjectId; Dictionary <string, string> keyValuePairs = new Dictionary <string, string>(); keyValuePairs.Add("项目负责人", technicalSupport.ResponsibleMan); keyValuePairs.Add("项目名称", technicalSupport.ProjectName); keyValuePairs.Add("项目编号", technicalSupport.ProjectNo); keyValuePairs.Add("项目组成员", technicalSupport.TeamMembers); keyValuePairs.Add("测试项目技术支持部门", technicalSupport.DeptName); keyValuePairs.Add("其他工程师", technicalSupport.OtherEngineers == "" ? "无" : technicalSupport.OtherEngineers); keyValuePairs.Add("客户名称", technicalSupport.Customer); keyValuePairs.Add("紧急程度", technicalSupport.EmergencyLevel); keyValuePairs.Add("要求完成时间", technicalSupport.TimeRequired); keyValuePairs.Add("所属公司", technicalSupport.CompanyName); keyValuePairs.Add("测试项目周期", technicalSupport.StartTime + "-" + technicalSupport.EndTime); Dictionary <string, string> keyValuePairsDb = new Dictionary <string, string>(); keyValuePairs.Add("客户项目整体概况", technicalSupport.ProjectOverview); keyValuePairs.Add("技术支持内容要点", technicalSupport.MainPoints); keyValuePairs.Add("处理方案", technicalSupport.TechnicalProposal); string path = pdfHelper.GeneratePDF(FlowName, TaskId, tasks.ApplyMan, tasks.Dept, tasks.ApplyTime, ProjectName, ProjectNo, "2", 300, 650, null, null, null, dtApproveView, keyValuePairs, keyValuePairsDb); string RelativePath = "~/UploadFile/PDF/" + Path.GetFileName(path); List <string> newPaths = new List <string>(); RelativePath = AppDomain.CurrentDomain.BaseDirectory + RelativePath.Substring(2, RelativePath.Length - 2).Replace('/', '\\'); newPaths.Add(RelativePath); string SavePath = string.Format(@"{0}\UploadFile\Ionic\{1}.zip", AppDomain.CurrentDomain.BaseDirectory, FlowName + DateTime.Now.ToString("yyyyMMddHHmmss")); //文件压缩打包 IonicHelper.CompressMulti(newPaths, SavePath, false); //上传盯盘获取MediaId SavePath = string.Format(@"~\UploadFile\Ionic\{0}", Path.GetFileName(SavePath)); DingTalkServersController dingTalkServersController = new DingTalkServersController(); var resultUploadMedia = await dingTalkServersController.UploadMedia(SavePath); //推送用户 FileSendModel fileSendModel = JsonConvert.DeserializeObject <FileSendModel>(resultUploadMedia); fileSendModel.UserId = UserId; var result = await dingTalkServersController.SendFileMessage(fileSendModel); return(new NewErrorModel() { error = new Error(0, result, "") { }, }); } } catch (Exception ex) { throw ex; } }
public async Task <string> GetReport(string TaskId, string UserId) { try { PDFHelper pdfHelper = new PDFHelper(); using (DDContext context = new DDContext()) { //获取表单信息 Tasks tasks = context.Tasks.Where(t => t.TaskId.ToString() == TaskId && t.NodeId == 0).First(); string FlowId = tasks.FlowId.ToString(); string ProjectId = tasks.ProjectId; //判断流程是否已结束 List <Tasks> tasksList = context.Tasks.Where(t => t.TaskId.ToString() == TaskId && t.IsSend != true && t.State == 0).ToList(); if (tasksList.Count > 0) { return(JsonConvert.SerializeObject( new NewErrorModel() { error = new Error(0, "流程尚未结束", "") { }, })); } List <Receiving> ReceivingList = context.Receiving.Where(u => u.TaskId == TaskId).ToList(); DataTable dtSourse = DtLinqOperators.CopyToDataTable(ReceivingList); List <NodeInfo> NodeInfoList = context.NodeInfo.Where(u => u.FlowId == FlowId && u.NodeId != 0 && u.NodeName != "结束" && !u.NodeName.Contains("抄送")).ToList(); foreach (NodeInfo nodeInfo in NodeInfoList) { if (string.IsNullOrEmpty(nodeInfo.NodePeople)) { List <Tasks> taskList = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).ToList(); foreach (var task in taskList) { nodeInfo.NodePeople += " " + task.ApplyMan + " " + task.ApplyTime; } } else { string ApplyTime = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyTime; nodeInfo.NodePeople = nodeInfo.NodePeople + " " + ApplyTime; } } DataTable dtApproveView = ClassChangeHelper.ToDataTable(NodeInfoList); string FlowName = context.Flows.Where(f => f.FlowId.ToString() == FlowId).First().FlowName.ToString(); Dictionary <string, string> dic = new Dictionary <string, string>(); Receiving receiving = context.Receiving.Where(r => r.TaskId == TaskId).SingleOrDefault(); dic.Add("申请人", tasks.ApplyMan); dic.Add("流水号", tasks.TaskId.ToString()); dic.Add("标题", tasks.Title); dic.Add("收文编号", receiving.ReceivingNo); dic.Add("来文单位", receiving.ReceivingUnit); dic.Add("文件文号", receiving.FileNo); dic.Add("收文时间", receiving.ReceivingTime); dic.Add("主要内容", receiving.MainIdea); dic.Add("拟办意见", receiving.Suggestion); dic.Add("领导阅示", receiving.Leadership); //dic.Add("承办部门阅办情况", receiving.Review.Replace("~", " ")); //dic.Add("办理落实情况", receiving.HandleImplementation.Replace("~", " ")); string path = pdfHelper.GeneratePDF(FlowName, null, tasks.ApplyMan, tasks.Dept, tasks.ApplyTime, "", "", "2", 380, 710, null, null, dtSourse, dtApproveView, dic); string RelativePath = "~/UploadFile/PDF/" + Path.GetFileName(path); List <string> newPaths = new List <string>(); RelativePath = AppDomain.CurrentDomain.BaseDirectory + RelativePath.Substring(2, RelativePath.Length - 2).Replace('/', '\\'); newPaths.Add(RelativePath); string SavePath = string.Format(@"{0}\UploadFile\Ionic\{1}.zip", AppDomain.CurrentDomain.BaseDirectory, "文件阅办单" + DateTime.Now.ToString("yyyyMMddHHmmss")); //文件压缩打包 IonicHelper.CompressMulti(newPaths, SavePath, false); //上传盯盘获取MediaId SavePath = string.Format(@"~\UploadFile\Ionic\{0}", Path.GetFileName(SavePath)); DingTalkServersController dingTalkServersController = new DingTalkServersController(); var resultUploadMedia = await dingTalkServersController.UploadMedia(SavePath); //推送用户 FileSendModel fileSendModel = JsonConvert.DeserializeObject <FileSendModel>(resultUploadMedia); fileSendModel.UserId = UserId; var result = await dingTalkServersController.SendFileMessage(fileSendModel); return(JsonConvert.SerializeObject( new NewErrorModel() { error = new Error(0, "获取成功,请在钉钉工作通知中查收!", "") { }, data = result })); } } catch (Exception ex) { throw ex; } }
static void Main(string[] args) { // Expected number of command line parms int expectedParms = 3; try { // Get command line parms and bail out if less than expected number of parms passed. // Parms should be passed with double quotes around values and single space between parms. // Example Windows command line call: pgm1.exe "parm1" "parm2" "parm3" if (args.Length < expectedParms) { throw new Exception(expectedParms + " required parms: [filelisttomergemerge] [outputpdffile] [replacepdf=true|false]"); } // Extract parms from command line string parmfilelist = args[0]; string parmoutputpdffile = args[1]; bool parmreplace = Convert.ToBoolean(args[2]); // Output any log info to console. This info will get returned in STDOUT which // also gets pipelined back to IBMi job if you use the MONO command to call this from // your IBMi system jobs. Console.WriteLine("Starting Process Now - " + System.DateTime.Now.ToString()); Console.WriteLine("--------------------------------------------------"); Console.WriteLine("Parameters:"); Console.WriteLine("--------------------------------------------------"); Console.WriteLine("Parm file list:" + parmfilelist); Console.WriteLine("Parm output PDF file:" + parmoutputpdffile); Console.WriteLine("Parm replace:" + parmreplace); // Make sure output PDF file does not exist if (File.Exists(parmoutputpdffile)) { if (parmreplace) { File.Delete(parmoutputpdffile); } else { throw new Exception(String.Format("Output PDF file {0} already exists and replace not selected. PDF merge process cancelled.", parmoutputpdffile)); } } // Instantiate PDF helper object PDFHelper _pdf = new PDFHelper(); // Burst file list on semicolon string[] arrFileList = parmfilelist.Split(';'); // Allocate ByteInfoArray for each image file ByteArrayInfo[] infoarray = new ByteArrayInfo[arrFileList.Length]; // Load each file in to memory as a ByteArrayInfo object // TODO - Alter logic to load file to memory one at a time // This could cause issues with LARGE files for (int x = 0; x < arrFileList.Length; x++) { string curfile = arrFileList[x]; infoarray[x] = new ByteArrayInfo(File.ReadAllBytes(curfile), curfile); } // Merge all selected files in to single PDF output file var rtn = _pdf.MergeIntoPDF(parmoutputpdffile, parmreplace, infoarray); // Bail if errors occurred during merge if (!rtn) { throw new Exception(String.Format("PDF merge process failed. Error: {0}", _pdf.GetLastError())); } // Successful query. Exit program with a success message and 0 error. Console.WriteLine(String.Format("Merge to PDF file {0} was successful", parmoutputpdffile)); Environment.ExitCode = 0; } catch (Exception ex) { // Write error message to console/STDOUT log and set exit code // to 99 to indicate an error to the Operating System. Console.WriteLine("Error: " + ex.Message); Environment.ExitCode = 99; } finally { // Exit the program Console.WriteLine("ExitCode: " + Environment.ExitCode); Console.WriteLine("Ending Process Now - " + System.DateTime.Now.ToString()); Environment.Exit(Environment.ExitCode); } }
public void ExportOrderRequestToPDF(Guid orderRequestId, Stream stream) { using (var context = SCMSEntities.Define()) { var orderRequest = context.OrderRequests.FirstOrDefault(r => r.Id == orderRequestId); var currency = context.Currencies.First(c => c.Id == orderRequest.CurrencyId); var mbCurrency = context.Currencies.FirstOrDefault(c => c.Id == orderRequest.MBCurrencyId); var countryProgramme = context.CountryProgrammes.First(p => p.Id == orderRequest.CountryProgrammeId); var project = context.ProjectDonors.FirstOrDefault(p => p.Id == (Guid)orderRequest.ProjectDonorId); var donor = context.ProjectDonors.First(d => d.Id == orderRequest.ProjectDonorId).Donor; var reqDesLocation = context.Locations.First(l => l.Id == orderRequest.RequestedDestinationId); var finDesLocation = context.Locations.First(l => l.Id == orderRequest.FinalDestinationId); var document = PDFHelper.NewDocument(); document.WithDocumentInfo("Order Request", "COUNTRY OFFICE, UGANDA", "DRC"); var section = document.AddSection(); section.AddLogo(); section.AddHeading("ORDER REQUEST", (heading, paragraph) => { heading.Width = "16cm"; heading.Height = "0.8cm"; paragraph.Format.Alignment = ParagraphAlignment.Center; var font = paragraph.Format.Font.Clone(); font.Size = 22.PixelsToUnitPoints(); font.Bold = true; paragraph.Format.Font = font; }); section.AddVerticalSpacing("0.5cm"); var orderRequestTable = section.AddNewTable(new[] { "Order Request Number:", "Date:", "Currency of OR:" }, new MigraDoc.DocumentObjectModel.Unit[] { 1.76.Inches(), 1.88.Inches(), 1.69.Inches() }, row => { row.Shading.Color = PDFHelper.SkyCloudyBlueColor; row.Format.Font.Bold = true; row.Format.Alignment = ParagraphAlignment.Left; }, (cell, paragraph, columnIndex) => { cell.Format.Alignment = ParagraphAlignment.Left; }); orderRequestTable.AddNewRow(new[] { orderRequest.RefNumber, orderRequest.OrderDate.Value.ToString("dd/MM/yyyy"), currency.ShortName }, row => { row.Height = 0.29.Inches(); row.Format.Font.Bold = true; }, (cell, paragraph, columnIndex) => { if (columnIndex == 0) { var font = cell.Format.Font.Clone(); cell.Format.Font = font; font.Color = PDFHelper.RedColor; } }); orderRequestTable.AddNewRow(new[] { "Program:", "Project Number:", "Donor:" }, row => { row.Shading.Color = PDFHelper.SkyCloudyBlueColor; row.Format.Font.Bold = true; row.Format.Alignment = ParagraphAlignment.Left; }, (cell, paragraph, columIndex) => { cell.Format.Alignment = ParagraphAlignment.Left; }); orderRequestTable.AddNewRow(new[] { project.Project.Name, project.ProjectNumber, donor.ShortName }, row => { row.Height = 0.29.Inches(); row.Format.Font.Bold = true; }, (cell, paragraph, columnIndex) => { if (columnIndex == 1) { var font = cell.Format.Font.Clone(); cell.Format.Font = font; } }); orderRequestTable.AddNewRow(new[] { "Requested Delivery Date:", "Requested Delivery Destination:", "Final Delivery Destination:" }, row => { row.Shading.Color = PDFHelper.SkyCloudyBlueColor; row.Format.Font.Bold = true; row.Format.Alignment = ParagraphAlignment.Left; }, (cell, paragraph, columIndex) => { cell.Format.Alignment = ParagraphAlignment.Left; }); orderRequestTable.AddNewRow(new[] { orderRequest.DeliveryDate.Value.ToString("dd/MM/yyyy"), reqDesLocation.Name, finDesLocation.Name }, row => { row.Height = 0.29.Inches(); row.Format.Font.Bold = true; }); section.AddVerticalSpacing("0.3cm"); section.AddHeading("Specification/Description, Unit, Quantities, Estimated Prices & PN/BL.", (textFrame, paragraph) => { textFrame.Width = MigraDoc.DocumentObjectModel.Unit.FromCentimeter(14.0); textFrame.Height = "0.8cm"; }); var specificationsTable = section.AddNewTable( new[] { "No.", "Description", "Unit", "Qty", "Estimated Price", "Estimated Total Price", "BL", "Remarks", }, new MigraDoc.DocumentObjectModel.Unit[] { 0.33.Inches(), 2.25.Inches(), 0.44.Inches(), 0.56.Inches(), 1.06.Inches(), 1.07.Inches(), 0.44.Inches(), 1.13.Inches() }, row => { row.Shading.Color = PDFHelper.SkyCloudyBlueColor; row.Format.Font.Bold = true; }); var orderRequestItems = (from orderRequestItem in context.OrderRequestItems join item in context.Items on orderRequestItem.ItemId equals item.Id join unitOfMeasure in context.UnitOfMeasures on orderRequestItem.Item.UnitOfMessureId equals unitOfMeasure.Id join projectBudget in context.ProjectBudgets on orderRequestItem.BudgetLineId equals projectBudget.Id join projectDonor in context.ProjectDonors on orderRequestItem.OrderRequest.ProjectDonorId equals projectDonor.Id where orderRequestItem.OrderRequestId == orderRequestId select new { item.Name, unitOfMeasure.Code, orderRequestItem.Quantity, orderRequestItem.EstimatedUnitPrice, orderRequestItem.EstimatedPrice, projectBudget.LineNumber, projectDonor.ProjectNumber, orderRequestItem.Remarks }).ToArray(); //Find number of extraRows to add var extraRows = 14 - orderRequestItems.Length; specificationsTable.AddNewRows( orderRequestItems.Select((p, i) => new object[] { i + 1, p.Name, p.Code, p.Quantity, p.EstimatedUnitPrice.FormatMoney(), p.EstimatedPrice.FormatMoney(), p.LineNumber, p.Remarks }).ToArray()); //Add extra blank rows for (int i = orderRequestItems.Length + 1; i <= 14; i++) { specificationsTable.AddNewRow(new object[] { i, "", "", "", "", "", "", "" }); } var specificationsTableTotalPrice = orderRequestItems.Sum(p => p.EstimatedPrice); specificationsTable.AddNewRow(new object[] { "Currency of Order Request", "", "", currency.ShortName, "Total", specificationsTableTotalPrice.FormatMoney(), "OR Value", "" }, null, (cell, paragraph, columnIndex) => { if (columnIndex < 1) { cell.MergeRight = 2; cell.Format.Alignment = ParagraphAlignment.Right; } if (columnIndex == 6) { cell.MergeRight = 1; cell.Format.Alignment = ParagraphAlignment.Left; } if (columnIndex < 3 || columnIndex == 4 || columnIndex > 5) { cell.Shading.Color = PDFHelper.SkyCloudyBlueColor; } }); specificationsTable.AddNewRow(new object[] { "Master Budget Currency", "", "", mbCurrency.ShortName, "Total", orderRequest.MBValue.FormatMoney(), "OR Value", "" }, null, (cell, paragraph, columnIndex) => { if (columnIndex < 1) { cell.MergeRight = 2; cell.Format.Alignment = ParagraphAlignment.Right; } if (columnIndex == 6) { cell.MergeRight = 1; cell.Format.Alignment = ParagraphAlignment.Left; } if (columnIndex < 3 || columnIndex == 4 || columnIndex > 5) { cell.Shading.Color = PDFHelper.GreenishGrayColor; } }); section.AddVerticalSpacing("0.3cm"); var authorizationTable = section.AddNewTable( new[] { "Authorization", "Authorized Requestor or Unit", "Finance Review/Approval of BL/PN", "Authorized by Manager/CD" }, new MigraDoc.DocumentObjectModel.Unit[] { 0.95.Inches(), 2.0.Inches(), 2.13.Inches(), 2.19.Inches() }, null, (cell, paragraph, columnIndex) => { if (columnIndex == 0) { var font = paragraph.Format.Font.Clone(); font.Underline = Underline.Single; paragraph.Format.Font = font; } }); //Get authorization values Person requestor = orderRequest.Staff2.Person; Person approver = orderRequest.Staff != null ? orderRequest.Staff.Person : null; Person reviewer = orderRequest.Staff3 != null ? orderRequest.Staff3.Person : null; Person authorizer = orderRequest.Staff1 != null ? orderRequest.Staff1.Person : null; string requestorName = requestor.FirstName + " " + requestor.OtherNames; string approverName = approver != null ? approver.FirstName + " " + approver.OtherNames : ""; string reviewerName = reviewer != null ? reviewer.FirstName + " " + reviewer.OtherNames : ""; string authorizerName = authorizer != null ? authorizer.FirstName + " " + authorizer.OtherNames : ""; string requestorTitle = orderRequest.Staff2 != null ? orderRequest.Staff2.Designation.Name : ""; string approverTitle = orderRequest.Staff != null ? orderRequest.Staff.Designation.Name : ""; string reviewerTitle = orderRequest.Staff3 != null ? orderRequest.Staff3.Designation.Name : ""; string authorizerTitle = orderRequest.Staff1 != null ? orderRequest.Staff1.Designation.Name : ""; string requestDate = orderRequest.PreparedOn.Value.ToString("dd/MM/yyyy h:mm tt"); string approvalDate = orderRequest.IsApproved ? orderRequest.ApprovedOn.Value.ToString("dd/MM/yyyy h:mm tt") : ""; string reviewDate = (bool)orderRequest.IsReviewed ? orderRequest.ReviewedOn.Value.ToString("dd/MM/yyyy h:mm tt") : ""; string authDate = (bool)orderRequest.IsAuthorized ? orderRequest.AuthorizedOn.Value.ToString("dd/MM/yyyy h:mm tt") : ""; authorizationTable.AddNewRow(new object[] { "Name", requestorName, reviewerName, authorizerName }); authorizationTable.AddNewRow(new object[] { "Title", requestorTitle, reviewerTitle, authorizerTitle }); authorizationTable.AddNewRow(new object[] { "Date", requestDate, reviewDate, authDate }); //authorizationTable.AddNewRow(new object[] { "Signature", "", "", "" }); authorizationTable.AddNewRow(new object[] { "Signature", "", "", "" }, null, (cell, paragraph, columnIndex) => { if (columnIndex == 1) { //cell.AddSignature(GetSignature(requestor)); cell.Add(GetSignature(requestor)); cell.VerticalAlignment = MigraDoc.DocumentObjectModel.Tables.VerticalAlignment.Center; } if (columnIndex == 2) { //cell.AddSignature(GetSignature(reviewer)); cell.Add(GetSignature(reviewer)); } if (columnIndex == 3) { //cell.AddSignature(GetSignature(authorizer)); cell.Add(GetSignature(authorizer)); } }); document.WriteAsPDFToStream(stream); } }
public async Task <string> PrintAndSend(PrintAndSendModel printAndSendModel) { try { string TaskId = printAndSendModel.TaskId; string UserId = printAndSendModel.UserId; string OldPath = printAndSendModel.OldPath; PDFHelper pdfHelper = new PDFHelper(); using (DDContext context = new DDContext()) { //获取表单信息 Tasks tasks = context.Tasks.Where(t => t.TaskId.ToString() == TaskId && t.NodeId == 0).First(); string FlowId = tasks.FlowId.ToString(); string ProjectId = tasks.ProjectId; ////判断是否有权限触发按钮 //string PeopleId = context.NodeInfo.Where(n => n.NodeName == "行政盖章" && n.FlowId == FlowId).First().PeopleId; //if (UserId != PeopleId) //{ // return JsonConvert.SerializeObject(new ErrorModel // { // errorCode = 1, // errorMessage = "没有权限" // }); //} //判断流程是否已结束 List <Tasks> tasksList = context.Tasks.Where(t => t.TaskId.ToString() == TaskId && t.IsSend != true && t.State == 0).ToList(); if (tasksList.Count > 0) { return(JsonConvert.SerializeObject(new ErrorModel { errorCode = 2, errorMessage = "流程未结束" })); } List <Purchase> PurchaseList = context.Purchase.Where(u => u.TaskId == TaskId).ToList(); var SelectPurchaseList = from p in PurchaseList select new { p.DrawingNo, p.Name, p.Count, p.MaterialScience, p.Unit, p.SingleWeight, p.AllWeight, p.Sorts, p.NeedTime, p.Mark }; DataTable dtSourse = DtLinqOperators.CopyToDataTable(SelectPurchaseList); //ClassChangeHelper.ToDataTable(SelectPurchaseList); List <NodeInfo> NodeInfoList = context.NodeInfo.Where(u => u.FlowId == FlowId && u.NodeId != 0 && u.NodeName != "结束" && u.IsSend != true).ToList(); foreach (NodeInfo nodeInfo in NodeInfoList) { if (string.IsNullOrEmpty(nodeInfo.NodePeople)) { string strNodePeople = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyMan; string ApplyTime = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyTime; nodeInfo.NodePeople = strNodePeople + " " + ApplyTime; } else { string ApplyTime = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyTime; nodeInfo.NodePeople = nodeInfo.NodePeople + " " + ApplyTime; } } DataTable dtApproveView = ClassChangeHelper.ToDataTable(NodeInfoList); string FlowName = context.Flows.Where(f => f.FlowId.ToString() == FlowId).First().FlowName.ToString(); ProjectInfo projectInfo = context.ProjectInfo.Where(p => p.ProjectId == ProjectId).First(); string ProjectName = projectInfo.ProjectName; string ProjectNo = projectInfo.ProjectId; //绘制BOM表单PDF List <string> contentList = new List <string>() { "序号", "代号", "名称", "数量", "材料", "单位", "单重", "总重", "类别", "需用日期", "备注" }; float[] contentWithList = new float[] { 50, 80, 80, 30, 60, 30, 60, 60, 60, 60, 60 }; string path = pdfHelper.GeneratePDF(FlowName, TaskId, tasks.ApplyMan, tasks.Dept, tasks.ApplyTime, ProjectName, ProjectNo, "1", 380, 710, contentList, contentWithList, dtSourse, dtApproveView, null); string RelativePath = "~/UploadFile/PDF/" + Path.GetFileName(path); string[] Paths = OldPath.Split(','); List <string> newPaths = new List <string>(); RelativePath = AppDomain.CurrentDomain.BaseDirectory + RelativePath.Substring(2, RelativePath.Length - 2).Replace('/', '\\'); newPaths.Add(RelativePath); foreach (string pathChild in Paths) { string AbPath = AppDomain.CurrentDomain.BaseDirectory + pathChild.Substring(2, pathChild.Length - 2); //PDF盖章 保存路径 newPaths.Add(pdfHelper.PDFWatermark(AbPath, string.Format(@"{0}\UploadFile\PDF\{1}", AppDomain.CurrentDomain.BaseDirectory, Path.GetFileName(pathChild)), string.Format(@"{0}\Content\images\受控章.png", AppDomain.CurrentDomain.BaseDirectory), 100, 100)); } string SavePath = string.Format(@"{0}\UploadFile\Ionic\{1}.zip", AppDomain.CurrentDomain.BaseDirectory, "图纸审核" + DateTime.Now.ToString("yyyyMMddHHmmss")); //文件压缩打包 IonicHelper.CompressMulti(newPaths, SavePath, false); //上传盯盘获取MediaId var otherController = DependencyResolver.Current.GetService <DingTalkServersController>(); SavePath = string.Format(@"~\UploadFile\Ionic\{0}", Path.GetFileName(SavePath)); var resultUploadMedia = await otherController.UploadMedia(SavePath); //推送用户 FileSendModel fileSendModel = JsonConvert.DeserializeObject <FileSendModel>(resultUploadMedia); fileSendModel.UserId = UserId; var result = await otherController.SendFileMessage(fileSendModel); return(result); } } catch (Exception ex) { return(JsonConvert.SerializeObject(new ErrorModel { errorCode = 3, errorMessage = ex.Message })); } }
public bool ConvertToPDF(DocumentSettings settings, string outputFileName) { WdExportItem wdExportItem; WdExportCreateBookmarks bookmarkOption; bool docStructureTags; bool bitmapNonEmbeddableFonts; bool flag; try { string tempPath = Path.GetTempPath(); Guid guid = Guid.NewGuid(); string str = Path.Combine(tempPath, string.Concat("aquaforest\\pdftoolkit\\", guid.ToString(), "\\", Path.GetFileName(this.filePath))); PDFHelper.CheckOutputFolder(Path.GetDirectoryName(str)); System.IO.File.Copy(this.filePath, str); string str1 = str; object missing = Type.Missing; object obj = Type.Missing; object missing1 = Type.Missing; object obj1 = this.password; object obj2 = this.password; object missing2 = Type.Missing; object obj3 = this.password; object obj4 = this.password; object missing3 = Type.Missing; object missing4 = Type.Missing; object obj5 = false; object missing5 = Type.Missing; object missing6 = Type.Missing; object obj6 = Type.Missing; object missing7 = Type.Missing; Application applicationClass = new ApplicationClass(); object obj7 = str1; object obj8 = missing; object obj9 = obj; object obj10 = missing1; object obj11 = obj1; object obj12 = obj2; object obj13 = missing2; object obj14 = obj3; object obj15 = obj4; object obj16 = missing3; object obj17 = missing4; object obj18 = obj5; object obj19 = missing5; object missing8 = missing6; object missing9 = obj6; object missing10 = missing7; Document pageOrientation = applicationClass.Documents.Open(ref obj7, ref obj8, ref obj9, ref obj10, ref obj11, ref obj12, ref obj13, ref obj14, ref obj15, ref obj16, ref obj17, ref obj18, ref obj19, ref missing8, ref missing9, ref missing10); if (settings.orientatinIset) { pageOrientation.PageSetup.Orientation = (WdOrientation)settings.PageOrientation; } if ((settings.PageHeight <= 0f ? false : settings.PageWidth > 0f)) { pageOrientation.PageSetup.PageHeight = settings.PageHeight; pageOrientation.PageSetup.PageWidth = settings.PageWidth; } else if (settings.paperSizeIset) { pageOrientation.PageSetup.PaperSize = (WdPaperSize)settings.PaperSize; } if (this.EmbedFonts > AquaforestFontEmbedding.EMBED_NONE) { pageOrientation.EmbedTrueTypeFonts = true; if (this.EmbedFonts == AquaforestFontEmbedding.EMBED_SUBSET) { pageOrientation.SaveSubsetFonts = true; } } if (settings.revisionModeIset) { pageOrientation.TrackRevisions = true; pageOrientation.ActiveWindow.View.MarkupMode = (WdRevisionsMode)settings.RevisionMode; } if (settings.MarginBottom > 0f) { pageOrientation.PageSetup.BottomMargin = settings.MarginBottom; } if (settings.MarginLeft > 0f) { pageOrientation.PageSetup.LeftMargin = settings.MarginLeft; } if (settings.MarginRight > 0f) { pageOrientation.PageSetup.RightMargin = settings.MarginRight; } if (settings.MarginTop > 0f) { pageOrientation.PageSetup.TopMargin = settings.MarginTop; } if (!settings.ConvertHyperLinks) { object obj20 = 1; while (pageOrientation.Hyperlinks.Count > 0) { pageOrientation.Hyperlinks[ref obj20].Delete();
private void SetHelper(CMWCouncilActionsPortfolio portfolio, float fontsize, float height, float width, float[] margins) { helper = new PDFHelper(portfolio, fontsize, height, width, margins); helper.PageEndReached += helper_PageEndReached; helper.PageEnd += helper_PageEnd; // page handlers writer.PageEvent = helper; // add events }
protected void btnPDF_Click(object sender, EventArgs e) { var p = new PDFHelper(); btnPDF.Enabled = false; }
protected void btnQuote_Click(object sender, EventArgs e) { try { PDFHelper _pdfhelper = new PDFHelper(); _pdfhelper.GeneratePDF(ViewState["EstNum"].ToString(),"N"); } catch (Exception) { throw; } }
public async Task <string> PrintAndSend([FromBody] PrintAndSendModel printAndSendModel) { try { string TaskId = printAndSendModel.TaskId; string UserId = printAndSendModel.UserId; PDFHelper pdfHelper = new PDFHelper(); using (DDContext context = new DDContext()) { //获取表单信息 Tasks tasks = context.Tasks.Where(t => t.TaskId.ToString() == TaskId && t.NodeId == 0).First(); string FlowId = tasks.FlowId.ToString(); string ProjectId = tasks.ProjectId; //判断是否有权限触发按钮 string PeopleId = context.Roles.Where(r => r.RoleName == "采购管理员").First().UserId; if (UserId != PeopleId) { return(JsonConvert.SerializeObject(new ErrorModel { errorCode = 1, errorMessage = "没有权限" })); } //判断流程是否已结束 List <Tasks> tasksList = context.Tasks.Where(t => t.TaskId.ToString() == TaskId && t.State == 0 && t.IsSend == false).ToList(); if (tasksList.Count > 0) { return(JsonConvert.SerializeObject(new ErrorModel { errorCode = 2, errorMessage = "流程未结束" })); } List <PurchaseTable> PurchaseTableList = context.PurchaseTable.Where(u => u.TaskId == TaskId).ToList(); var SelectPurchaseList = from p in PurchaseTableList select new { p.CodeNo, p.Name, p.Standard, p.Unit, p.Count, p.Price, p.Purpose, p.UrgentDate, p.Mark }; DataTable dtSourse = DtLinqOperators.CopyToDataTable(SelectPurchaseList); //ClassChangeHelper.ToDataTable(SelectPurchaseList); List <NodeInfo> NodeInfoList = context.NodeInfo.Where(u => u.FlowId == FlowId && u.NodeId != 0 && u.IsSend != true && u.NodeName != "结束").ToList(); foreach (NodeInfo nodeInfo in NodeInfoList) { if (string.IsNullOrEmpty(nodeInfo.NodePeople)) { string strNodePeople = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyMan; string ApplyTime = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyTime; nodeInfo.NodePeople = strNodePeople + " " + ApplyTime; } else { string ApplyTime = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyTime; nodeInfo.NodePeople = nodeInfo.NodePeople + " " + ApplyTime; } } DataTable dtApproveView = ClassChangeHelper.ToDataTable(NodeInfoList); string FlowName = context.Flows.Where(f => f.FlowId.ToString() == FlowId).First().FlowName.ToString(); string ProjectName = context.ProjectInfo.Where(p => p.ProjectId == ProjectId).First().ProjectName; //绘制BOM表单PDF List <string> contentList = new List <string>() { "序号", "物料编码", "物料名称", "规格型号", "单位", "数量", "单价", "用途", "需用日期", "备注" }; float[] contentWithList = new float[] { 50, 60, 60, 60, 60, 60, 60, 60, 60, 60 }; string path = pdfHelper.GeneratePDF(FlowName, TaskId, tasks.ApplyMan, tasks.ApplyTime, ProjectName, "2", 300, 650, contentList, contentWithList, dtSourse, dtApproveView); string RelativePath = "~/UploadFile/PDF/" + Path.GetFileName(path); List <string> newPaths = new List <string>(); RelativePath = AppDomain.CurrentDomain.BaseDirectory + RelativePath.Substring(2, RelativePath.Length - 2).Replace('/', '\\'); newPaths.Add(RelativePath); string SavePath = string.Format(@"{0}\UploadFile\Ionic\{1}.zip", AppDomain.CurrentDomain.BaseDirectory, FlowName + DateTime.Now.ToString("yyyyMMddHHmmss")); //文件压缩打包 IonicHelper.CompressMulti(newPaths, SavePath, false); //上传盯盘获取MediaId SavePath = string.Format(@"~\UploadFile\Ionic\{0}", Path.GetFileName(SavePath)); DingTalkServersController dingTalkServersController = new DingTalkServersController(); var resultUploadMedia = await dingTalkServersController.UploadMedia(SavePath); //推送用户 FileSendModel fileSendModel = JsonConvert.DeserializeObject <FileSendModel>(resultUploadMedia); fileSendModel.UserId = UserId; var result = await dingTalkServersController.SendFileMessage(fileSendModel); return(result); } } catch (Exception ex) { return(JsonConvert.SerializeObject(new ErrorModel { errorCode = 3, errorMessage = ex.Message })); } }