protected void get_page(int?pageNumber, DocFileInfo destFile) { if (!pageNumber.HasValue) { pageNumber = 1; } try { ImageFormat imageFormat = ImageFormat.Png; destFile.FileName = pageNumber.ToString(); destFile.Extension = imageFormat.ToString().ToLower(); byte[] fileBytes = !destFile.exists(paramsContainer.ApplicationID) ? File.ReadAllBytes(PublicMethods.map_path(PublicConsts.NoPDFPage)) : destFile.toByteArray(paramsContainer.ApplicationID); HttpContext.Current.Response.ContentType = "application/octet-stream"; HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename=\"{0}\"", pageNumber.ToString() + "." + imageFormat.ToString().ToLower())); HttpContext.Current.Response.AddHeader("Content-Length", fileBytes.Length.ToString()); HttpContext.Current.Response.BinaryWrite(fileBytes); HttpContext.Current.Response.End(); } catch { } }
/// 3. Taiin e yek file az DB ke mantnash estekhraj nashode ast. /// 4. Estekhraj e matn e file. /// 5. Zakhire ye matn e estekhraj shode dar DB (movaffagh ya Na movaffagh) public static void ExtractOneDocument(Guid applicationId, ref bool notExist) { //Taiin e yek file az DB ke mantnash estekhraj nashode ast. DocFileInfo file = DocumentsController.get_not_extracted_files(applicationId, "pdf,doc,docx,xlsx,ppt,pptx,txt,xml,htm,html", ',', 1).FirstOrDefault(); if (file == null || !file.FileID.HasValue) { notExist = true; return; } // vojoode file dar folder ha file.refresh_folder_name(); bool find = file.exists(applicationId); //estekhraje mant e file ba farakhani method e "ExtractFileContent" string content = string.Empty; bool NotExtractable = false; double duration = 0; string errorText = string.Empty; if (find) { DateTime dtBegin = DateTime.Now; content = FileContentExtractor.ExtractFileContent(applicationId, file, ref errorText); duration = DateTime.Now.Subtract(dtBegin).TotalMilliseconds; } if (!find) { find = false; } else if (string.IsNullOrEmpty(content)) { NotExtractable = true; } // Zakhire ye matn e estekhraj shode dar DB dar halate movaffagh boodan. DocumentsController.save_file_content(applicationId, file.FileID.Value, content, NotExtractable, !find, duration, errorText); }
protected void handle_imported_file(DocFileInfo file, ref string responseText) { //Privacy Check: OK if (!paramsContainer.GBEdit) { return; } if (!AuthorizationManager.has_right(AccessRoleName.DataImport, paramsContainer.CurrentUserID)) { responseText = "{\"ErrorText\":\"" + Messages.AccessDenied + "\"}"; return; } if (!file.exists(paramsContainer.Tenant.Id)) { responseText = "{\"ErrorText\":\"" + Messages.OperationFailed + "\"}"; return; } XmlDocument xmlDoc = new XmlDocument(); try { using (MemoryStream stream = new MemoryStream(file.toByteArray(paramsContainer.Tenant.Id))) xmlDoc.Load(stream); } catch (Exception ex) { responseText = "{\"ErrorText\":\"" + Messages.OperationFailed + "\"}"; return; } string docName = xmlDoc.DocumentElement.Name.ToLower(); bool result = false; switch (docName) { case "nodes": result = update_nodes(ref xmlDoc); break; case "nodeids": result = update_node_ids(ref xmlDoc); break; case "removenodes": result = remove_nodes(ref xmlDoc); break; case "users": result = update_users(ref xmlDoc); break; case "members": result = update_members(ref xmlDoc); break; case "experts": result = update_experts(ref xmlDoc); break; case "relations": result = update_relations(ref xmlDoc); break; case "authors": result = update_authors(ref xmlDoc); break; case "userconfidentialities": result = update_user_confidentialities(ref xmlDoc); break; case "permissions": result = update_permissions(ref xmlDoc); break; } responseText = result ? "{\"Succeed\":\"" + Messages.OperationCompletedSuccessfully + "\"}" : "{\"ErrorText\":\"" + Messages.OperationFailed + "\"}"; }
public void ProcessRequest(HttpContext context) { //Privacy Check: OK paramsContainer = new ParamsContainer(context, nullTenantResponse: true); if (!paramsContainer.ApplicationID.HasValue) { return; } string responseText = string.Empty; string command = PublicMethods.parse_string(context.Request.Params["Command"], false); if (string.IsNullOrEmpty(command)) { return; } Guid currentUserId = paramsContainer.CurrentUserID.HasValue ? paramsContainer.CurrentUserID.Value : Guid.Empty; Guid fileId = string.IsNullOrEmpty(context.Request.Params["FileID"]) ? Guid.Empty : Guid.Parse(context.Request.Params["FileID"]); DocFileInfo file = DocumentsController.get_file(paramsContainer.Tenant.Id, fileId); if (file == null) { paramsContainer.return_response(PublicConsts.BadRequestResponse); return; } bool isTemporary = PublicMethods.parse_string(HttpContext.Current.Request.Params["Category"], false).ToLower() == "temporary"; bool hasAccess = isTemporary || PublicMethods.is_system_admin(paramsContainer.Tenant.Id, currentUserId); PrivacyObjectType pot = file.OwnerType == FileOwnerTypes.Node ? PrivacyObjectType.Node : PrivacyObjectType.None; hasAccess = hasAccess || PrivacyController.check_access(paramsContainer.Tenant.Id, paramsContainer.CurrentUserID, file.OwnerID.Value, pot, PermissionType.View); if (!hasAccess && currentUserId != Guid.Empty && CNController.is_node(paramsContainer.Tenant.Id, file.OwnerID.Value)) { bool isCreator = false, isContributor = false, isExpert = false, isMember = false, isAdminMember = false, isServiceAdmin = false, isAreaAdmin = false, perCreatorLevel = false; CNController.get_user2node_status(paramsContainer.Tenant.Id, paramsContainer.CurrentUserID.Value, file.OwnerID.Value, ref isCreator, ref isContributor, ref isExpert, ref isMember, ref isAdminMember, ref isServiceAdmin, ref isAreaAdmin, ref perCreatorLevel); hasAccess = isServiceAdmin || isAreaAdmin || isCreator || isContributor || isExpert || isMember; } if (!hasAccess) { paramsContainer.return_response("{\"ErrorText\":\"" + Messages.AccessDenied.ToString() + "\"}"); } if (isTemporary) { file.FolderName = FolderNames.TemporaryFiles; } else { file.refresh_folder_name(); } if (!file.exists(paramsContainer.Tenant.Id)) { _return_response(ref responseText); } DocFileInfo destFile = new DocFileInfo() { FileID = file.FileID, FolderName = FolderNames.PDFImages }; switch (command) { case "Convert2Image": convert2image(file, PublicMethods.parse_string(context.Request.Params["PS"]), destFile, PublicMethods.parse_bool(context.Request.Params["Repair"]), ref responseText); _return_response(ref responseText); return; case "GetPagesCount": get_pages_count(file, PublicMethods.parse_string(context.Request.Params["PS"]), destFile, ref responseText); _return_response(ref responseText); return; case "GetPage": get_page(PublicMethods.parse_int(context.Request.Params["Page"], 1), destFile); return; } paramsContainer.return_response(PublicConsts.BadRequestResponse); }
public override IList <IElement> End(IWorkerContext ctx, Tag tag, IList <IElement> currentContent) { IDictionary <string, string> attributes = tag.Attributes; string src; if (!attributes.TryGetValue(itsXmlHtml.HTML.Attribute.SRC, out src)) { return(new List <IElement>(1)); } if (string.IsNullOrEmpty(src)) { return(new List <IElement>(1)); } //convert url to base64 image if (!src.StartsWith("data:image/", StringComparison.InvariantCultureIgnoreCase)) { int index = src.ToLower().IndexOf("fileid="); if (index >= 0) { string newSrc = src.Substring(index + "fileid=".Length); if (newSrc.IndexOf("&") > 0) { newSrc = newSrc.Substring(0, newSrc.IndexOf("&")); } Guid? fileId = PublicMethods.parse_guid(newSrc); DocFileInfo fi = DocumentsController.get_file(ApplicationID, fileId.Value); if (fi != null) { fi.refresh_folder_name(); } if (!fi.exists(ApplicationID)) { try { System.Drawing.Image img = null; using (MemoryStream stream = new MemoryStream(fi.toByteArray(ApplicationID))) img = System.Drawing.Bitmap.FromStream(stream); string strWidth = tag == null || tag.CSS == null || !tag.CSS.ContainsKey("width") ? string.Empty : tag.CSS["width"]; string strHeight = tag == null || tag.CSS == null || !tag.CSS.ContainsKey("height") ? string.Empty : tag.CSS["height"]; if (!string.IsNullOrEmpty(strWidth)) { strWidth = strWidth.ToLower().Replace("px", ""); } if (!string.IsNullOrEmpty(strHeight)) { strHeight = strHeight.ToLower().Replace("px", ""); } int width = 0, height = 0, maxWidth = 650, maxHeight = 900; if (string.IsNullOrEmpty(strWidth) || !int.TryParse(strWidth, out width) || width < 0) { width = img.Width; } if (string.IsNullOrEmpty(strHeight) || !int.TryParse(strHeight, out height) || height < 0) { height = img.Height; } double coeff = Math.Min(width <= maxWidth ? 1 : (double)maxWidth / (double)width, height <= maxHeight ? 1 : (double)maxHeight / (double)height); width = (int)Math.Floor(coeff * (double)width); height = (int)Math.Floor(coeff * (double)height); if (width != img.Width || height != img.Height) { string msg = string.Empty; if (RVGraphics.make_thumbnail(img, width, height, 0, 0, ref img, ref msg)) { tag.CSS["width"] = (width = img.Width).ToString() + "px"; tag.CSS["height"] = (height = img.Height).ToString() + "px"; } } newSrc = PublicMethods.image_to_base64(img, System.Drawing.Imaging.ImageFormat.Png); if (!string.IsNullOrEmpty(newSrc)) { src = "data:image/png;base64," + newSrc; } } catch { } } } } //end of convert url to base64 image if (src.StartsWith("data:image/", StringComparison.InvariantCultureIgnoreCase)) { // data:[<MIME-type>][;charset=<encoding>][;base64],<data> var base64Data = src.Substring(src.IndexOf(",") + 1); var imagedata = Convert.FromBase64String(base64Data); var image = iTextSharp.text.Image.GetInstance(imagedata); image.ScaleToFitLineWhenOverflow = true; image.ScaleToFitHeight = false; var list = new List <IElement>(); var htmlPipelineContext = GetHtmlPipelineContext(ctx); IElement imgElement = GetCssAppliers().Apply(new Chunk((iTextSharp.text.Image)GetCssAppliers() .Apply(image, tag, htmlPipelineContext), 0, 0, true), tag, htmlPipelineContext); list.Add(imgElement); return(list); } else { return(base.End(ctx, tag, currentContent)); } }
public static bool import_form(Guid applicationId, Guid?instanceId, DocFileInfo uploadedFile, Dictionary <string, object> map, Guid currentUserId, ref List <FormElement> savedElements, List <FormElement> nodeElements, ref string errorMessage) { if (!instanceId.HasValue || uploadedFile == null || !uploadedFile.FileID.HasValue) { return(false); } if (!uploadedFile.exists(applicationId)) { return(false); } if (map.ContainsKey("sub")) { map = (Dictionary <string, object>)map["sub"]; } FormType formInstance = FGController.get_form_instance(applicationId, instanceId.Value); if (formInstance == null || !formInstance.InstanceID.HasValue || !formInstance.FormID.HasValue) { return(false); } List <FormElement> formElements = FGController.get_form_instance_elements(applicationId, instanceId.Value).OrderBy(u => u.SequenceNumber).ToList(); if (formElements == null || formElements.Count == 0) { return(false); } XmlDocument doc = new XmlDocument(); try { using (MemoryStream stream = new MemoryStream(uploadedFile.toByteArray(applicationId))) doc.Load(stream); } catch (Exception ex) { LogController.save_error_log(applicationId, currentUserId, "FG_ImportForm_LoadFile", ex, ModuleIdentifier.FG); errorMessage = Messages.OperationFailed.ToString(); return(false); } XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); if (!string.IsNullOrEmpty(doc.DocumentElement.GetNamespaceOfPrefix(""))) { nsmgr.AddNamespace(DEFAULTPREFIX, doc.DocumentElement.GetNamespaceOfPrefix("")); nsmgr.AddNamespace("", doc.DocumentElement.GetNamespaceOfPrefix("")); } foreach (XmlAttribute attr in doc.SelectSingleNode("/*").Attributes) { if (attr.Prefix == "xmlns") { nsmgr.AddNamespace(attr.LocalName, attr.Value); } } List <FormElement> theElements = new List <FormElement>(); //add node elements if (nodeElements == null) { nodeElements = new List <FormElement>(); } foreach (FormElement e in nodeElements) { e.Type = FormElementTypes.Text; formElements.Add(e); } //end of add node elements foreach (string name in map.Keys) { List <FormElement> newElems = _parse_imported_form(applicationId, doc.DocumentElement, get_child_nodes(doc.DocumentElement, name, nsmgr), nsmgr, map[name], formElements, map); if (newElems != null && newElems.Count > 0) { theElements.AddRange(newElems); } } //remove node elements foreach (FormElement e in nodeElements) { FormElement elem = theElements.Where( u => (u.ElementID == e.ElementID || u.RefElementID == e.ElementID) && u.Name == e.Name).FirstOrDefault(); if (elem != null) { e.TextValue = elem.TextValue; theElements.Remove(elem); } } //end of remove node elements List <FormType> newFormInstances = new List <FormType>(); List <FormElement> newElements = new List <FormElement>(); List <DocFileInfo> newFiles = new List <DocFileInfo>(); get_save_items(formInstance, theElements, ref newFormInstances, ref newElements, ref newFiles); //set_national_ids(ref newElements); set_identity_values(ref newElements); //remove empty text elements newElements = newElements .Where(u => u.Type != FormElementTypes.Text || !string.IsNullOrEmpty(u.TextValue)).ToList(); //end of remove empty text elements if (newFiles != null) { newFiles.ForEach(f => f.move(applicationId, FolderNames.TemporaryFiles, FolderNames.Attachments)); } bool result = newFormInstances == null || newFormInstances.Count == 0 || FGController.create_form_instances(applicationId, newFormInstances, currentUserId); result = result && FGController.save_form_instance_elements(applicationId, ref newElements, new List <Guid>(), currentUserId, ref errorMessage); if (!result && newFiles != null) { newFiles.ForEach(f => f.move(applicationId, FolderNames.Attachments, FolderNames.TemporaryFiles)); } if (result) { savedElements = theElements; } return(result); }
public static void pdf2image(Guid applicationId, DocFileInfo pdf, string password, DocFileInfo destFile, ImageFormat imageFormat, bool repair) { //MagickNET.SetGhostscriptDirectory("[GhostScript DLL Dir]"); //MagickNET.SetTempDirectory("[a temp dir]"); if (!pdf.FileID.HasValue) { return; } else if (PDF2ImageProcessing.ContainsKey(pdf.FileID.Value) && (!repair || PDF2ImageProcessing[pdf.FileID.Value])) { return; } else { PDF2ImageProcessing[pdf.FileID.Value] = true; } if (destFile.file_exists_in_folder(applicationId) && !repair) { PDF2ImageProcessing[pdf.FileID.Value] = false; return; } try { string cacheDir = PublicMethods.map_path(PublicConsts.MagickCacheDirectory, localPath: true); if (!Directory.Exists(cacheDir)) { Directory.CreateDirectory(cacheDir); } MagickAnyCPU.CacheDirectory = cacheDir; } catch (Exception ex) { LogController.save_error_log(applicationId, null, "SetMagickCacheDirectory", ex, ModuleIdentifier.DCT); } try { string tempDir = PublicMethods.map_path(PublicConsts.TempDirectory, localPath: true); if (!Directory.Exists(tempDir)) { Directory.CreateDirectory(tempDir); } MagickNET.SetTempDirectory(tempDir); if (!string.IsNullOrEmpty(RaaiVanSettings.GhostScriptDirectory)) { MagickNET.SetGhostscriptDirectory(RaaiVanSettings.GhostScriptDirectory); } } catch (Exception ex) { LogController.save_error_log(applicationId, null, "SetMagickTempDirectory", ex, ModuleIdentifier.DCT); } try { using (MagickImageCollection pages = new MagickImageCollection()) { MagickReadSettings settings = new MagickReadSettings() { Density = new Density(100, 100) }; bool invalidPassword = false; using (PdfReader reader = PDFUtil.open_pdf_file(applicationId, pdf, password, ref invalidPassword)) { byte[] pdfContent = PDFUtil.to_byte_array(reader); pages.Read(pdfContent, settings); } int pageNum = 0; bool errorLoged = false; foreach (MagickImage p in pages) { ++pageNum; destFile.FileName = pageNum.ToString(); destFile.Extension = imageFormat.ToString().ToLower(); if (destFile.exists(applicationId)) { continue; } try { using (MemoryStream stream = new MemoryStream()) { p.ToBitmap(imageFormat).Save(stream, imageFormat); destFile.store(applicationId, stream.ToArray()); } } catch (Exception ex) { if (!errorLoged) { errorLoged = true; LogController.save_error_log(applicationId, null, "ConvertPDFPageToImage", ex, ModuleIdentifier.DCT); } } } } } catch (Exception ex) { LogController.save_error_log(applicationId, null, "ConvertPDFToImage", ex, ModuleIdentifier.DCT); } PDF2ImageProcessing[pdf.FileID.Value] = false; }