private void _btnLoadAnnotations_Click(object sender, EventArgs e) { using (OpenFileDialog openFileDialog = new OpenFileDialog()) { openFileDialog.Filter = "Annotations File (.xml)|*.xml"; if (openFileDialog.ShowDialog(this) == DialogResult.OK) { AnnContainer tmpContainer = null; try { AnnCodecs codecs = new AnnCodecs(); tmpContainer = codecs.Load(openFileDialog.FileName, 1); AnnContainer activeContainer = _automation.Container; if (activeContainer != null) { activeContainer.Children.Clear(); if (tmpContainer != null) { foreach (AnnObject annObject in tmpContainer.Children) { activeContainer.Children.Add(annObject); } } } _automation.Invalidate(LeadRectD.Empty); } catch { Messager.ShowError(this, "Invalid Annotation File"); } } } }
private void _btnSaveAnnotations_Click(object sender, EventArgs e) { using (SaveFileDialog saveFileDialog = new SaveFileDialog()) { saveFileDialog.Filter = "Annotations File (.xml)|*.xml"; if (saveFileDialog.ShowDialog(this) == DialogResult.OK) { AnnCodecs codecs = new AnnCodecs(); codecs.Save(saveFileDialog.FileName, _automation.Container, AnnFormat.Annotations, 1); } } }
private void _miLoad_Click(object sender, EventArgs e) { AnnContainer container = _automation.Container; AnnCodecs codecs = new AnnCodecs(); using (OpenFileDialog openFileDialog = new OpenFileDialog()) { openFileDialog.Filter = "Annotations File|*.xml"; if (openFileDialog.ShowDialog(this) == DialogResult.OK) { AnnContainer tmpContainer = null; try { tmpContainer = codecs.Load(openFileDialog.FileName, 1); } catch { Messager.ShowError(this, "Invalid Annotation File"); } if (tmpContainer != null) { _automation.SelectLayer(null); container.Children.Clear(); container.Layers.Clear(); container.SelectionObject.SelectedObjects.Clear(); foreach (AnnObject annObject in tmpContainer.Children) { container.Children.Add(annObject); } AnnLayerCollection tmpLayers = tmpContainer.Layers; AnnLayerCollection containerLayers = _containerNode.Layer.Layers; containerLayers.Clear(); foreach (AnnLayer layer in tmpLayers) { container.Layers.Add(layer); } _tvLayers.BeginUpdate(); _tvLayers.Nodes.Clear(); _containerNode.Nodes.Clear(); _tvLayers.Nodes.Add(_containerNode); AddLayersNodes(container.Layers, _containerNode); _tvLayers.EndUpdate(); _automation.Invalidate(LeadRectD.Empty); } } } }
public static GetAnnotationsResponse GetAnnotations(GetAnnotationsRequest request) { if (request == null) { throw new ArgumentNullException("request"); } if (string.IsNullOrEmpty(request.DocumentId)) { throw new ArgumentException("documentId must not be null"); } if (request.PageNumber < 0) { throw new ArgumentException("'pageNumber' must be a value greater than or equal to 0"); } // If page number is 0, get all annotations // Now load the document var cache = ServiceHelper.Cache; using (var document = DocumentFactory.LoadFromCache(cache, request.DocumentId)) { DocumentHelper.CheckLoadFromCache(document); var annCodec = new AnnCodecs(); string annotations = null; if (request.PageNumber == 0) { var containers = document.Annotations.GetAnnotations(request.CreateEmpty); annotations = annCodec.SaveAllToString(containers, AnnFormat.Annotations); } else { DocumentHelper.CheckPageNumber(document, request.PageNumber); var documentPage = document.Pages[request.PageNumber - 1]; var container = documentPage.GetAnnotations(request.CreateEmpty); if (container != null) { annotations = annCodec.SaveToString(container, AnnFormat.Annotations, request.PageNumber); } } return(new GetAnnotationsResponse { Annotations = annotations }); } }
public static DicomDataSet GeneratePresentationState(string seriesInstanceUID, string annotationData, string description, DicomDataSet seriesDs, int windowCenter, int windowWidth, out string sopInstanceUID) { AnnCodecs codec = new AnnCodecs(); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(annotationData))) { ms.Position = 0; AnnCodecsInfo codecInfo = codec.GetInfo(ms); ms.Position = 0; JavaScriptSerializer jsSerialzer = new JavaScriptSerializer(); DicomAnnotationsUtilities dicomAnnotationsUtilities = new DicomAnnotationsUtilities(); DicomDataSet ds = new DicomDataSet(); sopInstanceUID = SeriesGenerator.GenerateDicomUniqueIdentifier(); //Patient Module C.7.1.1 ds.InsertElementAndSetValue(DicomTag.PatientName, seriesDs.GetValue <string>(DicomTag.PatientName, string.Empty)); ds.InsertElementAndSetValue(DicomTag.PatientID, seriesDs.GetValue <string>(DicomTag.PatientID, string.Empty)); ds.InsertElementAndSetValue(DicomTag.PatientBirthDate, ""); ds.InsertElementAndSetValue(DicomTag.PatientSex, ""); //Study Module C.7.2.1 ds.InsertElementAndSetValue(DicomTag.StudyInstanceUID, seriesDs.GetValue <string>(DicomTag.StudyInstanceUID, string.Empty)); ds.InsertElementAndSetValue(DicomTag.StudyDate, ""); ds.InsertElementAndSetValue(DicomTag.StudyTime, ""); ds.InsertElementAndSetValue(DicomTag.ReferringPhysicianName, ""); ds.InsertElementAndSetValue(DicomTag.StudyID, seriesDs.GetValue <string>(DicomTag.StudyID, string.Empty)); ds.InsertElementAndSetValue(DicomTag.AccessionNumber, seriesDs.GetValue <string>(DicomTag.AccessionNumber, string.Empty)); //Series Module C.7.3.1 ds.InsertElementAndSetValue(DicomTag.SeriesInstanceUID, SeriesGenerator.GenerateDicomUniqueIdentifier()); ds.InsertElementAndSetValue(DicomTag.Modality, "PR"); ds.InsertElementAndSetValue(DicomTag.SeriesNumber, 1); ds.InsertElementAndSetValue(DicomTag.SeriesDate, DicomDateValue.Now); ds.InsertElementAndSetValue(DicomTag.SeriesTime, DicomTimeValue.Now); ds.InsertElementAndSetValue(DicomTag.SeriesDescription, "Study layout presentation state"); //General Equipment Module C.7.5.1 ds.InsertElementAndSetValue(DicomTag.Manufacturer, "LEADTOOLS IMAGING"); ds.InsertElementAndSetValue(DicomTag.InstitutionName, "LEADTOOLS, INC."); ds.InsertElementAndSetValue(DicomTag.StationName, "HTML5 Viewer"); //Presentation State Identification Module C.11.10 ds.InsertElementAndSetValue(DicomTag.PresentationCreationDate, DicomDateValue.Now); ds.InsertElementAndSetValue(DicomTag.PresentationCreationTime, DicomTimeValue.Now); //Content Identification Macro Table 10-12 ds.InsertElementAndSetValue(DicomTag.InstanceNumber, 1); ds.InsertElementAndSetValue(DicomTag.ContentLabel, "STUDY LAYOUT PRESENTATION"); ds.InsertElementAndSetValue(DicomTag.ContentDescription, description); //ds.InsertElementAndSetValue(DicomTag.ContentCreatorName, userName); //Presentation State RelationShip Module C11.11 PresentationStateRelationShip referncedSeriesSeq = new PresentationStateRelationShip(); referncedSeriesSeq.ReferencedSeriesSequence = new List <ReferencedSeries>(); ReferencedSeries referencedSeries = new ReferencedSeries(); referencedSeries.SeriesInstanceUID = seriesInstanceUID; referencedSeries.ReferencedImageSequence = new List <SopInstanceReference>(); referncedSeriesSeq.ReferencedSeriesSequence.Add(referencedSeries); Dictionary <LeadSize, List <ImageSopInstanceReference> > displayedAreaInstance = new Dictionary <LeadSize, List <ImageSopInstanceReference> >(); for (int index = 0; index < codecInfo.Pages.Length; index++) { AnnContainer container = codec.Load(ms, codecInfo.Pages[index]); ms.Position = 0; if (null == container.UserData) { continue; } AnnUserData refInstance = (AnnUserData)jsSerialzer.Deserialize <AnnUserData>(container.UserData.ToString()); if (null != refInstance && null != refInstance.ReferencedImageSequence) { referncedSeriesSeq.ReferencedSeriesSequence[0].ReferencedImageSequence.Add(refInstance.ReferencedImageSequence); // The Medical Viewer defaults dpi to 150 // In this case, there is enough information to compute the dpi, which should be 150 //double dpiX = 0; //double dpiY = 0; //container.CalculateDpi(out dpiX, out dpiY); //if (dpiX == 0 || dpiY == 0) //{ // dpiX = 150.0; // dpiY = 150.0; //} double xDpi = 150; double yDpi = 150; dicomAnnotationsUtilities.ImageDpiX = xDpi; dicomAnnotationsUtilities.ImageDpiY = yDpi; DicomElement graphicSequenceItem = dicomAnnotationsUtilities.FromAnnContainerToDataSet(ds, container); DicomElement layerElement = ds.FindFirstElement(graphicSequenceItem, DicomTag.GraphicLayer, false); if (null == layerElement) { ds.InsertElementAndSetValue(graphicSequenceItem, true, DicomTag.GraphicLayer, "LAYER1"); } else { ds.SetStringValue(layerElement, "LAYER1", DicomCharacterSetType.Default); } GraphicAnnotationsModule annModule = new GraphicAnnotationsModule(); annModule.ReferencedImageSequence = new List <ImageSopInstanceReference>(); annModule.ReferencedImageSequence.Add(refInstance.ReferencedImageSequence); ds.Set(graphicSequenceItem, annModule); } if (!refInstance.ImageSize.IsEmpty) { if (!displayedAreaInstance.ContainsKey(refInstance.ImageSize)) { displayedAreaInstance[refInstance.ImageSize] = new List <ImageSopInstanceReference>(); } displayedAreaInstance[refInstance.ImageSize].Add(refInstance.ReferencedImageSequence); } } ds.Set(referncedSeriesSeq); //Displayed Area Module // // DisplayedAreaModule displayedAreaModule = new DisplayedAreaModule(); displayedAreaModule.DisplayedAreaSelection = new List <DisplayedAreaSelection>(); foreach (KeyValuePair <LeadSize, List <ImageSopInstanceReference> > areaInstance in displayedAreaInstance) { DisplayedAreaSelection displayedArea = new DisplayedAreaSelection(); displayedAreaModule.DisplayedAreaSelection.Add(displayedArea); displayedArea.DisplayedAreaTopLeftHandCorner = new List <long>(); displayedArea.DisplayedAreaBottomRightHandCorner = new List <long>(); displayedArea.DisplayedAreaTopLeftHandCorner.Add(1); displayedArea.DisplayedAreaTopLeftHandCorner.Add(1); displayedArea.DisplayedAreaBottomRightHandCorner.Add(areaInstance.Key.Width); displayedArea.DisplayedAreaBottomRightHandCorner.Add(areaInstance.Key.Height); displayedArea.PresentationSizeMode = PresentationSizeMode.ScaleToFit; displayedArea.PresentationPixelAspectRatio = new List <int>(); displayedArea.PresentationPixelAspectRatio.Add(1); displayedArea.PresentationPixelAspectRatio.Add(1); if (displayedAreaInstance.Count > 1) { displayedArea.ReferencedImageSequence = areaInstance.Value; } } ds.Set(displayedAreaModule); //Graphic Layer Module GraphicLayerModule graphicLayerModule = new GraphicLayerModule(); GraphicLayer layer = new GraphicLayer(); graphicLayerModule.GraphicLayerSequence = new List <GraphicLayer>(); layer.GraphicLayerName = "LAYER1"; layer.GraphicLayerOrder = 1; graphicLayerModule.GraphicLayerSequence.Add(layer); ds.Set(graphicLayerModule); //Softcopy Presentation LUT Module SoftCopyPresentationLutModule presentationLut = new SoftCopyPresentationLutModule(); presentationLut.PresentationLutShape = PresentationLutShape.Identity; if (windowCenter != -1 || windowWidth != -1) { SoftCopyVoiLutModule module = new SoftCopyVoiLutModule(); module.WindowCenter = new List <double>(); module.WindowCenter.Add(windowCenter); module.WindowWidth = new List <double>(); module.WindowWidth.Add(windowWidth); ds.Set(module); } ds.Set(presentationLut); //SOP Common Module ds.InsertElementAndSetValue(DicomTag.SOPClassUID, DicomUidType.GrayscaleSoftcopyPresentationStateStorage); ds.InsertElementAndSetValue(DicomTag.SOPInstanceUID, sopInstanceUID); ds.InsertElementAndSetValue(DicomTag.InstanceCreationDate, DicomDateValue.Now); ds.InsertElementAndSetValue(DicomTag.InstanceCreationTime, DicomDateValue.Now); ds.InsertElementAndSetValue(DicomTag.InstanceNumber, 1); return(ds); } }
public static DicomDataSet GeneratePresentationStateForAnnotations ( string userName, string seriesInstanceUID, string annotationData, string description, string userData, DataSet seriesDs ) { AnnCodecs codec = new AnnCodecs(); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(annotationData))) { ms.Position = 0; AnnCodecsInfo codecInfo = codec.GetInfo(ms); ms.Position = 0; JavaScriptSerializer jsSerialzer = new JavaScriptSerializer(); DicomAnnotationsUtilities dicomAnnotationsUtilities = new DicomAnnotationsUtilities(); if (null == seriesDs || seriesDs.Tables[DataTableHelper.PatientTableName].Rows.Count == 0 || seriesDs.Tables[DataTableHelper.StudyTableName].Rows.Count == 0) { throw new Exception("Series not found"); } DicomDataSet ds = new DicomDataSet(); { DataRow patient = seriesDs.Tables[DataTableHelper.PatientTableName].Rows[0]; DataRow study = seriesDs.Tables[DataTableHelper.StudyTableName].Rows[0]; IPatientInfo patientInfo = RegisteredDataRows.PatientInfo; PersonNameComponent pn = patientInfo.Name(patient); string sFamilyName = pn.FamilyName; string sGivenName = pn.GivenName; string sMiddleName = pn.MiddleName; string sNamePrefix = pn.NamePrefix; string sNameSuffix = pn.NameSuffix; string sPatientId = patientInfo.GetElementValue(patient, DicomTag.PatientID); //Patient Module C.7.1.1 ds.InsertElementAndSetValue(DicomTag.PatientName, string.Format("{0}^{1}^{2}^{3}^{4}", string.IsNullOrEmpty(sFamilyName) ? "" : sFamilyName, string.IsNullOrEmpty(sGivenName) ? "" : sGivenName, string.IsNullOrEmpty(sMiddleName) ? "" : sMiddleName, string.IsNullOrEmpty(sNamePrefix) ? "" : sNamePrefix, string.IsNullOrEmpty(sNameSuffix) ? "" : sNameSuffix)); ds.InsertElementAndSetValue(DicomTag.PatientID, sPatientId); ds.InsertElementAndSetValue(DicomTag.PatientBirthDate, ""); ds.InsertElementAndSetValue(DicomTag.PatientSex, ""); IStudyInfo studyInfo = RegisteredDataRows.StudyInfo; string sStudyInstanceUid = studyInfo.GetElementValue(study, DicomTag.StudyInstanceUID); string sAccessionNumber = studyInfo.GetElementValue(study, DicomTag.AccessionNumber); string sStudyId = studyInfo.GetElementValue(study, DicomTag.StudyID); //Study Module C.7.2.1 ds.InsertElementAndSetValue(DicomTag.StudyInstanceUID, sStudyInstanceUid); ds.InsertElementAndSetValue(DicomTag.StudyDate, ""); ds.InsertElementAndSetValue(DicomTag.StudyTime, ""); ds.InsertElementAndSetValue(DicomTag.ReferringPhysicianName, ""); ds.InsertElementAndSetValue(DicomTag.StudyID, string.IsNullOrEmpty(sStudyId) ? "" : sStudyId); ds.InsertElementAndSetValue(DicomTag.AccessionNumber, string.IsNullOrEmpty(sAccessionNumber) ? "" : sAccessionNumber); //Series Module C.7.3.1 ds.InsertElementAndSetValue(DicomTag.SeriesInstanceUID, SeriesGenerator.GenerateDicomUniqueIdentifier()); ds.InsertElementAndSetValue(DicomTag.Modality, "PR"); ds.InsertElementAndSetValue(DicomTag.SeriesNumber, 1); ds.InsertElementAndSetValue(DicomTag.SeriesDate, DicomDateValue.Now); ds.InsertElementAndSetValue(DicomTag.SeriesTime, DicomTimeValue.Now); ds.InsertElementAndSetValue(DicomTag.SeriesDescription, "Annotations presentation state"); //General Equipment Module C.7.5.1 ds.InsertElementAndSetValue(DicomTag.Manufacturer, "LEADTOOLS IMAGING"); ds.InsertElementAndSetValue(DicomTag.InstitutionName, "LEADTOOLS, INC."); ds.InsertElementAndSetValue(DicomTag.StationName, "HTML5 Viewer"); //Presentation State Identification Module C.11.10 ds.InsertElementAndSetValue(DicomTag.PresentationCreationDate, DicomDateValue.Now); ds.InsertElementAndSetValue(DicomTag.PresentationCreationTime, DicomTimeValue.Now); //Content Identification Macro Table 10-12 ds.InsertElementAndSetValue(DicomTag.InstanceNumber, 1); ds.InsertElementAndSetValue(DicomTag.ContentLabel, "ANNOTATIONS"); ds.InsertElementAndSetValue(DicomTag.ContentDescription, description); ds.InsertElementAndSetValue(DicomTag.ContentCreatorName, userName); //Presentation State RelationShip Module C11.11 PresentationStateRelationShip referncedSeriesSeq = new PresentationStateRelationShip(); referncedSeriesSeq.ReferencedSeriesSequence = new List <ReferencedSeries>(); ReferencedSeries referencedSeries = new ReferencedSeries(); referencedSeries.SeriesInstanceUID = seriesInstanceUID; referencedSeries.ReferencedImageSequence = new List <SopInstanceReference>(); referncedSeriesSeq.ReferencedSeriesSequence.Add(referencedSeries); Dictionary <LeadSize, List <ImageSopInstanceReference> > displayedAreaInstance = new Dictionary <LeadSize, List <ImageSopInstanceReference> >(); for (int index = 0; index < codecInfo.Pages.Length; index++) { AnnContainer container = codec.Load(ms, codecInfo.Pages[index]); ms.Position = 0; if (null == container.UserData) { continue; } AnnUserData refInstance = (AnnUserData)jsSerialzer.Deserialize <AnnUserData>(container.UserData.ToString()); if (null != refInstance && null != refInstance.ReferencedImageSequence) { referncedSeriesSeq.ReferencedSeriesSequence[0].ReferencedImageSequence.Add(refInstance.ReferencedImageSequence); // The Medical Viewer defaults dpi to 150 // In this case, there is enough information to compute the dpi, which should be 150 //double dpiX = 0; //double dpiY = 0; //container.CalculateDpi(out dpiX, out dpiY); //if (dpiX == 0 || dpiY == 0) //{ // dpiX = 150.0; // dpiY = 150.0; //} double xDpi = 150; double yDpi = 150; dicomAnnotationsUtilities.ImageDpiX = xDpi; dicomAnnotationsUtilities.ImageDpiY = yDpi; DicomElement graphicSequenceItem = dicomAnnotationsUtilities.FromAnnContainerToDataSet(ds, container); DicomElement layerElement = ds.FindFirstElement(graphicSequenceItem, DicomTag.GraphicLayer, false); if (null == layerElement) { ds.InsertElementAndSetValue(graphicSequenceItem, true, DicomTag.GraphicLayer, "LAYER1"); } else { ds.SetStringValue(layerElement, "LAYER1", DicomCharacterSetType.Default); } GraphicAnnotationsModule annModule = new GraphicAnnotationsModule(); annModule.ReferencedImageSequence = new List <ImageSopInstanceReference>(); annModule.ReferencedImageSequence.Add(refInstance.ReferencedImageSequence); ds.Set(graphicSequenceItem, annModule); } if (!refInstance.ImageSize.IsEmpty) { if (!displayedAreaInstance.ContainsKey(refInstance.ImageSize)) { displayedAreaInstance[refInstance.ImageSize] = new List <ImageSopInstanceReference>(); } displayedAreaInstance[refInstance.ImageSize].Add(refInstance.ReferencedImageSequence); } } ds.Set(referncedSeriesSeq); //Displayed Area Module // // DisplayedAreaModule displayedAreaModule = new DisplayedAreaModule(); displayedAreaModule.DisplayedAreaSelection = new List <DisplayedAreaSelection>(); foreach (KeyValuePair <LeadSize, List <ImageSopInstanceReference> > areaInstance in displayedAreaInstance) { DisplayedAreaSelection displayedArea = new DisplayedAreaSelection(); displayedAreaModule.DisplayedAreaSelection.Add(displayedArea); displayedArea.DisplayedAreaTopLeftHandCorner = new List <long>(); displayedArea.DisplayedAreaBottomRightHandCorner = new List <long>(); displayedArea.DisplayedAreaTopLeftHandCorner.Add(1); displayedArea.DisplayedAreaTopLeftHandCorner.Add(1); displayedArea.DisplayedAreaBottomRightHandCorner.Add(areaInstance.Key.Width); displayedArea.DisplayedAreaBottomRightHandCorner.Add(areaInstance.Key.Height); displayedArea.PresentationSizeMode = PresentationSizeMode.ScaleToFit; displayedArea.PresentationPixelAspectRatio = new List <int>(); displayedArea.PresentationPixelAspectRatio.Add(1); displayedArea.PresentationPixelAspectRatio.Add(1); if (displayedAreaInstance.Count > 1) { displayedArea.ReferencedImageSequence = areaInstance.Value; } } ds.Set(displayedAreaModule); //Graphic Layer Module GraphicLayerModule graphicLayerModule = new GraphicLayerModule(); graphicLayerModule.GraphicLayerSequence = new List <GraphicLayer>(); GraphicLayer layer = new GraphicLayer(); layer.GraphicLayerName = "LAYER1"; layer.GraphicLayerOrder = 1; graphicLayerModule.GraphicLayerSequence.Add(layer); ds.Set(graphicLayerModule); //Softcopy Presentation LUT Module SoftCopyPresentationLutModule presentationLut = new SoftCopyPresentationLutModule(); presentationLut.PresentationLutShape = PresentationLutShape.Identity; ds.Set(presentationLut); //SOP Common Module ds.InsertElementAndSetValue(DicomTag.SOPClassUID, DicomUidType.GrayscaleSoftcopyPresentationStateStorage); ds.InsertElementAndSetValue(DicomTag.SOPInstanceUID, SeriesGenerator.GenerateDicomUniqueIdentifier()); ds.InsertElementAndSetValue(DicomTag.InstanceCreationDate, DicomDateValue.Now); ds.InsertElementAndSetValue(DicomTag.InstanceCreationTime, DicomDateValue.Now); ds.InsertElementAndSetValue(DicomTag.InstanceNumber, 1); } return(ds); } }
public static Response SetAnnotations(SetAnnotationsRequest request) { if (request == null) { throw new ArgumentNullException("request"); } if (string.IsNullOrEmpty(request.DocumentId)) { throw new ArgumentException("documentId must not be null"); } if (request.PageNumber < 0) { throw new ArgumentException("'pageNumber' must be a value greater than or equal to 0"); } // If pageNumber 0, set for all pages var annCodec = new AnnCodecs(); AnnContainer[] containers = null; if (!string.IsNullOrEmpty(request.Annotations)) { containers = annCodec.LoadAllFromString(request.Annotations); } // Now load the document var cache = ServiceHelper.Cache; using (var document = DocumentFactory.LoadFromCache(cache, request.DocumentId)) { DocumentHelper.CheckLoadFromCache(document); // If the document is read-only then below will fail. So, temporarily reset the value var wasReadOnly = document.IsReadOnly; document.IsReadOnly = false; if (request.PageNumber == 0) { // Set all document.Annotations.SetAnnotations(containers); } else { DocumentHelper.CheckPageNumber(document, request.PageNumber); var documentPage = document.Pages[request.PageNumber - 1]; AnnContainer container = null; if (containers != null) { if (containers.Length == 1) { container = containers[0]; } else { for (var i = 0; i < containers.Length && container == null; i++) { if (containers[i].PageNumber == request.PageNumber) { container = containers[i]; } } } } documentPage.SetAnnotations(container); } // reset the read-only value before saving into the cache document.IsReadOnly = wasReadOnly; document.SaveToCache(); } return(new Response()); }
private static void ProcessObjects(Dictionary <string, string> ibmStrings, string documentId, string[] guids, AnnHistoryItemState state, AnnContainer[] containers) { if (guids.Length == 0) { return; } bool logging = _loggingLEADToIBM; if (logging) { Trace.WriteLine(string.Format("Processing '{0}' objects", state)); } // Use the write options to customize the conversion. IBMP8WriteOptions writeOptions = new IBMP8WriteOptions(); // We know the destination page number from the container, so we don't need to infer it. writeOptions.InferPageNumberFromMetadata = false; writeOptions.InferForMultiPageTiffFromMetadata = false; // Deleted objects are a special case - we won't have their annotations to convert! We will only have the guid. if (state == AnnHistoryItemState.Deleted) { foreach (string guid in guids) { if (logging) { Trace.WriteLine(string.Format(" {0}", guid)); } ibmStrings.Add(guid, null); } } else { // Get the LEADTOOLS annotation objects for each container from the guids. var objects = AnnContainer.FindObjectsByGuid(containers, guids); foreach (int containerIndex in objects.Keys) { var container = containers[containerIndex]; var containerObjects = objects[containerIndex]; // Customize the write options for this specific container. writeOptions.PageNumber = container.PageNumber; writeOptions.Mapper = container.Mapper; if (logging) { Trace.WriteLine(string.Format(" Page {0}", container.PageNumber)); } // Convert each AnnObject back to an IBM annotation XML string. foreach (AnnObject leadObj in containerObjects) { string guid = leadObj.Guid; string outputLogMessage = null; if (logging) { outputLogMessage = string.Format(" {0} ({1}) ({2})", leadObj.FriendlyName, leadObj.Id, guid); } // See "#REF IBM_Annotations_Support" for support info string ibmObjString = AnnCodecs.ConvertToIBMP8(leadObj, writeOptions); // If null, the LEAD AnnObject is not supported in the IBMP8 spec. if (ibmObjString == null) { if (logging) { Trace.WriteLine(string.Format("{0} UNSUPPORTED", outputLogMessage)); } if (ReturnUnsupported) { // Still add it to the response ibmStrings.Add(guid, UNSUPPORTED_VALUE); } continue; } else { if (logging) { Trace.WriteLine(outputLogMessage); } } // The GUID for added objects are auto-generated by LEAD to random values. // You may modify them (or any attribute) here: guid = "mod-" + leadObj.Guid; // Change the guid in the XML ibmObjString = AnnCodecs.WriteIBMP8PropDescAttr(ibmObjString, AnnCodecs.IBM_ID, guid, writeOptions); // Update the guid for our response, too ibmStrings.Add(guid, ibmObjString); } } } }
public SetAnnotationsIBMResponse SetAnnotationsIBM(SetAnnotationsIBMRequest request) { if (request == null) { throw new ArgumentNullException("request"); } // Must have the documentId you'd like to add annotations to. // If you only have the document cache URI, DocumentFactory.LoadFromUri needs to be called. if (string.IsNullOrEmpty(request.DocumentId)) { throw new ArgumentNullException("documentId"); } // Check that we have annotations. if (request.Annotations == null) { throw new ArgumentNullException("annotations"); } var cache = ServiceHelper.Cache; using (var document = DocumentFactory.LoadFromCache(cache, request.DocumentId)) { // Ensure we have the document. DocumentHelper.CheckLoadFromCache(document); // If the document is read-only then we won't be able to modify its settings. Temporarily change this state. bool wasReadOnly = document.IsReadOnly; document.IsReadOnly = false; // Get the IBM annotations from the request. IBMAnnotation[] ibmAnnotationObjects = request.Annotations; // Start converting. We need a rendering engine instance to help with measuring font sizes. AnnRenderingEngine renderingEngine = ServiceHelper.GetAnnRenderingEngine(); // We have different options for reading the annotation... IBMP8ReadOptions readOptions = new IBMP8ReadOptions(); readOptions.RenderingEngine = renderingEngine; int pagesCount = document.Pages.Count; // We have all the IBM objects converted to LEAD; now, add them to their respective page containers. Dictionary <int, AnnContainer> modifiedContainers = new Dictionary <int, AnnContainer>(); for (int i = 0; i < ibmAnnotationObjects.Length; i++) { // Our IBM annotation, as an XML string. IBMAnnotation ibmObj = ibmAnnotationObjects[i]; if (ibmObj == null || string.IsNullOrEmpty(ibmObj.Annotation)) { continue; } try { // Before converting, get the target page number. string ibmPageNumberValue = AnnCodecs.ReadIBMP8PropDescAttr(ibmObj.Annotation, AnnCodecs.IBM_PAGENUMBER); int pageNumber = 1; if (!string.IsNullOrEmpty(ibmPageNumberValue)) { int.TryParse(ibmPageNumberValue, out pageNumber); } // Make sure the page exists. // If zero, set to page 1; if outside of the document range, disregard it. if (pageNumber == 0) { pageNumber = 1; } else if (pageNumber > pagesCount) { continue; } // Get its container (one per page) and add the object to it. DocumentPage documentPage = document.Pages[pageNumber - 1]; AnnContainer container = null; if (modifiedContainers.ContainsKey(pageNumber)) { container = modifiedContainers[pageNumber]; } else { container = documentPage.GetAnnotations(true); modifiedContainers.Add(pageNumber, container); } readOptions.Mapper = container.Mapper; // Convert to a LEADTOOLS AnnObject. // See "#REF IBM_Annotations_Support" for support info AnnObject leadObj = AnnCodecs.ConvertFromIBMP8(ibmObj.Annotation, readOptions); if (leadObj == null) { Trace.WriteLine("Conversion from IBM Annotation not supported for item at index " + i); continue; } // Add the supplied properties if (!string.IsNullOrEmpty(ibmObj.Password)) { leadObj.Lock(ibmObj.Password); } if (!string.IsNullOrEmpty(ibmObj.UserId)) { leadObj.UserId = ibmObj.UserId; Dictionary <string, string> metadata = leadObj.Metadata; string key = AnnObject.AuthorMetadataKey; if (metadata.ContainsKey(key)) { if (string.IsNullOrEmpty(metadata[key])) { metadata[key] = ibmObj.UserId; } } else { metadata.Add(key, ibmObj.UserId); } } container.Children.Add(leadObj); } catch (Exception e) { Trace.WriteLine(string.Format("Failed to convert IBM Annotation at index {0}: {1}", i, e.Message)); } } // Set the modified containers in the document. AnnContainer[] containers = modifiedContainers.Values.ToArray(); document.Annotations.SetAnnotations(containers); // Reset the read-only value from above before saving into the cache. document.IsReadOnly = wasReadOnly; // Enable history tracking from this point forward so that calls to retrieve the IBM Annotations will have a history from this set operation. document.History.AutoUpdate = true; // Clear any old history. AnnHistory history = document.Annotations.GetHistory(); if (history != null) { history.Clear(); document.Annotations.SetHistory(history); } document.SaveToCache(); return(new SetAnnotationsIBMResponse()); } }
public Annotation() { annCodec = new AnnCodecs(); }
public Annotation() { annCodec = new AnnCodecs(); }
private void _btnStart_Click(object sender, EventArgs e) { bool sourceHasAnnFiles = false; try { //check if source exist. if (!Directory.Exists(_txtSourceDirectory.Text)) { MessageBox.Show("The source directory is not existing", "Incorrect source directory", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } //check if destination exist. if (!Directory.Exists(_txtDestinationDirectory.Text)) { Directory.CreateDirectory(_txtDestinationDirectory.Text); } } catch (Exception ex) { MessageBox.Show(ex.Message); } _converting = true; _lvResults.Items.Clear(); UpdateButtons(); int index = 0; string[] srcFolderFiles = Directory.GetFiles(_txtSourceDirectory.Text, "*.*", SearchOption.TopDirectoryOnly); foreach (string srcAnnotationFile in srcFolderFiles.Where(ext => ext.ToLower().EndsWith(".ann") || ext.ToLower().EndsWith(".xml") || ext.ToLower().EndsWith(".tif") || ext.ToLower().EndsWith(".pdf"))) { Application.DoEvents(); ConversionInfo conversionInfo = new ConversionInfo(); conversionInfo.SourcePath = srcAnnotationFile; string destAnnotationFile = string.Format("{0}.xml", Path.Combine(_txtDestinationDirectory.Text, Path.GetFileNameWithoutExtension(srcAnnotationFile))); conversionInfo.DestinationPath = destAnnotationFile; try { AnnContainer[] containers = null; double dpiX = 96.0; double dpiY = 96.0; //try to get the relative image for this annotations file assuming it is located behind the annotations file , if it is not exist then take the default dpi 96*96 string relativeImageFile = string.Empty; string fileExt = Path.GetExtension(srcAnnotationFile); if (fileExt.ToLower() == ".tif" || fileExt.ToLower() == ".pdf") { //the annotations is embedded inside the file relativeImageFile = srcAnnotationFile; } else { foreach (string file in srcFolderFiles) { if (Path.GetFileNameWithoutExtension(file) == Path.GetFileNameWithoutExtension(srcAnnotationFile) && Path.GetExtension(file).ToLower() != ".xml" && Path.GetExtension(file).ToLower() != ".ann") { relativeImageFile = file; } } } try { if (relativeImageFile != string.Empty) { using (RasterCodecs codecs = new RasterCodecs()) { CodecsImageInfo imageInfo = codecs.GetInformation(relativeImageFile, false); dpiX = imageInfo.XResolution; dpiY = imageInfo.YResolution; } } } catch (Exception ex) { MessageBox.Show(ex.Message); } AnnCodecs annCodecs = new AnnCodecs(); containers = annCodecs.LoadAll(srcAnnotationFile, dpiX, dpiY); conversionInfo.Result = ConversionResult.Success; using (Stream stream = File.OpenWrite(destAnnotationFile)) { annCodecs.SaveAll(stream, containers, AnnFormat.Annotations); } conversionInfo.Page = index + 1; index++; AddConversionUpdate(conversionInfo); sourceHasAnnFiles = true; } catch (Exception) { conversionInfo.Result = ConversionResult.Failed; AddConversionUpdate(conversionInfo); continue; } } _converting = false; UpdateButtons(); if (sourceHasAnnFiles) { MessageBox.Show("Conversion Complete", "Complete", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { MessageBox.Show("There is no valid annotation file in source directory", "No source annotations", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }