public PageEventHelper(Guid applicationId, string documentTitle, Font font, DownloadedFileMeta meta) { this.ApplicationID = applicationId; this.DocumentTitle = documentTitle; this.font = new Font(font.BaseFont, 10, Font.NORMAL, BaseColor.GRAY); this.Meta = meta; }
protected void send_file(DocFileInfo file, bool logNeeded, bool addPDFCover = false, bool addPDFFooter = false, Guid?coverId = null, string pdfPassword = null, string contentType = null, bool isAttachment = true) { byte[] fileContent = file.toByteArray(paramsContainer.ApplicationID); if (fileContent.Length == 0) { send_empty_response(); return; } //Save Log if (logNeeded && paramsContainer.CurrentUserID.HasValue) { LogController.save_log(paramsContainer.Tenant.Id, new Log() { UserID = paramsContainer.CurrentUserID, Date = DateTime.Now, HostAddress = PublicMethods.get_client_ip(HttpContext.Current), HostName = PublicMethods.get_client_host_name(HttpContext.Current), Action = Modules.Log.Action.Download, SubjectID = file.FileID, Info = file.toJson(paramsContainer.Tenant.Id), ModuleIdentifier = ModuleIdentifier.DCT }); } //end of Save Log if (file.Extension.ToLower() == "pdf") { addPDFCover = addPDFCover && file.OwnerNodeID.HasValue && coverId.HasValue && paramsContainer.ApplicationID.HasValue && paramsContainer.CurrentUserID.HasValue; if (addPDFFooter || addPDFCover) { bool invalidPassword = false; fileContent = PDFUtil.get_pdf_content(paramsContainer.Tenant.Id, fileContent, pdfPassword, ref invalidPassword); if (invalidPassword) { string responseText = "{\"InvalidPassword\":" + true.ToString().ToLower() + "}"; paramsContainer.return_response(ref responseText); return; } } if (addPDFFooter) { User currentUser = !paramsContainer.CurrentUserID.HasValue ? null : UsersController.get_user(paramsContainer.Tenant.Id, paramsContainer.CurrentUserID.Value); if (currentUser == null) { currentUser = new User() { UserID = Guid.NewGuid(), UserName = "******", FirstName = "[anonymous]", LastName = "[anonymous]" }; } DownloadedFileMeta meta = new DownloadedFileMeta(PublicMethods.get_client_ip(HttpContext.Current), currentUser.UserName, currentUser.FirstName, currentUser.LastName, null); fileContent = PDFTemplates.append_footer(fileContent, meta.toString()); } if (addPDFCover) { fileContent = Wiki2PDF.add_custom_cover(paramsContainer.Tenant.Id, paramsContainer.CurrentUserID.Value, fileContent, coverId.Value, file.OwnerNodeID.Value); } if (!string.IsNullOrEmpty(pdfPassword)) { fileContent = PDFUtil.set_password(fileContent, pdfPassword); } } string retFileName = file.FileName + (string.IsNullOrEmpty(file.Extension) ? string.Empty : "." + file.Extension); paramsContainer.file_response(fileContent, retFileName, contentType: contentType, isAttachment: isAttachment); }
public static byte[] export_as_pdf(Guid applicationId, Guid?currentUserId, bool isUser, DownloadedFileMeta meta, string title, string description, List <string> keywords, List <KeyValuePair <Guid, string> > wikiTitles, Dictionary <Guid, List <KeyValuePair <string, string> > > wikiParagraphs, Dictionary <string, string> metaData, List <string> authors, Guid?coverId, Guid?coverOwnerNodeId, string password, HttpContext context) { bool hasCustomCover = coverId.HasValue && coverOwnerNodeId.HasValue && currentUserId.HasValue; List <WikiPDFText> wikiCover = hasCustomCover ? new List <WikiPDFText>() : get_default_cover(applicationId, isUser, title, metaData, authors); string strKeywords = string.Join(" - ", keywords); WikiPDFText wikiTitle = new WikiPDFText(applicationId, @"<br><br><p style='text-align:center;'><strong><span style='color:DarkSlateGray;'>" + title + "</span></strong></p><br><br>"); List <WikiPDFText> wikiDesc = convert_div_to_p(applicationId, new List <WikiPDFText>() { new WikiPDFText(applicationId, string.IsNullOrEmpty(description) ? "" : @"<br><p class='NodeAbs'>" + description + "</p><br>") }); WikiPDFText wikiKeywords = new WikiPDFText(applicationId, string.IsNullOrEmpty(strKeywords) ? "" : @"<br><p> " + strKeywords + " </p><br>"); string pdfTitles = string.Empty; WikiPDFText wikiPDFTitles = null; List <WikiPDFText> strHTMLParagraphs = new List <WikiPDFText>(); foreach (KeyValuePair <Guid, string> t in wikiTitles) { if (!wikiParagraphs.ContainsKey(t.Key) || wikiParagraphs[t.Key].Count == 0) { continue; } bool hasTitle = !string.IsNullOrEmpty(t.Value); int counter = 0; if (hasTitle) { pdfTitles += "<p><a href='#" + t.Key.ToString() + "'>" + t.Value + "</a></p><br>"; pdfTitles += ProviderUtil.list_to_string <string>(wikiParagraphs[t.Key].Where( u => !string.IsNullOrEmpty(u.Key) && !string.IsNullOrEmpty(u.Value)).Select( p => "<p><a style='color:gray;' href='#" + t.Key.ToString() + (++counter).ToString() + "'>" + p.Key + "</a></p><br>").ToList <string>(), ' '); } wikiPDFTitles = new WikiPDFText(applicationId, pdfTitles); counter = 0; WikiPDFText mt = !hasTitle ? null : new WikiPDFText(applicationId, @"<br><a name='" + t.Key.ToString() + "'><strong style='color:#00a;'>" + t.Value + "</strong></a>"); List <KeyValuePair <string, string> > prgrs = wikiParagraphs[t.Key].Where( u => !string.IsNullOrEmpty(u.Value)).Select(x => x).ToList(); WikiPDFText tempParagraphs = new WikiPDFText(applicationId, ProviderUtil.list_to_string <string>(prgrs.Select(u => u.Value).ToList(), ' ')); if (mt != null && tempParagraphs.IsProbablyRTL) { mt.set_is_rtl(true); } if (mt != null) { strHTMLParagraphs.Add(mt); } foreach (KeyValuePair <string, string> kvp in prgrs) { WikiPDFText pp = new WikiPDFText(applicationId, kvp.Value); if (!string.IsNullOrEmpty(kvp.Key)) { WikiPDFText pt = new WikiPDFText(applicationId, "<p><a style='color:#444;' name='" + t.Key.ToString() + (++counter).ToString() + "'><strong>" + kvp.Key + "</strong></a></p>"); if (pp.IsProbablyRTL) { pt.set_is_rtl(true); } strHTMLParagraphs.Add(pt); } strHTMLParagraphs.Add(pp); } } strHTMLParagraphs = convert_div_to_p(applicationId, strHTMLParagraphs); using (MemoryStream mem = new MemoryStream()) { using (Document pdfDoc = new Document(PageSize.A4)) { BaseFont baseFont = BaseFont.CreateFont( PublicMethods.map_path("~/Fonts/windows/IRANSans.ttf"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); Font font = new Font(baseFont, size: 9); PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, mem); PageEventHelper pageEvents = new PageEventHelper(applicationId, title, font, meta); pdfWriter.PageEvent = pageEvents; pdfWriter.RgbTransparencyBlending = true; pdfDoc.Open(); StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(); cssResolver.AddCssFile(PublicMethods.map_path("~/CSS/pdf.css"), true); PdfPTable mainTable = new PdfPTable(1) { WidthPercentage = 100, RunDirection = PdfWriter.RUN_DIRECTION_RTL }; mainTable.SplitLate = false; PdfPCell coverCell = new PdfPCell() { FixedHeight = 750, RunDirection = PdfWriter.RUN_DIRECTION_RTL, HorizontalAlignment = Element.ALIGN_CENTER }; PdfPCell titlesCell = new PdfPCell { Border = 0, RunDirection = PdfWriter.RUN_DIRECTION_RTL, HorizontalAlignment = Element.ALIGN_RIGHT, PaddingRight = 20f, PaddingLeft = 20f, BackgroundColor = BaseColor.LIGHT_GRAY }; for (int c = 0; c < wikiCover.Count; c++) { _add_to_table(applicationId, context, mainTable, cssResolver, wikiCover[c], font, coverCell); } //_add_to_table(applicationId, context, mainTable, cssResolver, wikiTitle, font); if (!string.IsNullOrEmpty(description)) { for (int c = 0; c < wikiDesc.Count; c++) { _add_to_table(applicationId, context, mainTable, cssResolver, wikiDesc[c], font); } } if (!string.IsNullOrEmpty(strKeywords)) { _add_to_table(applicationId, context, mainTable, cssResolver, wikiKeywords, font); } //_add_to_table(applicationId, context, mainTable, cssResolver, wikiPDFTitles, font, titlesCell); for (int c = 0; c < strHTMLParagraphs.Count; c++) { _add_to_table(applicationId, context, mainTable, cssResolver, strHTMLParagraphs[c], font); } pdfDoc.Add(mainTable); pdfDoc.Close(); byte[] finalContent = mem.ToArray(); if (hasCustomCover) { finalContent = add_custom_cover(applicationId, currentUserId.Value, finalContent, coverId.Value, coverOwnerNodeId.Value); } return(string.IsNullOrEmpty(password) ? finalContent : PDFUtil.set_password(finalContent, password)); } } }
protected void get_report(ModuleIdentifier moduleIdentifier, string reportName, bool excel, bool rtl, bool isPersian, ref Dictionary <string, string> dic, int pageNumber, int pageSize, ref string responseText, List <ReportParameter> parameters, string password) { //Privacy Check: OK if (!paramsContainer.GBEdit) { return; } bool isSystemAdmin = PublicMethods.is_system_admin(paramsContainer.Tenant.Id, paramsContainer.CurrentUserID.Value); Guid?reportId = ReportUtilities.get_report_id(moduleIdentifier, reportName); bool hasAccess = reportId.HasValue && (isSystemAdmin || AuthorizationManager.has_right(AccessRoleName.Reports, paramsContainer.CurrentUserID)); hasAccess = hasAccess && (isSystemAdmin || PrivacyController.check_access(paramsContainer.Tenant.Id, paramsContainer.CurrentUserID, reportId.Value, PrivacyObjectType.Report, PermissionType.View)); if (!hasAccess) { responseText = "{\"ErrorText\":\"" + Messages.AccessDenied + "\"}"; return; } DataTable tbl = new DataTable(); string actions = string.Empty; Dictionary <string, string> columnsDic = new Dictionary <string, string>(); ReportsController.get_report(paramsContainer.Tenant.Id, moduleIdentifier, reportName, ref tbl, ref actions, ref columnsDic, parameters); int firstRow = excel ? 0 : (pageSize * (pageNumber - 1)); int lastRow = (excel ? tbl.Rows.Count : Math.Min(firstRow + pageSize, tbl.Rows.Count)) - 1; for (int c = 0; c < tbl.Columns.Count; ++c) { if (tbl.Columns[c].DataType != typeof(string) || tbl.Columns[c].ColumnName.IndexOf("_HTML") < 0) { continue; } tbl.Columns[c].ColumnName = tbl.Columns[c].ColumnName.Replace("_HTML", string.Empty); for (int r = firstRow; r <= lastRow; ++r) { if (tbl.Rows[r][c] != DBNull.Value && !string.IsNullOrEmpty((string)tbl.Rows[r][c])) { //tbl.Rows[r][c] = PublicMethods.markup2plaintext( //Expressions.replace((string)tbl.Rows[r][c], Expressions.Patterns.HTMLTag, " ")).Trim(); string str = (string)tbl.Rows[r][c]; str = Expressions.replace(str, Expressions.Patterns.HTMLTag, " "); str = PublicMethods.markup2plaintext(paramsContainer.Tenant.Id, str).Trim(); tbl.Rows[r][c] = str; } } } if (excel) { try { Dictionary <string, bool> usedColNames = new Dictionary <string, bool>(); foreach (string n in dic.Values) { usedColNames[n] = true; } for (int c = 0; c < tbl.Columns.Count; ++c) { if (columnsDic.ContainsKey(tbl.Columns[c].ColumnName)) { string colName = columnsDic[tbl.Columns[c].ColumnName]; int num = 1; while (true) { string tmpName = colName + (num <= 1 ? string.Empty : " (" + num.ToString() + ")"); if (!usedColNames.ContainsKey(tmpName)) { usedColNames[tmpName] = true; colName = tmpName; break; } else { ++num; } } tbl.Columns[c].ColumnName = colName; } bool isString = tbl.Columns[c].DataType == typeof(string); bool isDic = tbl.Columns[c].ColumnName.IndexOf("_Dic") >= 0; if (isString && isDic) { Dictionary <string, string> colDic = _get_dictionary(tbl.Columns[c].ColumnName); for (int r = 0; r < tbl.Rows.Count; ++r) { bool isNull = tbl.Rows[r].ItemArray[c] == DBNull.Value || tbl.Rows[r].ItemArray[c] == null; if (!isNull && colDic.ContainsKey((string)tbl.Rows[r].ItemArray[c])) { tbl.Rows[r][c] = colDic[(string)tbl.Rows[r].ItemArray[c]]; } } } if (isDic) { tbl.Columns[c].ColumnName = tbl.Columns[c].ColumnName.Replace("_Dic", string.Empty); } } //meta data for exported file Privacy p = !reportId.HasValue ? null : PrivacyController.get_settings(paramsContainer.Tenant.Id, reportId.Value); string confidentiality = p == null ? null : p.Confidentiality.Title; User currentUser = !paramsContainer.CurrentUserID.HasValue ? null : UsersController.get_user(paramsContainer.Tenant.Id, paramsContainer.CurrentUserID.Value); if (currentUser == null) { currentUser = new User(); } DownloadedFileMeta meta = new DownloadedFileMeta(PublicMethods.get_client_ip(HttpContext.Current), currentUser.UserName, currentUser.FirstName, currentUser.LastName, confidentiality); //end of meta data for exported file string reportFileName = "Reports_" + PublicMethods.get_random_number().ToString(); ExcelUtilities.ExportToExcel(reportFileName, tbl, rtl, dic, password, meta); } catch (Exception ex) { responseText = "{\"ErrorText\":\"" + Messages.OperationFailed + "\"}"; LogController.save_error_log(paramsContainer.Tenant.Id, paramsContainer.CurrentUserID, "ExportReportToExcel", ex, ModuleIdentifier.RPT, LogLevel.Fatal); } return; } Dictionary <string, bool> isFloatDic = new Dictionary <string, bool>(); responseText = "{\"Columns\":["; for (int i = 0, lnt = tbl.Columns.Count; i < lnt; ++i) { object obj = null; for (int j = firstRow; j <= lastRow; ++j) { if (tbl.Rows[j][i] != DBNull.Value && tbl.Rows[j][i] != null && !string.IsNullOrEmpty(tbl.Rows[j][i].ToString())) { obj = tbl.Rows[j][i]; break; } } bool isNumber = false; bool isFloat = false; if (obj != null) { var objType = obj.GetType(); isNumber = objType == typeof(int) || objType == typeof(long) || objType == typeof(float) || objType == typeof(double) || objType == typeof(decimal); isFloat = objType == typeof(float) || objType == typeof(double) || objType == typeof(decimal); } isFloatDic.Add(tbl.Columns[i].ColumnName, isFloat); string colTitle = columnsDic.ContainsKey(tbl.Columns[i].ColumnName) ? columnsDic[tbl.Columns[i].ColumnName] : tbl.Columns[i].ColumnName; responseText += (i == 0 ? string.Empty : ",") + "{\"ID\":\"" + tbl.Columns[i].ColumnName + "\",\"Title\":\"" + Base64.encode(colTitle) + "\",\"Encoded\":true" + ",\"IsNumber\":" + isNumber.ToString().ToLower() + "}"; } responseText += "],\"Total\":" + tbl.Rows.Count.ToString() + ",\"Rows\":["; for (int i = firstRow; i <= lastRow; ++i) { responseText += (i == firstRow ? string.Empty : ",") + "{"; for (int j = 0, _ln = tbl.Columns.Count; j < _ln; ++j) { if (isFloatDic[tbl.Columns[j].ColumnName]) { tbl.Rows[i].ItemArray[j] = Math.Round(double.Parse((tbl.Rows[i].ItemArray[j] == DBNull.Value ? 0 : tbl.Rows[i].ItemArray[j]).ToString()), 2); } string strVal = tbl.Rows[i].ItemArray[j].GetType() == typeof(DateTime) ? PublicMethods.get_local_date((DateTime)tbl.Rows[i].ItemArray[j], true) : (isFloatDic[tbl.Columns[j].ColumnName] ? Math.Round(double.Parse((tbl.Rows[i].ItemArray[j] == DBNull.Value ? 0 : tbl.Rows[i].ItemArray[j]).ToString()), 2) : tbl.Rows[i].ItemArray[j]).ToString(); responseText += (j == 0 ? string.Empty : ",") + "\"" + tbl.Columns[j].ColumnName + "\":\"" + Base64.encode(strVal) + "\""; } responseText += "}"; } responseText += "],\"Actions\":" + (string.IsNullOrEmpty(actions) ? "{}" : actions) + "}"; }