public string DetectMICRLine(string ImageFile)
        {
            string errorCode;

            // CloseNativeImage();
            _imageId = _gdPictureImaging.CreateGdPictureImageFromFile(ImageFile);
            _gdPictureImaging.AutoDeskew(_imageId);
            // System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            // sw.Start();
            int           Length = 36;
            StringBuilder result = new StringBuilder(_gdPictureImaging.MICRDoMICR(_imageId, MICRFont.MICRFontE13B,
                                                                                  MICRContext.MICRContextLineFinding, "0123456789ABCD", Length));

            result = result.Replace(System.Convert.ToString('\0'), "?");
            // sw.Stop();
            GdPictureStatus status = _gdPictureImaging.GetStat();

            if (status == GdPictureStatus.OK)
            {
                result.ToString();
            }
            else
            {
                errorCode = status.ToString();
                return(errorCode);
            }
            _gdPictureImaging.Dispose();

            return(result.ToString());
        }
Exemple #2
0
        /// <summary>
        /// AddTextAnnot adds a text annotation to the annotation manager.
        /// </summary>
        /// <param name="leftPixels">The left coordinate of the annotation (pixels).</param>
        /// <param name="topPixels">The top coordinate of the annotation (pixels).</param>
        /// <param name="widthPixels">The width of the annotation (pixels).</param>
        /// <param name="heightPixels">The height of the annotation (pixels).</param>
        /// <param name="text">The text.</param>
        /// <param name="italic">The italic flag.</param>
        /// <param name="underline">The underline flag.</param>
        /// <param name="fontName">The font name.</param>
        /// <param name="rotation">The rotation of the annotation in the range [0;360] (degrees, clockwise). </param>
        public void AddTextAnnot(int leftPixels, int topPixels, int widthPixels, int heightPixels, string text, bool italic, bool underline, string fontName,
                                 int rotation)
        {
            if (_textWriter != null)
            {
                _textWriter.WriteLine("AddTextAnnot");
                _textWriter.WriteLine("leftPixels: " + leftPixels + " topPixels: " + topPixels + " widthPixels: " + widthPixels + " heightPixels: " + heightPixels);
                _textWriter.WriteLine("text: " + text);
                _textWriter.WriteLine("italic: " + italic + " underline: " + underline + " fontName: " + fontName + " rotation: " + rotation);
            }
            AnnotationText annotationText = _annotationManager.AddTextAnnot(ToInchesHorizontal(leftPixels),
                                                                            ToInchesVertical(topPixels), ToInchesHorizontal(widthPixels), ToInchesVertical(heightPixels), text);
            GdPictureStatus status = _annotationManager.GetStat();

            if (status != GdPictureStatus.OK)
            {
                LastError = status;
            }

            annotationText.Rotation  = rotation;
            annotationText.FontName  = fontName;
            annotationText.FontStyle = FontStyle.Regular;
            if (italic)
            {
                annotationText.FontStyle |= FontStyle.Italic;
            }
            if (underline)
            {
                annotationText.FontStyle |= FontStyle.Underline;
            }
        }
Exemple #3
0
        /// <summary>
        /// AddPolygonAnnot adds a polygon annotation to the annotation manager.
        /// </summary>
        /// <param name="pointsCoordinates">The coordinates for the points that are defining the polygon.</param>
        /// <param name="borderColorComponents">The components for the color of the border.</param>
        /// <param name="backColorComponents">The components for the color of the background.</param>
        /// <param name="fill">The flag indicating whether the polygon should be filled (filled polygon) or not (hollow polygon).</param>
        /// <param name="borderWidthPixels">The width of the border (pixels).</param>
        public void AddPolygonAnnot(int[] pointsCoordinates, byte[] borderColorComponents, byte[] backColorComponents,
                                    bool fill, int borderWidthPixels)
        {
            PointF[] pointsForGdPicture = new PointF[pointsCoordinates.Length / 2];
            for (int index = 0; index < pointsForGdPicture.Length; index++)
            {
                pointsForGdPicture[index].X = ToInchesHorizontal(pointsCoordinates[2 * index]);
                pointsForGdPicture[index].Y = ToInchesVertical(pointsCoordinates[2 * index + 1]);
            }

            AnnotationPolygon annotationPolygon =
                _annotationManager.AddPolygonAnnot(GdPictureColor(borderColorComponents),
                                                   GdPictureColor(backColorComponents), pointsForGdPicture);

            GdPictureStatus status = _annotationManager.GetStat();

            if (status != GdPictureStatus.OK)
            {
                LastError = status;
            }

            if (!fill)
            {
                // We do consider the border width only for hollow polygons.
                annotationPolygon.BorderWidth = ToInchesHorizontal(borderWidthPixels);
                annotationPolygon.Fill        = false;
            }
        }
Exemple #4
0
 private void ThrowIfFailed(GdPictureStatus status, string step)
 {
     if (status != GdPictureStatus.OK)
     {
         string message = $"{step} failed: {status.ToString()}";
         logger.LogError(message);
         throw new Exception(message);
     }
 }
Exemple #5
0
        public static string GerarDocumentoPesquisavelPdf(GdPictureImaging _gdPictureImaging, GdPicturePDF _gdPicturePDF, string documento, bool pdfa = true, string idioma = "por", string titulo = null, string autor = null, string assunto = null, string palavrasChaves = null, string criador = null, int dpi = 250)
        {
            if (Path.GetExtension(documento) != ".pdf")
            {
                documento = Ocr.castTopdf(documento, _gdPictureImaging, _gdPicturePDF);
            }
            int num   = 0;
            var pasta = Guid.NewGuid().ToString();

            _gdPicturePDF.LoadFromFile(documento, true);
            string str = string.Concat(Ocr.GetCurrentDirectory(), "\\GdPicture\\Idiomas");


            using (FileStream fs = File.Create("c:\\lodg.txt"))
            {
                Byte[] info = new UTF8Encoding(true).GetBytes(str);
                // Add some information to the file.
                fs.Write(info, 0, info.Length);
            }
            //  Console.WriteLine(ex.Message);

            string str1      = ConfigurationManager.AppSettings["PastaDestinoTemp"].ToString();
            string str2      = string.Concat(str1, "\\", Path.GetFileName(documento));
            string folder    = Guid.NewGuid().ToString();
            int    pageCount = _gdPicturePDF.GetPageCount();

            for (int i = 1; i <= pageCount; i++)
            {
                Directory.CreateDirectory(str1 + "\\" + pasta);
                _gdPicturePDF.SelectPage(i);
                int gdPictureImageEx = _gdPicturePDF.RenderPageToGdPictureImageEx((float)dpi, true);
                if (gdPictureImageEx != 0)
                {
                    num = _gdPictureImaging.PdfOCRStart(str1 + "\\" + pasta + "\\" + i.ToString() + ".pdf", pdfa, titulo, autor, assunto, palavrasChaves, criador);
                    _gdPictureImaging.PdfAddGdPictureImageToPdfOCR(num, gdPictureImageEx, idioma, str, "");
                    _gdPictureImaging.ReleaseGdPictureImage(gdPictureImageEx);
                    _gdPictureImaging.PdfOCRStop(num);
                }
            }

            _gdPicturePDF.CloseDocument();
            File.Delete(documento);

            GdPictureStatus status = _gdPicturePDF.MergeDocuments(Directory.GetFiles(str1 + "\\" + pasta), str2);


            DirectoryInfo dir = new DirectoryInfo(str1 + "\\" + pasta);

            foreach (FileInfo fi in dir.GetFiles())
            {
                fi.Delete();
            }

            Directory.Delete(str1 + "\\" + pasta);
            return(str2);
        }
Exemple #6
0
        /// <summary>
        /// AddTextAnnot adds a text annotation to the annotation manager.
        /// </summary>
        /// <param name="leftPixels">The left coordinate of the annotation (pixels).</param>
        /// <param name="topPixels">The top coordinate of the annotation (pixels).</param>
        /// <param name="widthPixels">The width of the annotation (pixels).</param>
        /// <param name="heightPixels">The height of the annotation (pixels).</param>
        /// <param name="text">The text.</param>
        /// <param name="link">The link. </param>
        public void AddLinkAnnot(int leftPixels, int topPixels, int widthPixels, int heightPixels, string text,
                                 string link)
        {
            AnnotationLink annotationLink = _annotationManager.AddLinkAnnot(ToInchesHorizontal(leftPixels),
                                                                            ToInchesVertical(topPixels), ToInchesHorizontal(widthPixels), ToInchesVertical(heightPixels), text, link);
            GdPictureStatus status = _annotationManager.GetStat();

            if (status != GdPictureStatus.OK)
            {
                LastError = status;
            }
        }
Exemple #7
0
        /// <summary>
        /// AddRubberStampAnnot adds a buffer stamp annotation to the annotation manager.
        /// </summary>
        /// <param name="leftPixels">The left coordinate of the annotation (pixels).</param>
        /// <param name="topPixels">The top coordinate of the annotation (pixels).</param>
        /// <param name="widthPixels">The width of the annotation (pixels).</param>
        /// <param name="heightPixels">The height of the annotation (pixels).</param>
        /// <param name="text">The text.</param>
        /// <param name="rotation">The rotation of the annotation in the range [0;360] (degrees, clockwise). </param>
        /// <param name="colorComponents">The components for the color for the stamp.</param>
        public void AddRubberStampAnnot(int leftPixels, int topPixels, int widthPixels, int heightPixels, string text,
                                        int rotation, byte[] colorComponents)
        {
            AnnotationRubberStamp annotationRubberStamp =
                _annotationManager.AddRubberStampAnnot(GdPictureColor(colorComponents),
                                                       ToInchesHorizontal(leftPixels), ToInchesVertical(topPixels), ToInchesHorizontal(widthPixels),
                                                       ToInchesVertical(heightPixels), text);
            GdPictureStatus status = _annotationManager.GetStat();

            if (status != GdPictureStatus.OK)
            {
                LastError = status;
            }

            annotationRubberStamp.Rotation = rotation;
        }
Exemple #8
0
        /// <summary>
        /// AddStickyNoteAnnot adds a sticky note annotation to the annotation manager.
        /// </summary>
        /// <param name="leftPixels">The left coordinate of the annotation (pixels).</param>
        /// <param name="topPixels">The top coordinate of the annotation (pixels).</param>
        /// <param name="widthPixels">The width of the annotation (pixels).</param>
        /// <param name="heightPixels">The height of the annotation (pixels).</param>
        /// <param name="text">The text.</param>
        /// <param name="foreColorComponents">The components for the fore color.</param>
        /// <param name="fillColorComponents">the components for the fill color.</param>
        public void AddStickyNoteAnnot(int leftPixels, int topPixels, int widthPixels, int heightPixels, string text,
                                       byte[] foreColorComponents, byte[] fillColorComponents)
        {
            AnnotationStickyNote annotationStickyNote =
                _annotationManager.AddStickyNoteAnnot(ToInchesHorizontal(leftPixels), ToInchesVertical(topPixels),
                                                      ToInchesHorizontal(widthPixels), ToInchesVertical(heightPixels), text);

            GdPictureStatus status = _annotationManager.GetStat();

            if (status != GdPictureStatus.OK)
            {
                LastError = status;
            }

            annotationStickyNote.ForeColor = GdPictureColor(foreColorComponents);
            annotationStickyNote.FillColor = GdPictureColor(fillColorComponents);
        }
Exemple #9
0
        private static void ProcessMovedFileWithGdPicture(string filePath, string ocrDirectory, string completedDirectory)
        {
            var fileName = Path.GetFileName(filePath);
            //We assume that GdPicture has been correctly installed and unlocked.
            GdPicturePDF oGdPicturePDF = new GdPicturePDF();
            //Loading an input document.
            GdPictureStatus status = oGdPicturePDF.LoadFromFile(filePath, false);

            //Checking if loading has been successful.
            if (status == GdPictureStatus.OK)
            {
                int pageCount = oGdPicturePDF.GetPageCount();
                //Loop through pages.
                for (int i = 1; i <= pageCount; i++)
                {
                    //Selecting a page.
                    oGdPicturePDF.SelectPage(i);
                    if (oGdPicturePDF.OcrPage("eng", ocrDirectory, "", 200.0F) != GdPictureStatus.OK)
                    {
                        //Console.WriteLine("OCR Pages Example - Error occurred on the page " + i.ToString() + ". Error: " + oGdPicturePDF.GetStat().ToString());
                    }
                }
                //Saving to a different file.
                var completedFilePath = Path.Combine(
                    completedDirectory,
                    fileName
                    );
                status = oGdPicturePDF.SaveToFile(completedFilePath, true);
                if (status == GdPictureStatus.OK)
                {
                    Console.WriteLine("OCR Pages Example - Done! " + fileName);
                }
                else
                {
                    Console.WriteLine("OCR Pages Example - " + "The document can't be saved." + status.ToString() + " " + fileName);
                }
                //Closing and releasing resources.
                oGdPicturePDF.CloseDocument();
            }
            else
            {
                Console.WriteLine("OCR Pages Example - " + "The document can't be opened." + status.ToString() + " " + fileName);
            }
            oGdPicturePDF.Dispose();
        }
Exemple #10
0
        /// <summary>
        /// Dedicated to process image documents
        /// It retrieves the currently loaded native image handle and initializes an annotation manager object from it.
        /// </summary>
        /// <param name="customActionEventArgs">The arguments received from the custom action handler</param>
        private static void AnnotatePdfDocument(CustomActionEventArgs customActionEventArgs)
        {
            GdPicturePDF    gdPicturePdf;
            GdPictureStatus status = customActionEventArgs.docuVieware.GetNativePDF(out gdPicturePdf);

            if (status == GdPictureStatus.OK)
            {
                using (AnnotationManager annotateMngr = new AnnotationManager())
                {
                    status = annotateMngr.InitFromGdPicturePDF(gdPicturePdf);
                    if (status == GdPictureStatus.OK)
                    {
                        if (customActionEventArgs.actionName == "addTimestamp")
                        {
                            AddTimestampAnnotation(customActionEventArgs, annotateMngr);
                        }
                        else if (customActionEventArgs.actionName == "addSignature")
                        {
                            AddSignatureAnnotation(customActionEventArgs, annotateMngr);
                        }
                        else if (customActionEventArgs.actionName == "addApprovedStamp")
                        {
                            AddApprovedStampAnnotation(customActionEventArgs, annotateMngr);
                        }
                        else if (customActionEventArgs.actionName == "addRejectedStamp")
                        {
                            AddRejecteStampAnnotation(customActionEventArgs, annotateMngr);
                        }
                    }
                    else
                    {
                        customActionEventArgs.message = new DocuViewareMessage("Failed to initialize Annotation Manager. Status is : " + status + ".",
                                                                               icon: DocuViewareMessageIcon.Error);
                    }
                }
            }
            else
            {
                customActionEventArgs.message = new DocuViewareMessage("Failed to retrieve native document. Status is : " + status + ".",
                                                                       icon: DocuViewareMessageIcon.Error);
            }

            return;
        }
Exemple #11
0
        /// <summary>
        /// AddLineAnnot adds a line annotation to the annotation manager.
        /// </summary>
        /// <param name="srcXPixels">The X coordinate of the source (pixels).</param>
        /// <param name="srcYPixels">The Y coordinate of the source (pixels).</param>
        /// <param name="dstXPixels">The X coordinate of the target (pixels).</param>
        /// <param name="dstYPixels">The Y coordinate of the target (pixels).</param>
        /// <param name="colorComponents">The components for the color of the line.</param>
        /// <param name="borderWidthPixels">The width of the border (pixels).</param>
        public void AddLineAnnot(int srcXPixels, int srcYPixels, int dstXPixels, int dstYPixels, byte[] colorComponents, int borderWidthPixels)
        {
            if (_textWriter != null)
            {
                _textWriter.WriteLine("AddLineAnnot");
                _textWriter.WriteLine("srcYPixels: " + srcXPixels + "srcYPixels: " + srcYPixels + " dstXPixels: " + dstXPixels + " dstYPixels: " + dstYPixels);
                _textWriter.WriteLine("colorComponents: " + colorComponents[0] + " " + colorComponents[1] + " " + colorComponents[2]);
                _textWriter.WriteLine("borderWidthPixels: " + borderWidthPixels);
            }
            AnnotationLine  annotation = _annotationManager.AddLineAnnot(GdPictureColor(colorComponents), ToInchesHorizontal(srcXPixels), ToInchesVertical(srcYPixels), ToInchesHorizontal(dstXPixels), ToInchesVertical(dstYPixels));
            GdPictureStatus status     = _annotationManager.GetStat();

            if (status != GdPictureStatus.OK)
            {
                LastError = status;
            }

            annotation.BorderWidth = ToInchesHorizontal(borderWidthPixels);
        }
Exemple #12
0
        public static void CleHole(List <string> strfile)
        {
            LicenseManager oLicenceManager = new LicenseManager();

            oLicenceManager.RegisterKEY(T_ConFigure.Imgid);
            int imageId = 0;

            try {
                using (GdPictureImaging oGdPictureImaging = new GdPictureImaging()) {
                    for (int i = 0; i < strfile.Count; i++)
                    {
                        string file = strfile[i];
                        imageId = oGdPictureImaging.CreateGdPictureImageFromFile(file);
                        if (oGdPictureImaging.GetStat() != GdPictureStatus.OK)
                        {
                            continue;
                        }
                        else
                        {
                            GdPictureStatus status = oGdPictureImaging.RemoveHolePunch(imageId, HolePunchMargins.MarginAll);
                            if (status != GdPictureStatus.OK)
                            {
                                continue;
                            }
                            else
                            {
                                string path = Path.Combine(Path.GetDirectoryName(file));
                                if (!Directory.Exists(path))
                                {
                                    Directory.CreateDirectory(path);
                                }
                                status = oGdPictureImaging.SaveAsTIFF(imageId, file, TiffCompression.TiffCompressionJPEG);
                                if (status != GdPictureStatus.OK)
                                {
                                    continue;
                                }
                            }
                        }
                    }
                    oGdPictureImaging.ReleaseGdPictureImage(imageId);
                }
            } catch {}
        }
Exemple #13
0
        public static string CleHole(Bitmap bmp)
        {
            string         file            = "";
            LicenseManager oLicenceManager = new LicenseManager();

            oLicenceManager.RegisterKEY(T_ConFigure.Imgid);
            using (GdPictureImaging oGdPictureImaging = new GdPictureImaging()) {
                int imageId = oGdPictureImaging.CreateGdPictureImageFromBitmap(bmp);
                if (oGdPictureImaging.GetStat() != GdPictureStatus.OK)
                {
                    return(file);
                }
                else
                {
                    GdPictureStatus status = oGdPictureImaging.RemoveHolePunch(imageId, HolePunchMargins.MarginAll);
                    if (status != GdPictureStatus.OK)
                    {
                        return(file);
                    }
                    else
                    {
                        string path = @"c:\temp\cle";
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        file = Path.Combine(path, DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg");
                        if (File.Exists(file))
                        {
                            File.Delete(file);
                        }
                        status = oGdPictureImaging.SaveAsTIFF(imageId, file, TiffCompression.TiffCompressionJPEG);
                        if (status != GdPictureStatus.OK)
                        {
                            return("");
                        }
                    }
                    oGdPictureImaging.ReleaseGdPictureImage(imageId);
                }
            }
            return(file);
        }
Exemple #14
0
        /// <summary>
        /// Convert pdf to tiff
        /// </summary>
        /// <param name="data">Pdf as byte array (blob)</param>
        /// <returns>Tiff as byte array (blob)</returns>
        public byte[] Convert(byte[] data)
        {
            //We assume that GdPicture has been correctly installed and unlocked.
            using (var converter = GdPictureHelper.GetGdPictureDocumentConverterInstance())
            {
                using (var inStream = new MemoryStream(data))
                {
                    GdPictureStatus status = converter.LoadFromStream(inStream, GdPicture14.DocumentFormat.DocumentFormatPDF);
                    if (status == GdPictureStatus.OK)
                    {
                        using (var stream = new MemoryStream())
                        {
                            status = converter.SaveAsTIFF(stream, TiffCompression.TiffCompressionAUTO);
                            return(stream.ToArray());
                        }
                    }
                }
            }

            return(null);
        }
Exemple #15
0
        /// <summary>
        /// AddFreeHandAnnot adds a free hand annotation to the annotation manager.
        /// </summary>
        /// <param name="pointsCoordinates">The coordinates for the points that are defining the serie of lines.</param>
        /// <param name="colorComponents">The components for the color.</param>
        /// <param name="borderWidthPixels">The width of the border (pixels).</param>
        public void AddFreeHandAnnot(int[] pointsCoordinates, byte[] colorComponents, int borderWidthPixels)
        {
            PointF[] pointsForGdPicture = new PointF[pointsCoordinates.Length / 2];
            for (int index = 0; index < pointsForGdPicture.Length; index++)
            {
                pointsForGdPicture[index].X = ToInchesHorizontal(pointsCoordinates[2 * index]);
                pointsForGdPicture[index].Y = ToInchesVertical(pointsCoordinates[2 * index + 1]);
            }

            AnnotationFreeHand annotationFreeHand = _annotationManager.AddFreeHandAnnot(
                GdPictureColor(colorComponents), pointsForGdPicture);

            GdPictureStatus status = _annotationManager.GetStat();

            if (status != GdPictureStatus.OK)
            {
                LastError = status;
            }

            annotationFreeHand.BorderWidth = ToInchesHorizontal(borderWidthPixels);
        }
Exemple #16
0
        /// <summary>
        /// AddEmbeddedImageAnnot adds an embedded image annotation.
        /// </summary>
        /// <param name="leftPixels">The left coordinate of the annotation (pixels).</param>
        /// <param name="topPixels">The top coordinate of the annotation (pixels).</param>
        /// <param name="widthPixels">The width of the annotation (pixels).</param>
        /// <param name="heightPixels">The height of the annotation (pixels).</param>
        /// <param name="dib">Pointer to a Microsoft® Windows® Graphics Device Interface (GDI) BITMAPINFO structure, as IntPtr value.</param>
        public void AddEmbeddedImageAnnot(int leftPixels, int topPixels, int widthPixels, int heightPixels, IntPtr dib)
        {
            GdPictureImaging imaging = new GdPictureImaging();
            int id = imaging.CreateGdPictureImageFromDIB(dib);

            if (id < 0)
            {
                LastError = imaging.GetStat();
                return;
            }

            AnnotationEmbeddedImage annotationEmbeddedImage = _annotationManager.AddEmbeddedImageAnnot(id,
                                                                                                       ToInchesHorizontal(leftPixels), ToInchesVertical(topPixels),
                                                                                                       ToInchesHorizontal(widthPixels), ToInchesVertical(heightPixels));

            GdPictureStatus status = _annotationManager.GetStat();

            if (status != GdPictureStatus.OK)
            {
                LastError = status;
            }
        }
        /// <summary>
        /// Convert the provided Wang annotated TIFF to a GdPicture/XMP annotated TIFF.
        /// </summary>
        /// <param name="strOutputFilePath">The path to the output tiff.</param>
        /// <param name="errorMessage">Used to retrieve an error message.</param>
        /// <param name="strInputFilePath">The path to the input tiff.</param>
        /// <param name="textExtension">The extension for the text file.</param>
        /// <returns>true if the conversion succeded otherwise returns false.</returns>
        public static bool Convert(string strOutputFilePath, ref string errorMessage, string strInputFilePath,
                                   string textExtension = "")
        {
            using (GdPictureImaging gdPictureImaging = new GdPictureImaging())
            {
                // Load the image
                int imageId = gdPictureImaging.CreateGdPictureImageFromFile(strInputFilePath);
                if (imageId == 0)
                {
                    errorMessage = System.Convert.ToString(gdPictureImaging.GetStat().ToString());
                    gdPictureImaging.ReleaseGdPictureImage(imageId);
                    return(false);
                }

                int pageCount = gdPictureImaging.GetPageCount(imageId);

                // Collect the information required for the conversion of the annotations

                PageInfo[] pageInfo = ReadPageInfo(gdPictureImaging, imageId, pageCount);

                // Save tiff to output file
                GdPictureStatus status = pageCount > 1
                    ? gdPictureImaging.TiffSaveMultiPageToFile(imageId, strOutputFilePath,
                                                               TiffCompression.TiffCompressionAUTO, 100)
                    : gdPictureImaging.SaveAsTIFF(imageId, strOutputFilePath, false,
                                                  TiffCompression.TiffCompressionAUTO, 100);

                gdPictureImaging.ReleaseGdPictureImage(imageId);

                if (status != GdPictureStatus.OK)
                {
                    return(false);
                }

                // Writes the annotations to the tiff
                return(WriteAnnotations(strOutputFilePath, ref errorMessage, pageInfo, pageCount, textExtension));
            }
        }
Exemple #18
0
        /// <summary>
        /// AddFreeHandHighligtherAnnot adds a free hand highligther annotation to the annotation manager.
        /// </summary>
        /// <param name="pointsCoordinates">The coordinates for the points that are defining the serie of lines.</param>
        /// <param name="colorComponents">The components for the color.</param>
        /// <param name="borderWidthPixels">The width of the border (pixels).</param>
        public void AddFreeHandHighligtherAnnot(int[] pointsCoordinates, byte[] colorComponents, int borderWidthPixels)
        {
            if (_textWriter != null)
            {
                _textWriter.WriteLine("AddFreeHandHighligtherAnnot");
                for (int index = 0; index < pointsCoordinates.Length; index++)
                {
                    _textWriter.Write(pointsCoordinates[index] + " ");
                }
                _textWriter.WriteLine("");
                _textWriter.WriteLine("colorComponents: " + colorComponents[0] + " " + colorComponents[1] + " " + colorComponents[2]);
                _textWriter.WriteLine("borderWidthPixels: " + borderWidthPixels);
            }

            AnnotationFreeHandHighlighter annotation = _annotationManager.AddFreeHandHighlighterAnnot(GdPictureColor(colorComponents), ToInches(pointsCoordinates));
            GdPictureStatus status = _annotationManager.GetStat();

            if (status != GdPictureStatus.OK)
            {
                LastError = status;
            }

            annotation.BorderWidth = ToInchesHorizontal(borderWidthPixels);
        }
Exemple #19
0
        /// <summary>
        /// AddRectangleAnnot adds a rectangle annotation to the annotation manager.
        /// </summary>
        /// <param name="leftPixels">The left coordinate of the annotation (pixels).</param>
        /// <param name="topPixels">The top coordinate of the annotation (pixels).</param>
        /// <param name="widthPixels">The width of the annotation (pixels).</param>
        /// <param name="heightPixels">The height of the annotation (pixels).</param>
        /// <param name="borderColorComponents">The components for the color of the border.</param>
        /// <param name="backColorComponents">The components for the color of the background.</param>
        /// <param name="fill">The flag indicating whether the rectangle should be filled (filled rectangle) or not (hollow rectangle).</param>
        /// <param name="borderWidthPixels">The width of the border (pixels).</param>
        public void AddRectangleAnnot(int leftPixels, int topPixels, int widthPixels, int heightPixels,
                                      byte[] borderColorComponents, byte[] backColorComponents, bool fill, int borderWidthPixels)
        {
            AnnotationRectangle annotationRectangle =
                _annotationManager.AddRectangleAnnot(GdPictureColor(borderColorComponents),
                                                     GdPictureColor(backColorComponents),
                                                     ToInchesHorizontal(leftPixels),
                                                     ToInchesVertical(topPixels),
                                                     ToInchesHorizontal(widthPixels), ToInchesVertical(heightPixels));

            GdPictureStatus status = _annotationManager.GetStat();

            if (status != GdPictureStatus.OK)
            {
                LastError = status;
            }

            if (!fill)
            {
                // We do consider the border width only for hollow rectangles.
                annotationRectangle.BorderWidth = ToInchesHorizontal(borderWidthPixels);
                annotationRectangle.Fill        = false;
            }
        }
        /// <summary>
        /// WriteAnnotations writes the tiff to a file including its annotations.
        /// </summary>
        /// <param name="strOutputFilePath">The path to the output file.</param>
        /// <param name="errorMessage">Used to retrieve an error message.</param>
        /// <param name="pageCount">The number of pages.</param>
        /// <param name="pageInfo">The page information.</param>
        /// <param name="textExtension">The extension for the text file.</param>
        /// <returns>true if the conversion succeded otherwise returns false.</returns>
        private static bool WriteAnnotations(string strOutputFilePath, ref string errorMessage, PageInfo[] pageInfo,
                                             int pageCount, string textExtension)
        {
            // Load the tiff from the stream
            using (MemoryStream stream = new MemoryStream())
            {
                using (FileStream fileStream = File.OpenRead(strOutputFilePath))
                {
                    stream.SetLength(fileStream.Length);
                    fileStream.Read(stream.GetBuffer(), 0, (int)fileStream.Length);
                }

                using (AnnotationManager annotationManager = new AnnotationManager())
                {
                    GdPictureStatus status = annotationManager.InitFromStream(stream);
                    if (status != GdPictureStatus.OK)
                    {
                        errorMessage = annotationManager.GetStat().ToString();
                        return(false);
                    }

                    // Write the annotation from the pages
                    for (int pageIndex = 0; pageIndex < pageCount; pageIndex++)
                    {
                        if (pageInfo[pageIndex].WangTagData != null)
                        {
                            annotationManager.SelectPage(pageIndex + 1);
                            bool wangAnnotationsReadingSuccess;
                            if (textExtension == "")
                            {
                                WangTiffToGdPictureTiffWangAnnotationHandler handler =
                                    new WangTiffToGdPictureTiffWangAnnotationHandler(pageInfo[pageIndex].WidthPixels,
                                                                                     pageInfo[pageIndex].HeightPixels, pageInfo[pageIndex].WidthInches,
                                                                                     pageInfo[pageIndex].HeightInches, annotationManager, null);
                                wangAnnotationsReadingSuccess = WangTagReadingLibrary.WangAnnotationsReader.Read(
                                    handler,
                                    pageInfo[pageIndex].WangTagData);
                            }
                            else
                            {
                                using (
                                    StreamWriter textWriter =
                                        new StreamWriter(strOutputFilePath + "." + pageIndex + textExtension))
                                {
                                    WangTiffToGdPictureTiffWangAnnotationHandler handler =
                                        new WangTiffToGdPictureTiffWangAnnotationHandler(
                                            pageInfo[pageIndex].WidthPixels,
                                            pageInfo[pageIndex].HeightPixels, pageInfo[pageIndex].WidthInches,
                                            pageInfo[pageIndex].HeightInches, annotationManager, textWriter);
                                    wangAnnotationsReadingSuccess = WangTagReadingLibrary.WangAnnotationsReader.Read(
                                        handler,
                                        pageInfo[pageIndex].WangTagData);
                                }
                            }
                            if (!wangAnnotationsReadingSuccess)
                            {
                                annotationManager.Close();
                                errorMessage = "An error occurred while reading Wang annotations.";
                                return(false);
                            }
                        }
                    }

                    // Writes the tiff as a file
                    status = annotationManager.SaveDocumentToTIFF(strOutputFilePath,
                                                                  TiffCompression.TiffCompressionAUTO);
                    if (status != GdPictureStatus.OK)
                    {
                        errorMessage = annotationManager.GetStat().ToString();
                        return(false);
                    }
                    annotationManager.Close();
                }
            }
            return(true);
        }
        public static string castTopdf(string file, GdPictureImaging oGdPictureImaging, GdPicturePDF oGdPicturePDF, bool pdfa = true, string idioma = "por", string white = null, string titulo = null, string autor = null, string assunto = null, string palavrasChaves = null, string criador = null, int dpi = 250)
        {
            try
            {
                var exFile = Path.GetExtension(file).ToUpper();
                switch (exFile)
                {
                case ".PDF":
                    #region PDF

                    String folderpdf = Guid.NewGuid().ToString();

                    string strpdf = "";

                    GdPictureStatus status = oGdPicturePDF.LoadFromFile(file, false);


                    if (status == GdPictureStatus.OK)
                    {
                        int      ident      = 1;
                        int      num1       = oGdPicturePDF.GetPageCount();
                        int      num4       = 1;
                        string[] mergeArray = new string[num1];
                        Directory.CreateDirectory(folderpdf);
                        if (num1 > 0)
                        {
                            bool flagpdf = true;

                            while (num4 <= num1)
                            {
                                oGdPicturePDF.SelectPage(num4);

                                int numpdf1 = oGdPicturePDF.RenderPageToGdPictureImage(300, true);

                                var docuemntoId = Guid.NewGuid();

                                string sstr = string.Concat(Ocr.GetCurrentDirectory(), "\\GdPicture\\Idiomas");

                                oGdPicturePDF.SaveToFile(folderpdf + @"\" + ident + "_" + docuemntoId + ".pdf");


                                var id = oGdPictureImaging.PdfOCRStart(folderpdf + @"\" + ident + "_" + docuemntoId + ".pdf", true, "", "", "", "", "");

                                oGdPictureImaging.PdfAddGdPictureImageToPdfOCR(id, numpdf1, "por", sstr, "");
                                oGdPictureImaging.PdfOCRStop(id);


                                mergeArray[num4 - 1] = folderpdf + @"\" + ident + "_" + docuemntoId + ".pdf";


                                if (oGdPicturePDF.GetStat() == 0)
                                {
                                    num4++;
                                    ident++;
                                }
                                else
                                {
                                    flagpdf = false;
                                    break;
                                }

                                oGdPictureImaging.ReleaseGdPictureImage(numpdf1);
                            }
                            oGdPicturePDF.CloseDocument();


                            if (flagpdf)
                            {
                                var strPdf1 = file.Replace(Path.GetExtension(file), ".pdf");
                                oGdPicturePDF.MergeDocuments(mergeArray, strPdf1);
                                strpdf = strPdf1;
                                oGdPicturePDF.CloseDocument();
                            }

                            oGdPictureImaging.ClearGdPicture();

                            string str1pdf = ConfigurationManager.AppSettings["PastaDestinoTemp"].ToString();
                            if (File.Exists(str1pdf + @"\" + Path.GetFileName(strpdf)))
                            {
                                File.Replace(strpdf, str1pdf + @"\" + Path.GetFileName(strpdf), null);
                            }
                            else
                            {
                                File.Move(strpdf, str1pdf + @"\" + Path.GetFileName(strpdf));
                            }

                            var filefinal = str1pdf + @"\" + Path.GetFileName(strpdf);
                            foreach (var item in Directory.GetFiles(folderpdf))
                            {
                                File.Delete(item);
                            }
                            Directory.Delete(folderpdf);
                            file = filefinal;
                        }
                        else
                        {
                            oGdPicturePDF.SelectPage(num4);
                            int    numpdf      = oGdPicturePDF.RenderPageToGdPictureImage(300, true);
                            var    docuemntoId = Guid.NewGuid();
                            string sstr        = string.Concat(Ocr.GetCurrentDirectory(), "\\GdPicture\\Idiomas");
                            oGdPictureImaging.SaveAsPDFOCR(numpdf, folderpdf + @"\" + docuemntoId + ".pdf", idioma, sstr, white, pdfa, titulo, autor, assunto, palavrasChaves, criador);


                            var strPdf = file.Replace(Path.GetExtension(file), ".pdf");
                            oGdPictureImaging.ReleaseGdPictureImage(numpdf);



                            oGdPicturePDF.MergeDocuments(System.IO.Directory.GetFiles(folderpdf), strPdf);
                            strpdf = strPdf;

                            oGdPictureImaging.ClearGdPicture();


                            string str1tif = ConfigurationManager.AppSettings["PastaDestinoTemp"].ToString();
                            if (File.Exists(str1tif + @"\" + Path.GetFileName(strpdf)))
                            {
                                File.Replace(strpdf, str1tif + @"\" + Path.GetFileName(strpdf), null);
                            }
                            else
                            {
                                File.Move(strpdf, str1tif + @"\" + Path.GetFileName(strpdf));
                            }

                            var filefinal = str1tif + @"\" + Path.GetFileName(strpdf);
                            foreach (var item in Directory.GetFiles(folderpdf))
                            {
                                File.Delete(item);
                            }
                            Directory.Delete(folderpdf);
                            file = filefinal;
                        }
                    }

                    #endregion
                    break;

                case (".TIF"):
                    String folder = Guid.NewGuid().ToString();

                    string str = "";
                    oGdPictureImaging.TiffOpenMultiPageForWrite(false);
                    int num = oGdPictureImaging.CreateGdPictureImageFromFile(file);
                    if (num != 0)
                    {
                        int ident = 1;
                        Directory.CreateDirectory(folder);

                        if (oGdPictureImaging.TiffIsMultiPage(num))
                        {
                            int      num1       = oGdPictureImaging.TiffGetPageCount(num);
                            bool     flag       = true;
                            int      num4       = 1;
                            string[] mergeArray = new string[num1];
                            while (num4 <= num1)
                            {
                                oGdPictureImaging.TiffSelectPage(num, num4);
                                // oGdPicturePDF.AddImageFromGdPictureImage(num, false, true);
                                oGdPicturePDF.NewPDF();
                                var docuemntoId = Guid.NewGuid();
                                oGdPicturePDF.SaveToFile(folder + @"\" + ident + "_" + docuemntoId + ".pdf");
                                var id = oGdPictureImaging.PdfOCRStart(folder + @"\" + ident + "_" + docuemntoId + ".pdf", true, "", "", "", "", "");

                                string sstr = string.Concat(Ocr.GetCurrentDirectory(), "\\GdPicture\\Idiomas");
                                oGdPictureImaging.PdfAddGdPictureImageToPdfOCR(id, num, "por", sstr, "");
                                oGdPictureImaging.PdfOCRStop(id);
                                //     oGdPictureImaging.SaveAsPDFOCR(num4, @"C:\Processamento" + @"\" + docuemntoId + ".pdf", idioma, sstr, "", true, titulo, autor, assunto, palavrasChaves, criador);

                                oGdPicturePDF.CloseDocument();
                                mergeArray[num4 - 1] = folder + @"\" + ident + "_" + docuemntoId + ".pdf";
                                if (oGdPicturePDF.GetStat() == 0)
                                {
                                    num4++;
                                    ident++;
                                }
                                else
                                {
                                    flag = false;
                                    break;
                                }
                                //      oGdPictureImaging.ReleaseGdPictureImage(num);
                            }


                            if (flag)
                            {
                                var strPdf = file.Replace(Path.GetExtension(file), ".pdf");

                                oGdPicturePDF.MergeDocuments(mergeArray, strPdf);
                                str = strPdf;
                            }

                            oGdPictureImaging.ReleaseGdPictureImage(num);
                            oGdPictureImaging.ClearGdPicture();

                            string str1tif = ConfigurationManager.AppSettings["PastaDestinoTemp"].ToString();
                            if (File.Exists(str1tif + @"\" + Path.GetFileName(str)))
                            {
                                File.Replace(str, str1tif + @"\" + Path.GetFileName(str), null);
                                File.Delete(file);
                            }
                            else
                            {
                                File.Move(str, str1tif + @"\" + Path.GetFileName(str));
                                File.Delete(file);
                            }

                            var filefinal = str1tif + @"\" + Path.GetFileName(str);
                            foreach (var item in Directory.GetFiles(folder))
                            {
                                File.Delete(item);
                            }
                            Directory.Delete(folder);
                            file = filefinal;
                        }
                        else
                        {
                            var    docuemntoId = Guid.NewGuid();
                            string sstr        = string.Concat(Ocr.GetCurrentDirectory(), "\\GdPicture\\Idiomas");

                            oGdPicturePDF.NewPDF();
                            oGdPicturePDF.SaveToFile(folder + @"\" + ident + "_" + docuemntoId + ".pdf");
                            var id = oGdPictureImaging.PdfOCRStart(folder + @"\" + ident + "_" + docuemntoId + ".pdf", true, "", "", "", "", "");
                            oGdPictureImaging.PdfAddGdPictureImageToPdfOCR(id, num, "por", sstr, "");
                            oGdPictureImaging.PdfOCRStop(id);
                            oGdPicturePDF.CloseDocument();

                            //oGdPictureImaging.SaveAsPDFOCR(num, folder + @"\" + docuemntoId + ".pdf", idioma, sstr, white, pdfa, titulo, autor, assunto, palavrasChaves, criador);


                            var strPdf = file.Replace(Path.GetExtension(file), ".pdf");

                            oGdPicturePDF.MergeDocuments(System.IO.Directory.GetFiles(folder), strPdf);

                            str = strPdf;

                            oGdPictureImaging.ReleaseGdPictureImage(num);
                            oGdPicturePDF.CloseDocument();

                            oGdPictureImaging.ClearGdPicture();
                            string str1tif = ConfigurationManager.AppSettings["PastaDestinoTemp"].ToString();
                            if (File.Exists(str1tif + @"\" + Path.GetFileName(str)))
                            {
                                File.Replace(str, str1tif + @"\" + Path.GetFileName(str), null);
                                File.Delete(file);
                            }
                            else
                            {
                                File.Move(str, str1tif + @"\" + Path.GetFileName(str));
                                File.Delete(file);
                            }

                            var filefinal = str1tif + @"\" + Path.GetFileName(str);
                            foreach (var item in Directory.GetFiles(folder))
                            {
                                File.Delete(item);
                            }
                            Directory.Delete(folder);
                            file = filefinal;
                        }
                    }

                    break;

                case ".TIFF":
                    String folder2 = Guid.NewGuid().ToString();

                    string str2 = "";
                    oGdPictureImaging.TiffOpenMultiPageForWrite(false);
                    int num2 = oGdPictureImaging.CreateGdPictureImageFromFile(file);
                    if (num2 != 0)
                    {
                        int ident = 1;

                        Directory.CreateDirectory(folder2);
                        if (oGdPictureImaging.TiffIsMultiPage(num2))
                        {
                            int      num1       = oGdPictureImaging.TiffGetPageCount(num2);
                            bool     flag       = true;
                            int      num3       = 1;
                            string[] mergeArray = new string[num1];
                            while (num3 <= num1)
                            {
                                oGdPictureImaging.TiffSelectPage(num2, num3);
                                oGdPicturePDF.NewPDF();
                                oGdPicturePDF.AddImageFromGdPictureImage(num2, false, true);

                                var docuemntoId = Guid.NewGuid();
                                // oGdPicturePDF.SaveToFile(folder + @"\" + docuemntoId + ".pdf");
                                oGdPicturePDF.SaveToFile(folder2 + @"\" + ident + "_" + docuemntoId + ".pdf");
                                //   var id = oGdPictureImaging.PdfOCRStart(folder + @"\" + docuemntoId + ".pdf", true, "", "", "", "", "");
                                //oGdPictureImaging.PdfAddGdPictureImageToPdfOCR(id, num, "por", str, "");
                                string sstr = string.Concat(Ocr.GetCurrentDirectory(), "\\GdPicture\\Idiomas");

                                var id = oGdPictureImaging.PdfOCRStart(folder2 + @"\" + ident + "_" + docuemntoId + ".pdf", true, "", "", "", "", "");
                                oGdPictureImaging.PdfAddGdPictureImageToPdfOCR(id, num2, "por", sstr, "");
                                oGdPictureImaging.PdfOCRStop(id);
                                oGdPicturePDF.CloseDocument();
                                //oGdPictureImaging.SaveAsPDFOCR(num3, folder2 + @"\" + docuemntoId + ".pdf", idioma, sstr, white, pdfa, titulo, autor, assunto, palavrasChaves, criador);
                                mergeArray[num3 - 1] = folder2 + @"\" + ident + "_" + docuemntoId + ".pdf";


                                if (oGdPicturePDF.GetStat() == 0)
                                {
                                    num3++;
                                    ident++;
                                }
                                else
                                {
                                    flag = false;
                                    break;
                                }
                                //oGdPictureImaging.ReleaseGdPictureImage(num2);
                            }

                            if (flag)
                            {
                                var strPdf = file.Replace(Path.GetExtension(file), ".pdf");

                                oGdPicturePDF.MergeDocuments(mergeArray, strPdf);
                                str2 = strPdf;
                            }
                            oGdPictureImaging.ReleaseGdPictureImage(num2);


                            oGdPictureImaging.ClearGdPicture();
                            string str1tiff = ConfigurationManager.AppSettings["PastaDestinoTemp"].ToString();
                            if (File.Exists(str1tiff + @"\" + Path.GetFileName(str2)))
                            {
                                File.Replace(str2, str1tiff + @"\" + Path.GetFileName(str2), null);
                                File.Delete(file);
                            }
                            else
                            {
                                File.Move(str2, str1tiff + @"\" + Path.GetFileName(str2));
                                File.Delete(file);
                            }

                            var filefinal2 = str1tiff + @"\" + Path.GetFileName(str2);
                            foreach (var item in Directory.GetFiles(folder2))
                            {
                                File.Delete(item);
                            }
                            Directory.Delete(folder2);
                            file = filefinal2;
                        }
                        else
                        {
                            var    docuemntoId = Guid.NewGuid();
                            string sstr        = string.Concat(Ocr.GetCurrentDirectory(), "\\GdPicture\\Idiomas");

                            oGdPicturePDF.NewPDF();
                            var id = oGdPictureImaging.PdfOCRStart(folder2 + @"\" + ident + "_" + docuemntoId + ".pdf", true, "", "", "", "", "");
                            oGdPicturePDF.SaveToFile(folder2 + @"\" + ident + "_" + docuemntoId + ".pdf");
                            oGdPictureImaging.PdfAddGdPictureImageToPdfOCR(id, num2, "por", sstr, "");
                            oGdPictureImaging.PdfOCRStop(id);
                            oGdPicturePDF.CloseDocument();

                            var strPdf = file.Replace(Path.GetExtension(file), ".pdf");

                            oGdPicturePDF.MergeDocuments(System.IO.Directory.GetFiles(folder2), strPdf);

                            str2 = strPdf;

                            oGdPictureImaging.ReleaseGdPictureImage(num2);
                            oGdPicturePDF.CloseDocument();

                            oGdPictureImaging.ClearGdPicture();
                            string str1tiff = ConfigurationManager.AppSettings["PastaDestinoTemp"].ToString();
                            if (File.Exists(str1tiff + @"\" + Path.GetFileName(str2)))
                            {
                                File.Replace(str2, str1tiff + @"\" + Path.GetFileName(str2), null);
                                File.Delete(file);
                            }
                            else
                            {
                                File.Move(str2, str1tiff + @"\" + Path.GetFileName(str2));
                                File.Delete(file);
                            }
                            var filefinal2 = str1tiff + @"\" + Path.GetFileName(str2);
                            foreach (var item in Directory.GetFiles(folder2))
                            {
                                File.Delete(item);
                            }
                            Directory.Delete(folder2);
                            file = filefinal2;
                        }
                    }

                    break;
                }
            }
            catch (Exception ex)
            {
                var logpath = ConfigurationManager.AppSettings["PastaDestinoLog"].ToString();
                File.AppendAllText(logpath + @"\" + "log.txt", ex.ToString());

                //  Console.WriteLine(ex.Message);
            }

            return(file);
        }
Exemple #22
0
        public ActionResult GalleryGetDocumentThumbnail(string doc)
        {
            const int THUMBNAIL_WIDTH          = 120;
            const int THUMBNAIL_HEIGHT         = 100;
            Color     thumbnailBackgroundColor = Color.Transparent;

            if (doc != null)
            {
                string docPath = MvcApplication.GetDocumentsDirectory() + "\\" + HttpUtility.UrlDecode(doc);

                string thumbPath = string.Empty;

                //thumbPath = MvcApplication.GetCacheDirectory() + "\\" + "DOCX.thumb";

                GdPicture14.DocumentFormat documentFormat = new GdPicture14.DocumentFormat();

                switch (Path.GetExtension(doc).ToUpper())
                {
                case ".PDF":
                    thumbPath = MvcApplication.GetCacheDirectory() + "\\" + "PDF.thumb";
                    break;

                case ".JPEG":
                    thumbPath = MvcApplication.GetCacheDirectory() + "\\" + "JPEG.thumb";
                    break;

                case ".DOCX":
                    thumbPath = MvcApplication.GetCacheDirectory() + "\\" + "DOCX.thumb";
                    break;

                case ".XLSX":
                    thumbPath = MvcApplication.GetCacheDirectory() + "\\" + "XLSX.thumb";
                    break;

                default:
                    thumbPath = MvcApplication.GetCacheDirectory() + "\\" + "PDF.thumb";
                    break;
                }


                if (System.IO.File.Exists(thumbPath))
                {
                    byte[] content = null;
                    // getting thumbnail from cache
                    try
                    {
                        using (FileStream fileStream = new FileStream(thumbPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            content = new byte[fileStream.Length];
                            fileStream.Read(content, 0, (int)fileStream.Length); // safe cast as thumbnail size will never exceed int.maxValue
                        }
                    }
                    catch // can fail during first concurrent accesses.
                    {
                        goto gen_thumb;
                    }
                    return(File(content, "image/png"));
                }

gen_thumb:
                // GdPicture14.DocumentFormat documentFormat = GdPicture14.DocumentFormat.DocumentFormatUNKNOWN;

                // GdPicture14.DocumentFormat documentFormat = GdPicture14.DocumentFormat.DocumentFormatDOCX;// h.GetExtension(doc);
                int thumbnailId = 0;
                int             pageCount = 0;
                GdPictureStatus status    = GdPictureDocumentUtilities.GetDocumentPreview(docPath, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT, thumbnailBackgroundColor.ToArgb(), ref documentFormat, ref thumbnailId, ref pageCount);
                if (status == GdPictureStatus.OK)
                {
                    using (GdPictureImaging gdpictureImaging = new GdPictureImaging())
                    {
                        using (MemoryStream memoryStream = new MemoryStream())
                        {
                            try
                            {
                                if (gdpictureImaging.SaveAsStream(thumbnailId, memoryStream, GdPicture14.DocumentFormat.DocumentFormatTXT, 6) == GdPictureStatus.OK)
                                {
                                    byte[] content = memoryStream.ToArray();
                                    // let's cache result
                                    using (FileStream fileStream = new FileStream(thumbPath, FileMode.CreateNew, FileAccess.Write, FileShare.None))
                                    {
                                        fileStream.Write(content, 0, content.Length);
                                    }
                                }
                            }
                            finally
                            {
                                GdPictureDocumentUtilities.DisposeImage(thumbnailId);
                            }
                        }
                    }
                }
            }
            return(null);
        }
Exemple #23
0
        /// <summary>
        /// WriteAnnotations writes the pdf to a file including its annotations.
        /// </summary>
        /// <param name="strOutputFilePath">The path to the output file.</param>
        /// <param name="errorMessage">Used to retrieve an error message.</param>
        /// <param name="stream">The stream containing the PDF.</param>
        /// <param name="pageCount">The number of pages.</param>
        /// <param name="pageInfo">The page information.</param>
        /// <param name="textExtension">The extension for the text file.</param>
        /// <returns>true if the conversion succeded otherwise returns false.</returns>
        private static bool WriteAnnotations(string strOutputFilePath, ref string errorMessage, MemoryStream stream,
                                             int pageCount,
                                             PageInfo[] pageInfo, string textExtension)
        {
            using (AnnotationManager annotationManager = new AnnotationManager())
            {
                // Load the pdf from the stream

                GdPictureStatus status = annotationManager.InitFromStream(stream);
                if (status != GdPictureStatus.OK)
                {
                    errorMessage = annotationManager.GetStat().ToString();
                    return(false);
                }

                // Write the annotation from the pages

                for (int pageIndex = 0; pageIndex < pageCount; pageIndex++)
                {
                    if (pageInfo[pageIndex].WangTagData != null)
                    {
                        annotationManager.SelectPage(pageIndex + 1);
                        bool wangAnnotationsReadingSuccess;
                        if (textExtension == "")
                        {
                            WangTiffToPdfWangAnnotationHandler handler =
                                new WangTiffToPdfWangAnnotationHandler(pageInfo[pageIndex].WidthPixels,
                                                                       pageInfo[pageIndex].HeightPixels, pageInfo[pageIndex].WidthInches,
                                                                       pageInfo[pageIndex].HeightInches, annotationManager, null);
                            wangAnnotationsReadingSuccess = WangTagReadingLibrary.WangAnnotationsReader.Read(handler,
                                                                                                             pageInfo[pageIndex].WangTagData);
                        }
                        else
                        {
                            using (
                                StreamWriter textWriter =
                                    new StreamWriter(strOutputFilePath + "." + pageIndex + textExtension))
                            {
                                WangTiffToPdfWangAnnotationHandler handler =
                                    new WangTiffToPdfWangAnnotationHandler(pageInfo[pageIndex].WidthPixels,
                                                                           pageInfo[pageIndex].HeightPixels, pageInfo[pageIndex].WidthInches,
                                                                           pageInfo[pageIndex].HeightInches, annotationManager, textWriter);
                                wangAnnotationsReadingSuccess = WangTagReadingLibrary.WangAnnotationsReader.Read(
                                    handler,
                                    pageInfo[pageIndex].WangTagData);
                            }
                        }

                        status = wangAnnotationsReadingSuccess
                            ? annotationManager.BurnAnnotationsToPage(true)
                            : GdPictureStatus.GenericError;

                        if (status != GdPictureStatus.OK)
                        {
                            annotationManager.Close();
                            errorMessage = wangAnnotationsReadingSuccess
                                ? annotationManager.GetStat().ToString()
                                : "An error occurred while reading Wang annotations.";
                            return(false);
                        }
                    }
                }

                // Writes the pdf as a file

                status = annotationManager.SaveDocumentToPDF(strOutputFilePath);
                if (status != GdPictureStatus.OK)
                {
                    errorMessage = annotationManager.GetStat().ToString();
                    return(false);
                }
                annotationManager.Close();
            }
            return(true);
        }
        private static void Dispatcher(object sender, CustomActionEventArgs e)
        {
            GdPicturePDF oPdf = new GdPicturePDF();

            switch (e.actionName)
            {
            //loading document and setting annotations access control
            //the workflow is designed for PDF files, you can apply similar workflow on the other formats using GdPictureImaging class
            case "load":
                load              oLoad              = JsonConvert.DeserializeObject <load>(e.args.ToString());
                GdPictureStatus   status             = oPdf.LoadFromFile(HttpRuntime.AppDomainAppPath + "\\Files\\" + oLoad.Path, true);
                AnnotationManager oAnnotationmanager = new AnnotationManager();
                oAnnotationmanager.InitFromGdPicturePDF(oPdf);
                for (int i = 1; i < oAnnotationmanager.PageCount; i++)
                {
                    oAnnotationmanager.SelectPage(i);
                    for (int y = 0; y < oAnnotationmanager.GetAnnotationCount(); y++)
                    {
                        Annotation annot = oAnnotationmanager.GetAnnotationFromIdx(y);
                        if (oLoad.UserType == "user")        //case for external user member
                        {
                            if (annot.Tag != oLoad.UserType) //annotation is not vissible if not added by external group memebr
                            {
                                annot.Visible = false;
                            }
                        }
                        else if (oLoad.UserType == "staff") //case for staff member
                        {
                            annot.Visible = true;           //all annot are visible
                        }
                    }
                    oAnnotationmanager.SaveAnnotationsToPage();
                }
                e.docuVieware.LoadFromGdPicturePdf(oPdf);
                e.docuVieware.DisplayPage(1);

                break;


            //setting annotation tag that represents access group and saving annotation to PDF
            //the workflow is designed for PDF files, you can apply similar workflow on the other formats using GdPictureImaging class

            case "setAnnotationTag":

                e.docuVieware.GetNativePDF(out oPdf);
                AnnotationManager manager = new AnnotationManager();
                manager.InitFromGdPicturePDF(oPdf);

                details oDetails = JsonConvert.DeserializeObject <details>(e.args.ToString());
                manager.SelectPage(oDetails.annot.pageNo);
                int pages = manager.GetAnnotationCount();
                for (int i = 0; i < pages; i++)
                {
                    Annotation oAnnotation = manager.GetAnnotationFromIdx(i);
                    if (oAnnotation.Guid == oDetails.annot.id)
                    {
                        oAnnotation.Tag = oDetails.type;
                    }
                }
                manager.SaveAnnotationsToPage();

                status = oPdf.SaveToFile(HttpRuntime.AppDomainAppPath + "\\Files\\DocuViewareFlyer.pdf", true);


                break;
            }
        }
Exemple #25
0
        public static string CastToPDF(string pathFile, bool pdfa = true, string idioma = "por", string white = null, string titulo = null, string autor = null, string assunto = null, string palavrasChaves = null, string criador = null, int dpi = 250)//
        {
            string pathFileFinal = "";
            string folderpdf     = Path.Combine(pathDestinyTemporary, Guid.NewGuid().ToString());

            try
            {
                oGdPicturePDF.SetLicenseNumber("4118106456693265856441854");
                oGdPictureImaging.SetLicenseNumber("4118106456693265856441854");

                #region .: PDF :.

                string strpdf = "";

                GdPictureStatus status = oGdPicturePDF.LoadFromFile(pathFile, false);

                if (status == GdPictureStatus.OK)
                {
                    oGdPicturePDF.EnableCompression(true);
                    int      ident      = 1;
                    int      num1       = oGdPicturePDF.GetPageCount();
                    int      num4       = 1;
                    string[] mergeArray = new string[num1];
                    Directory.CreateDirectory(folderpdf);
                    if (num1 > 0)
                    {
                        bool flagpdf = true;

                        while (num4 <= num1)
                        {
                            oGdPicturePDF.SelectPage(num4);

                            int numpdf1 = oGdPicturePDF.RenderPageToGdPictureImage(300, true);//here

                            var docuemntoId = Guid.NewGuid();

                            string sstr = Path.Combine(Gdpicture.GetCurrentDirectory(), "GdPicture\\Idiomas");

                            status = oGdPicturePDF.SaveToFile(folderpdf + "\\compressed_pack.pdf", true);
                            oGdPicturePDF.SaveToFile(folderpdf + "\\" + ident + "_" + docuemntoId + ".pdf", true);

                            var id = oGdPictureImaging.PdfOCRStart(folderpdf + "\\" + ident + "_" + docuemntoId + ".pdf", true, "", "", "", "", "");

                            oGdPictureImaging.PdfAddGdPictureImageToPdfOCR(id, numpdf1, "por", sstr, "");
                            oGdPictureImaging.PdfOCRStop(id);

                            mergeArray[num4 - 1] = folderpdf + "\\" + ident + "_" + docuemntoId + ".pdf"; //

                            if (oGdPicturePDF.GetStat() == 0)
                            {
                                num4++;
                                ident++;
                            }
                            else
                            {
                                flagpdf = false;
                                break;
                            }

                            oGdPictureImaging.ReleaseGdPictureImage(numpdf1);
                        }

                        oGdPicturePDF.CloseDocument();

                        if (flagpdf)
                        {
                            var strPdf1 = pathFile.Replace(Path.GetExtension(pathFile), ".pdf");
                            oGdPicturePDF.MergeDocuments(mergeArray, strPdf1);
                            strpdf = strPdf1;
                            oGdPicturePDF.CloseDocument();
                        }

                        oGdPictureImaging.ClearGdPicture();

                        if (File.Exists(pathDestinyTemporary + "\\" + Path.GetFileName(strpdf)))
                        {
                            File.Replace(strpdf, pathDestinyTemporary + "\\" + Path.GetFileName(strpdf), null);
                        }
                        else
                        {
                            File.Move(strpdf, pathDestinyTemporary + "\\" + Path.GetFileName(strpdf));
                        }

                        pathFileFinal = pathDestinyTemporary + "\\" + Path.GetFileName(strpdf);
                        foreach (var item in Directory.GetFiles(folderpdf))
                        {
                            File.Delete(item);
                        }
                        Directory.Delete(folderpdf);
                    }
                    else
                    {
                        oGdPicturePDF.SelectPage(num4);
                        int    numpdf      = oGdPicturePDF.RenderPageToGdPictureImage(300, true); //here
                        var    docuemntoId = Guid.NewGuid();
                        string sstr        = string.Concat(Gdpicture.GetCurrentDirectory(), "\\GdPicture\\Idiomas");
                        oGdPictureImaging.SaveAsPDFOCR(numpdf, folderpdf + "\\" + docuemntoId + ".pdf", idioma, sstr, white, pdfa, titulo, autor, assunto, palavrasChaves, criador);

                        var strPdf = pathFile.Replace(Path.GetExtension(pathFile), ".pdf");
                        oGdPictureImaging.ReleaseGdPictureImage(numpdf);

                        oGdPicturePDF.MergeDocuments(System.IO.Directory.GetFiles(folderpdf), strPdf);
                        strpdf = strPdf;

                        oGdPictureImaging.ClearGdPicture();

                        if (File.Exists(pathDestinyTemporary + "\\" + Path.GetFileName(strpdf)))
                        {
                            File.Replace(strpdf, pathDestinyTemporary + "\\" + Path.GetFileName(strpdf), null);
                        }
                        else
                        {
                            File.Move(strpdf, pathDestinyTemporary + "\\" + Path.GetFileName(strpdf));
                        }

                        pathFileFinal = pathDestinyTemporary + "\\" + Path.GetFileName(strpdf);
                        foreach (var item in Directory.GetFiles(folderpdf))
                        {
                            File.Delete(item);
                        }
                        Directory.Delete(folderpdf);
                    }
                }

                #endregion
            }
            catch (Exception ex)
            {
                if (Directory.Exists(folderpdf))
                {
                    foreach (var item in Directory.GetFiles(folderpdf))
                    {
                        File.Delete(item);
                    }
                    Directory.Delete(folderpdf);
                }

                throw ex;
            }

            return(pathFileFinal);
        }
Exemple #26
0
        /*
         * /// <summary>
         * ///
         * /// </summary>
         * /// <param name="e"></param>
         * public static void HandleSaveFile(CustomActionEventArgs customActionEventArgs)
         * {
         *
         *  DocumentType docType = customActionEventArgs.docuVieware.GetDocumentType();
         *  if (docType == DocumentType.DocumentTypeTXT)
         *  {
         *      MemoryStream memStream = null;
         *      GdPictureStatus status;
         *
         *      status = customActionEventArgs.docuVieware.GetDocumentData(out memStream);
         *
         *      if (status == GdPictureStatus.OK)
         *      {
         *          string nm = customActionEventArgs.docuVieware.GetDocumentName();
         *          int indexOf = nm.IndexOf('.');
         *          if (indexOf > 0)
         *              nm = nm.Substring(0, indexOf);
         *
         *          nm = nm + ".tiff";
         *          string fileName = HttpRuntime.AppDomainAppPath + "\\" + nm;
         *          FileStream fs = new FileStream(fileName, FileMode.CreateNew, FileAccess.ReadWrite);
         *          fs.Write(memStream.GetBuffer(), 0, (int)memStream.Length);
         *          customActionEventArgs.docuVieware.SaveAsTIFF(memStream);
         *
         *          fs = null;
         *      } else
         *      {
         *          customActionEventArgs.message = GetMessage("Save : Fail to get Stream data.", DocuViewareMessageIcon.Error);
         *      }
         *
         *      memStream = null;
         *  }
         * }
         */

        /// <summary>
        /// Triggers when user clicks on Rotate -90 or Rotate +90. Rotates the image file as per the request.
        /// </summary>
        /// <remarks>
        /// Only image file formats can be Rotated. Shows error message if File is not Supported, File is not of proper format,
        /// Cannot select Page, Failed to Rotate the file contents.
        /// </remarks>
        /// <param name="e">The CustomActionEventArgs received from the Global.asax.cs custom actions handler</param>
        public static void HandleRotationAction(CustomActionEventArgs e)
        {
            GdPictureStatus status = GdPictureStatus.Aborted;

            // For Images
            if (e.docuVieware.GetDocumentType() == DocumentType.DocumentTypeBitmap)
            {
                int imageId;
                status = e.docuVieware.GetNativeImage(out imageId);
                if (status == GdPictureStatus.OK)
                {
                    GdPictureImaging       gdPictureImaging = new GdPictureImaging();
                    RotateActionParameters rotateParams     = JsonConvert.DeserializeObject <RotateActionParameters>(e.args.ToString());

                    int currPage = rotateParams.CurrentPage;
                    status = gdPictureImaging.SelectPage(imageId, currPage);    //  rotateParams.CurrentPage);
                    if (status == GdPictureStatus.OK)
                    {
                        switch (e.actionName)
                        {
                        case "rotateM90":
                            status = gdPictureImaging.Rotate(imageId, RotateFlipType.Rotate270FlipNone);
                            break;

                        case "rotateP90":
                            status = gdPictureImaging.Rotate(imageId, RotateFlipType.Rotate90FlipNone);
                            break;
                        }
                        if (status != GdPictureStatus.OK)
                        {
                            e.message = new DocuViewareMessage("Error during rotating: " + status + ".", icon: DocuViewareMessageIcon.Error);
                        }
                        else
                        {
                            status    = e.docuVieware.RedrawPage();
                            e.message = status == GdPictureStatus.OK ? new DocuViewareMessage("Rotation successfuly applied.", icon: DocuViewareMessageIcon.Ok) : new DocuViewareMessage("Error during redraw pages : " + status + ".", icon: DocuViewareMessageIcon.Error);
                        }
                    }
                    else
                    {
                        e.message = new DocuViewareMessage("Error during page selection: " + status + ".", icon: DocuViewareMessageIcon.Error);
                    }

                    rotateParams     = null;
                    gdPictureImaging = null;
                }
                else
                {
                    e.message = new DocuViewareMessage("Error during get native image : " + status + ".", icon: DocuViewareMessageIcon.Error);
                }
            }
            else if (e.docuVieware.GetDocumentType() == DocumentType.DocumentTypePDF)
            {
                GdPicturePDF gdPdf = null;
                if (e.docuVieware.GetNativePDF(out gdPdf) == GdPictureStatus.OK)
                {
                    RotateActionParameters rotateParams = JsonConvert.DeserializeObject <RotateActionParameters>(e.args.ToString());

                    int currPage = rotateParams.CurrentPage;
                    gdPdf.SelectPage(currPage);
                    switch (e.actionName)
                    {
                    case "rotateM90":
                        status = gdPdf.RotatePage(-90);
                        break;

                    case "rotateP90":
                        status = gdPdf.RotatePage(90);
                        break;
                    }
                    if (status != GdPictureStatus.OK)
                    {
                        e.message = GetMessage("Error during rotating: " + status + ".", DocuViewareMessageIcon.Error);
                    }
                    else
                    {
                        status    = e.docuVieware.RedrawPage();
                        e.message = status == GdPictureStatus.OK ? GetMessage("Rotation successfuly applied.", DocuViewareMessageIcon.Ok) : GetMessage("Error during redraw pages : " + status + ".", DocuViewareMessageIcon.Error);
                    }

                    rotateParams = null;
                    gdPdf        = null;
                }
                else
                {
                    e.message = GetMessage("Error during get native image : " + status + ".", DocuViewareMessageIcon.Error);
                }
            }
            else
            {
                e.message = GetMessage("Only Images & PDF formats Rotation supported", DocuViewareMessageIcon.Error);
            }



            return;
        }
Exemple #27
0
        /// <summary>
        /// Handles Image Cleaup Actions
        /// </summary>
        /// <param name="e"></param>
        public static void HandleImageCleanupAction(CustomActionEventArgs e)
        {
            if (e.docuVieware.PageCount > 0)
            {
                if (e.docuVieware.GetDocumentType() == DocumentType.DocumentTypeBitmap)
                {
                    int             imageId;
                    GdPictureStatus status = e.docuVieware.GetNativeImage(out imageId);
                    if (status == GdPictureStatus.OK)
                    {
                        status = GdPictureStatus.GenericError;
                        using (GdPictureImaging gdPictImg = new GdPictureImaging())
                        {
                            RotateActionParameters parameters = JsonConvert.DeserializeObject <RotateActionParameters>(e.args.ToString());
                            if (parameters.RegionOfInterest != null && parameters.RegionOfInterest.Width > 0 && parameters.RegionOfInterest.Height > 0)
                            {
                                gdPictImg.SetROI((int)Math.Round(parameters.RegionOfInterest.Left * gdPictImg.GetHorizontalResolution(imageId), 0),
                                                 (int)Math.Round(parameters.RegionOfInterest.Top * gdPictImg.GetVerticalResolution(imageId), 0),
                                                 (int)Math.Round(parameters.RegionOfInterest.Width * gdPictImg.GetHorizontalResolution(imageId), 0),
                                                 (int)Math.Round(parameters.RegionOfInterest.Height * gdPictImg.GetVerticalResolution(imageId), 0));
                            }
                            if (e.actionName != "punchHoleRemoval" || (e.actionName == "punchHoleRemoval" && gdPictImg.GetBitDepth(imageId) == 1))
                            {
                                foreach (var page in parameters.Pages)
                                {
                                    status = gdPictImg.SelectPage(imageId, page);
                                    if (status == GdPictureStatus.OK)
                                    {
                                        switch (e.actionName)
                                        {
                                        case "automaticRemoveBlackBorders":
                                            status = gdPictImg.DeleteBlackBorders(imageId, 10, false);
                                            break;

                                        case "autoDeskew":
                                            status = gdPictImg.AutoDeskew(imageId);
                                            break;

                                        case "punchHoleRemoval":
                                            status = gdPictImg.RemoveHolePunch(imageId, HolePunchMargins.MarginLeft | HolePunchMargins.MarginRight | HolePunchMargins.MarginBottom | HolePunchMargins.MarginTop);
                                            break;

                                        case "despeckle":
                                            status = gdPictImg.FxDespeckle(imageId);
                                            break;
                                        }

                                        if (status != GdPictureStatus.OK)
                                        {
                                            e.message = GetMessage("Error during apply filter: " + status + " on page " + page, DocuViewareMessageIcon.Error);
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        e.message = GetMessage("Error during page selectionr: " + status + "." + page, DocuViewareMessageIcon.Error);
                                        break;
                                    }
                                }   // foreach
                                if (status == GdPictureStatus.OK)
                                {
                                    status    = e.docuVieware.RedrawPages(parameters.Pages);
                                    e.message = status == GdPictureStatus.OK ? new DocuViewareMessage("Filter successfuly applied.", icon: DocuViewareMessageIcon.Ok) : GetMessage("Error during redraw pages : " + status + ".", DocuViewareMessageIcon.Error);
                                }
                            }
                            else
                            {
                                e.message = GetMessage("Your image must be 1 bit-depth to apply this filter!", DocuViewareMessageIcon.Error);
                            }
                        }   // using
                    }
                    else
                    {
                        e.message = GetMessage("Error during get native image : " + status + ".", DocuViewareMessageIcon.Error);
                    }
                }
                else
                {
                    e.message = GetMessage("Only raster formats are supported!", DocuViewareMessageIcon.Error);
                }
            }
            else
            {
                e.message = GetMessage("Please open an image first." + ".", DocuViewareMessageIcon.Error);
            }

            return;
        }
Exemple #28
0
        public byte[] Convert(byte[] data, bool embeddOCRText = true, string language = "deu")
        {
            byte[] pdf = null;

            using (var pdfInstance = GdPictureHelper.GetPDFInstance())
            {
                using (var gdPictureImaging = GdPictureHelper.GetImagingInstance())
                {
                    int imageId = gdPictureImaging.CreateGdPictureImageFromByteArray(data);
                    if (gdPictureImaging.GetStat() == GdPictureStatus.OK)
                    {
                        float           resolution = System.Math.Max(200, gdPictureImaging.GetVerticalResolution(imageId));
                        GdPictureStatus state      = GdPictureStatus.OK;

                        if (embeddOCRText)
                        {
                            state = pdfInstance.NewPDF(PdfConformance.PDF_A_1a);
                        }
                        else
                        {
                            state = pdfInstance.NewPDF();
                        }

                        if (state == GdPictureStatus.OK)
                        {
                            for (int i = 1; i <= gdPictureImaging.GetPageCount(imageId); i++)
                            {
                                if (gdPictureImaging.SelectPage(imageId, i) == GdPictureStatus.OK)
                                {
                                    var addImageResult = pdfInstance.AddImageFromGdPictureImage(imageId, false, true);
                                }
                            }

                            // pdfInstance.OcrPages("*", 1, language, GdPictureHelper.OCRDirectory, "", resolution, 0, true);

                            using (var stream = new MemoryStream())
                            {
                                pdfInstance.SaveToStream(stream);
                                stream.Position = 0;
                                pdf             = stream.ToArray();
                            }
                        }
                        else
                        {
                            throw new Exception($"Culd not convert document. State: {state}");
                        }

                        // Release gdpicture image
                        gdPictureImaging.ReleaseGdPictureImage(imageId);
                    }
                    else
                    {
                        throw new Exception("Could not create gdpicture imaging instance");
                    }

                    // Close pdf document
                    pdfInstance?.CloseDocument();
                }
            }

            return(pdf);
        }