public DecryptResponse Decrypt(DecryptRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (request.DocumentId == null)
            {
                throw new ArgumentException("documentId must not be null");
            }

            var cache = ServiceHelper.Cache;

            using (var document = DocumentFactory.LoadFromCache(cache, request.DocumentId))
            {
                DocumentHelper.CheckLoadFromCache(document);

                if (!document.Decrypt(request.Password))
                {
                    throw new ServiceException("Incorrect Password", HttpStatusCode.Forbidden);
                }

                document.SaveToCache();
                return(new DecryptResponse {
                    Document = document
                });
            }
        }
        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
                });
            }
        }
Esempio n. 3
0
        public ParseStructureResponse ParseStructure(ParseStructureRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (string.IsNullOrEmpty(request.DocumentId))
            {
                throw new ArgumentException("documentId must not be null");
            }

            // Now load the document
            var cache = ServiceHelper.Cache;

            using (var document = DocumentFactory.LoadFromCache(cache, request.DocumentId))
            {
                DocumentHelper.CheckLoadFromCache(document);

                if (!document.IsStructureSupported)
                {
                    return(new ParseStructureResponse());
                }

                if (!document.Structure.IsParsed)
                {
                    document.Structure.ParseBookmarks = request.ParseBookmarks;
                    document.Structure.ParsePageLinks = request.ParsePageLinks;
                    document.Structure.Parse();
                    document.SaveToCache();
                }

                var pageLinks = new List <DocumentLink[]>();
                var bookmarks = new List <DocumentBookmark>();

                bookmarks.AddRange(document.Structure.Bookmarks);

                foreach (var page in document.Pages)
                {
                    var links = page.GetLinks();
                    pageLinks.Add(links);
                }

                return(new ParseStructureResponse
                {
                    Bookmarks = bookmarks.ToArray(),
                    PageLinks = pageLinks.ToArray()
                });
            }
        }
        public GetHistoryResponse GetHistory(GetHistoryRequest 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");
            }

            IList <DocumentHistoryItem> items = null;

            var cache = ServiceHelper.Cache;

            using (var document = DocumentFactory.LoadFromCache(cache, request.DocumentId))
            {
                // Ensure we have the document.
                DocumentHelper.CheckLoadFromCache(document);

                DocumentHistory history = document.History;
                items = history.GetItems();

                if (items != null && request.ClearHistory)
                {
                    history.Clear();
                    document.SaveToCache();
                }
            }

            if (_loggingDocumentHistory)
            {
                ShowHistory(request.DocumentId, items);
            }

            DocumentHistoryItem[] itemsArray = new DocumentHistoryItem[items.Count];
            items.CopyTo(itemsArray, 0);
            GetHistoryResponse response = new GetHistoryResponse
            {
                Items = itemsArray
            };

            return(response);
        }
        public HttpResponseMessage GetThumbnailsGrid([FromUri] GetThumbnailsGridRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request", "must not be null");
            }

            if (string.IsNullOrEmpty(request.DocumentId))
            {
                throw new ArgumentException("documentId", "must not be null");
            }

            if (request.FirstPageNumber < 0)
            {
                throw new ArgumentException("'firstPageNumber' must be a value greater than or equal to 0");
            }

            var firstPageNumber = request.FirstPageNumber;
            var lastPageNumber  = request.LastPageNumber;

            // Default is page 1 and -1
            if (firstPageNumber == 0)
            {
                firstPageNumber = 1;
            }
            if (lastPageNumber == 0)
            {
                lastPageNumber = -1;
            }

            if (request.Width < 0 || request.Height < 0)
            {
                throw new ArgumentException("'width' and 'height' must be value greater than or equal to 0");
            }
            if (request.MaximumGridWidth < 0)
            {
                throw new ArgumentException("'maximumGridWidth' must be a value greater than or equal to 0");
            }

            // Get the image format
            var saveFormat = SaveImageFormat.GetFromMimeType(request.MimeType);

            // Now load the document
            var cache = ServiceHelper.Cache;

            using (var document = DocumentFactory.LoadFromCache(cache, request.DocumentId))
            {
                DocumentHelper.CheckLoadFromCache(document);

                if (request.Width > 0 && request.Height > 0)
                {
                    document.Images.ThumbnailPixelSize = new LeadSize(request.Width, request.Height);
                }

                using (var image = document.Images.GetThumbnailsGrid(firstPageNumber, lastPageNumber, request.MaximumGridWidth))
                {
                    Stream stream = ImageSaver.SaveImage(image, document.RasterCodecs, saveFormat, request.MimeType, 0, 0);

                    // If we just return the stream, Web Api will try to serialize it.
                    // If the return type is "HttpResponseMessage" it will not serialize
                    // and you can set the content as you wish.
                    var result = new HttpResponseMessage();
                    result.Content = new StreamContent(stream);
                    ServiceHelper.UpdateCacheSettings(result);
                    return(result);
                }
            }
        }
        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());
        }
        public GetAnnotationsIBMResponse GetAnnotationsIBM(GetAnnotationsIBMRequest 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");
            }

            // The IBM annotations will be stored here (key: GUID, value: XML string).
            Dictionary <AnnHistoryItemState, Dictionary <string, string> > ibmObjects = null;

            var cache = ServiceHelper.Cache;

            using (var document = DocumentFactory.LoadFromCache(cache, request.DocumentId))
            {
                // Ensure we have the document.
                DocumentHelper.CheckLoadFromCache(document);

                // Use the history to return all added, modified, and deleted IBM annotations.
                ibmObjects = ProcessAnnotationsHistory(document);
            }

            // Here (if defined) we send the converted annotations to disk as an example.
            if (ibmObjects != null && _processToDiskRoot != null)
            {
                try
                {
                    string dir = _processToDiskRoot + "/" + request.DocumentId;
                    ProcessToDisk(dir, ibmObjects);
                }
                catch (Exception e)
                {
                    Trace.WriteLine(string.Format("Failed to process converted annotations to disk: {0}", e.Message));
                }
            }

            GetAnnotationsIBMResponse response = new GetAnnotationsIBMResponse();

            if (ibmObjects != null)
            {
                // See #REF IBM_Annotations_Support
                if (ibmObjects.ContainsKey(AnnHistoryItemState.Added))
                {
                    response.Added = ibmObjects[AnnHistoryItemState.Added];
                }
                if (ibmObjects.ContainsKey(AnnHistoryItemState.Modified))
                {
                    response.Modified = ibmObjects[AnnHistoryItemState.Modified];
                }
                if (ibmObjects.ContainsKey(AnnHistoryItemState.Deleted))
                {
                    response.Deleted = ibmObjects[AnnHistoryItemState.Deleted];
                }
            }

            return(response);
        }
        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 HttpResponseMessage GetImage([FromUri] GetImageRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            var pageNumber = request.PageNumber;

            if (string.IsNullOrEmpty(request.DocumentId))
            {
                throw new ArgumentException("documentId must not be null");
            }

            if (pageNumber < 0)
            {
                throw new ArgumentException("'pageNumber' must be a value greater than or equal to 0");
            }

            // Default is page 1
            if (pageNumber == 0)
            {
                pageNumber = 1;
            }

            if (request.Resolution < 0)
            {
                throw new ArgumentException("'resolution' must be a value greater than or equal to 0");
            }

            // Sanity check on other parameters
            if (request.QualityFactor < 0 || request.QualityFactor > 100)
            {
                throw new ArgumentException("'qualityFactor' must be a value between 0 and 100");
            }

            if (request.Width < 0 || request.Height < 0)
            {
                throw new ArgumentException("'width' and 'height' must be value greater than or equal to 0");
            }

            // Get the image format
            var saveFormat = SaveImageFormat.GetFromMimeType(request.MimeType);

            // Now load the document
            var cache = ServiceHelper.Cache;

            using (var document = DocumentFactory.LoadFromCache(cache, request.DocumentId))
            {
                DocumentHelper.CheckLoadFromCache(document);
                DocumentHelper.CheckPageNumber(document, pageNumber);

                var documentPage = document.Pages[pageNumber - 1];
                using (var image = documentPage.GetImage(request.Resolution))
                {
                    // Resize it (will only resize if both width and height are not 0), will also take care of FAX images (with different resolution)
                    ImageResizer.ResizeImage(image, request.Width, request.Height);
                    var stream = ImageSaver.SaveImage(image, document.RasterCodecs, saveFormat, request.MimeType, request.BitsPerPixel, request.QualityFactor);

                    // If we just return the stream, Web Api will try to serialize it.
                    // If the return type is "HttpResponseMessage" it will not serialize
                    // and you can set the content as you wish.
                    var response = new HttpResponseMessage();
                    response.Content = new StreamContent(stream);
                    ServiceHelper.UpdateCacheSettings(response);
                    return(response);
                }
            }
        }
        public ReadBarcodesResponse ReadBarcodes(ReadBarcodesRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            var pageNumber = request.PageNumber;

            if (string.IsNullOrEmpty(request.DocumentId))
            {
                throw new ArgumentException("documentId must not be null");
            }

            if (pageNumber < 0)
            {
                throw new ArgumentException("'pageNumber' must be a value greater than or equal to 0");
            }

            // Default is page 1
            if (pageNumber == 0)
            {
                pageNumber = 1;
            }

            try
            {
                // Now load the document
                var cache = ServiceHelper.Cache;
                using (var document = DocumentFactory.LoadFromCache(cache, request.DocumentId))
                {
                    DocumentHelper.CheckLoadFromCache(document);
                    DocumentHelper.CheckPageNumber(document, pageNumber);

                    // Set the options
                    var barcodeEngine = new BarcodeEngine();
                    document.Barcodes.BarcodeEngine = barcodeEngine;
                    var barcodeReader = barcodeEngine.Reader;

                    // Get the symbologies to read
                    var symbologies = new List <BarcodeSymbology>();
                    if (request.Symbologies != null && request.Symbologies.Length > 0)
                    {
                        symbologies.AddRange(request.Symbologies);
                    }
                    else
                    {
                        symbologies.AddRange(barcodeReader.GetAvailableSymbologies());
                    }

                    // Load the options from config
                    bool usedCustomOptions = ServiceHelper.SetBarcodeReadOptions(barcodeReader);
                    if (!usedCustomOptions)
                    {
                        ServiceHelper.InitBarcodeReader(barcodeReader, false);
                    }

                    var documentPage = document.Pages[pageNumber - 1];
                    var barcodes     = documentPage.ReadBarcodes(request.Bounds, request.MaximumBarcodes, symbologies.ToArray());
                    if (barcodes.Length == 0 && !usedCustomOptions)
                    {
                        // Did not find any barcodes, try again with double pass enabled
                        ServiceHelper.InitBarcodeReader(barcodeReader, true);

                        // Do not read MicroPDF417 in this pass since it is too slow
                        if (symbologies != null && symbologies.Contains(BarcodeSymbology.MicroPDF417))
                        {
                            symbologies.Remove(BarcodeSymbology.MicroPDF417);
                        }

                        // Try again
                        barcodes = documentPage.ReadBarcodes(request.Bounds, request.MaximumBarcodes, symbologies.ToArray());
                    }

                    // If we found any barcodes, parse the ECI data if available
                    foreach (var barcode in barcodes)
                    {
                        if (barcode.Symbology == BarcodeSymbology.QR || barcode.Symbology == BarcodeSymbology.MicroQR)
                        {
                            string eciData = BarcodeData.ParseECIData(barcode.GetData());
                            if (!string.IsNullOrEmpty(eciData))
                            {
                                barcode.Value = eciData;
                            }
                        }
                    }

                    return(new ReadBarcodesResponse {
                        Barcodes = barcodes
                    });
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("ReadBarcodes - Error:{1}{0}documentId:{2} pageNumber:{3}", Environment.NewLine, ex.Message, request.DocumentId, pageNumber), "Error");
                throw;
            }
        }
        public GetTextResponse GetText(GetTextRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            var pageNumber = request.PageNumber;

            if (string.IsNullOrEmpty(request.DocumentId))
            {
                throw new ArgumentException("documentId must not be null");
            }

            if (pageNumber < 0)
            {
                throw new ArgumentException("'pageNumber' must be a value greater than or equal to 0");
            }

            // Default is page 1
            if (pageNumber == 0)
            {
                pageNumber = 1;
            }

            IOcrEngine ocrEngine = null;

            try
            {
                // Now load the document
                var cache = ServiceHelper.Cache;
                using (var document = DocumentFactory.LoadFromCache(cache, request.DocumentId))
                {
                    DocumentHelper.CheckLoadFromCache(document);
                    DocumentHelper.CheckPageNumber(document, pageNumber);

                    document.Text.TextExtractionMode = request.TextExtractionMode;

                    var documentPage = document.Pages[pageNumber - 1];

                    if (document.Text.TextExtractionMode != DocumentTextExtractionMode.OcrOnly && !document.Images.IsSvgSupported)
                    {
                        ocrEngine = ServiceHelper.GetOCREngine();
                        if (ocrEngine != null)
                        {
                            document.Text.OcrEngine = ocrEngine;
                        }
                    }

                    var pageText = documentPage.GetText(request.Clip);
                    return(new GetTextResponse {
                        PageText = pageText
                    });
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("GetText - Error:{1}{0}documentId:{2} pageNumber:{3}", Environment.NewLine, ex.Message, request.DocumentId, pageNumber), "Error");
                throw;
            }
        }
        public HttpResponseMessage GetSvg([FromUri] GetSvgRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            int pageNumber = request.PageNumber;

            if (string.IsNullOrEmpty(request.DocumentId))
            {
                throw new ArgumentException("documentId must not be null");
            }

            if (pageNumber < 0)
            {
                throw new ArgumentException("'pageNumber' must be a value greater than or equals to 0");
            }

            // Default is page 1
            if (pageNumber == 0)
            {
                pageNumber = 1;
            }

            // Now load the document
            var cache = ServiceHelper.Cache;

            using (var document = DocumentFactory.LoadFromCache(cache, request.DocumentId))
            {
                DocumentHelper.CheckLoadFromCache(document);
                DocumentHelper.CheckPageNumber(document, pageNumber);

                document.Images.UnembedSvgImages = request.UnembedImages;

                var documentPage = document.Pages[pageNumber - 1];
                var loadOptions  = new CodecsLoadSvgOptions();
                loadOptions.ForceTextPath          = (request.Options & DocumentGetSvgOptions.ForceTextPath) == DocumentGetSvgOptions.ForceTextPath;
                loadOptions.ForceRealText          = (request.Options & DocumentGetSvgOptions.ForceRealText) == DocumentGetSvgOptions.ForceRealText;
                loadOptions.DropImages             = (request.Options & DocumentGetSvgOptions.DropImages) == DocumentGetSvgOptions.DropImages;
                loadOptions.DropShapes             = (request.Options & DocumentGetSvgOptions.DropShapes) == DocumentGetSvgOptions.DropShapes;
                loadOptions.DropText               = (request.Options & DocumentGetSvgOptions.DropText) == DocumentGetSvgOptions.DropText;
                loadOptions.ForConversion          = (request.Options & DocumentGetSvgOptions.ForConversion) == DocumentGetSvgOptions.ForConversion;
                loadOptions.IgnoreXmlParsingErrors = (request.Options & DocumentGetSvgOptions.IgnoreXmlParsingErrors) == DocumentGetSvgOptions.IgnoreXmlParsingErrors;

                using (var svgDocument = documentPage.GetSvg(loadOptions))
                {
                    if (svgDocument != null)
                    {
                        if (!svgDocument.IsFlat)
                        {
                            svgDocument.Flat(null);
                        }

                        if (!svgDocument.IsRenderOptimized)
                        {
                            svgDocument.BeginRenderOptimize();
                        }

                        var svgBounds = svgDocument.Bounds;
                        if (!svgBounds.IsValid)
                        {
                            svgDocument.CalculateBounds(false);
                        }
                    }

                    if (svgDocument != null)
                    {
                        var gzip   = ServiceHelper.GetSettingBoolean(ServiceHelper.Key_Svg_GZip);
                        var stream = ToStream(svgDocument, gzip);

                        // HttpContext is Web Api's version of WebOperationContext
                        //var currentContext = WebOperationContext.Current;
                        var currentContext = HttpContext.Current;
                        if (currentContext != null)
                        {
                            if (gzip)
                            {
                                currentContext.Response.Headers.Add("Content-Encoding", "gzip");
                            }

                            currentContext.Response.ContentType = "image/svg+xml";
                            currentContext.Response.Headers.Add("ContentLength", stream.Length.ToString());
                        }

                        // If we just return the stream, Web Api will try to serialize it.
                        // If the return type is "HttpResponseMessage" it will not serialize
                        // and you can set the content as you wish.
                        var response = new HttpResponseMessage();
                        response.Content = new StreamContent(stream);
                        ServiceHelper.UpdateCacheSettings(response);
                        return(response);
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
        }
        public HttpResponseMessage GetSvgBackImage([FromUri] GetSvgBackImageRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            var pageNumber = request.PageNumber;

            if (string.IsNullOrEmpty(request.DocumentId))
            {
                throw new ArgumentException("documentId must not be null");
            }

            if (pageNumber < 0)
            {
                throw new ArgumentException("'pageNumber' must be a value greater than or equals to 0");
            }

            // Default is page 1
            if (pageNumber == 0)
            {
                pageNumber = 1;
            }

            if (request.Resolution < 0)
            {
                throw new ArgumentException("'resolution' must be a value greater than or equal to 0");
            }

            // Sanity check on other parameters
            if (request.QualityFactor < 0 || request.QualityFactor > 100)
            {
                throw new ArgumentException("'qualityFactor' must be a value between 0 and 100");
            }

            if (request.Width < 0 || request.Height < 0)
            {
                throw new ArgumentException("'width' and 'height' must be value greater than or equal to 0");
            }

            // Get the image format
            var saveFormat = SaveImageFormat.GetFromMimeType(request.MimeType);

            var rasterBackColor = RasterColor.White;

            if (request.BackColor != null)
            {
                try
                {
                    rasterBackColor = RasterColor.FromHtml(request.BackColor);
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(string.Format("GetImage - Error:{1}{0}documentId:{2} pageNumber:{3}", Environment.NewLine, ex.Message, request.DocumentId, pageNumber), "Error");
                }
            }

            // Now load the document
            var cache = ServiceHelper.Cache;

            using (var document = DocumentFactory.LoadFromCache(cache, request.DocumentId))
            {
                DocumentHelper.CheckLoadFromCache(document);
                DocumentHelper.CheckPageNumber(document, pageNumber);

                var documentPage = document.Pages[pageNumber - 1];
                var image        = documentPage.GetSvgBackImage(rasterBackColor, request.Resolution);
                if (image != null)
                {
                    try
                    {
                        // Resize it (will only resize if both width and height are not 0), will also take care of FAX images (with different resolution)
                        ImageResizer.ResizeImage(image, request.Width, request.Height);
                        var stream = ImageSaver.SaveImage(image, document.RasterCodecs, saveFormat, request.MimeType, request.BitsPerPixel, request.QualityFactor);

                        // If we just return the stream, Web Api will try to serialize it.
                        // If the return type is "HttpResponseMessage" it will not serialize
                        // and you can set the content as you wish.
                        var response = new HttpResponseMessage();
                        response.Content = new StreamContent(stream);
                        ServiceHelper.UpdateCacheSettings(response);
                        return(response);
                    }
                    finally
                    {
                        image.Dispose();
                    }
                }
                else
                {
                    // Instead of throwing an exception, let's return the smallest possible GIF
                    //throw new ServiceException("No SVG Back Image exists", HttpStatusCode.NotFound);

                    var response = new HttpResponseMessage();
                    var data     = Convert.FromBase64String(PageController.smallest_GIF_base64);
                    var ms       = new MemoryStream(data);
                    response.Content = new StreamContent(ImageSaver.PrepareStream(ms, "image/gif"));
                    ServiceHelper.UpdateCacheSettings(response);
                    return(response);
                }
            }
        }