Example #1
0
            public static Bitmap ResizeImage(System.Drawing.Image image, decimal percentage)
            {
                int width  = (int)Math.Round(image.Width * percentage, MidpointRounding.AwayFromZero);
                int height = (int)Math.Round(image.Height * percentage, MidpointRounding.AwayFromZero);

                return(ResizeImage(image, width, height));
            }
Example #2
0
        public static byte[] imageToByteArray(System.Drawing.Image image)
        {
            ImageConverter converter = new ImageConverter();

            byte[] imgArray = (byte[])converter.ConvertTo(image, typeof(byte[]));
            return(imgArray);
        }
Example #3
0
 private static byte[] ToByteArray(this System.Drawing.Image image, ImageFormat format)
 {
     using (MemoryStream ms = new MemoryStream())
     {
         image.Save(ms, format);
         return(ms.ToArray());
     }
 }
Example #4
0
        /// <summary>
        /// Vykreslování čísla na podklad
        /// </summary>
        /// <param name="aNumber">Číslo, které se má na obrázek vložit</param>
        /// <param name="aImage">Obrázek (podklad) na který se vkládá</param>
        /// <param name="aXMove">Počet pixelů o které se má číslo na obrázku posunout v ose X</param>
        /// <param name="aYMove">Počet pixelů o které se má číslo na obrázku posunout v ose Y</param>
        /// <param name="aFont">Font v jakém má číslo být napsáno</param>
        private void DrawNumber(decimal aNumber, ref System.Drawing.Image aImage, int aXMove, int aYMove, Font aFont)
        {
            var lGraphics = Graphics.FromImage(aImage);

            TextRenderer.DrawText(lGraphics,
                                  aNumber.ToString("000"),
                                  aFont,
                                  new Point(aXMove, aYMove), //new Point(1502, 30),
                                  Color.Black);
        }
        void WriteGraph(Document doc, System.Drawing.Image bmp, INode <string> start, INode <string> goal)
        {
            doc.Add(new Paragraph(new Chunk("The Graph", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 24, iTextSharp.text.Font.ITALIC, iTextSharp.text.BaseColor.BLACK))));
            // add graph image
            AddImage(doc, bmp);

            doc.Add(new Paragraph(new Chunk($"We will perform a search for {goal} starting from {start} node.", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.ITALIC, iTextSharp.text.BaseColor.BLACK))));
            doc.Add(new Paragraph(new Chunk("We will use various search algorithms such as (BFS, DFS, UCS, IDLS, Greedy, A*, IDA*).", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.ITALIC, iTextSharp.text.BaseColor.BLACK))));
            doc.Add(new Paragraph(new Chunk("This report will include Algorithms benchmarks and resolution steps, by illustrating each step performed by the search algorithms.", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.ITALIC, iTextSharp.text.BaseColor.BLACK))));
        }
Example #6
0
 private void SaveThumbnail(System.Drawing.Image original, SizeF newSize, string thumbnailFilename)
 {
     using (MemoryStream imageout = new MemoryStream())
     {
         var thumb = original.GetThumbnailImage((int)newSize.Width, (int)newSize.Height, () => false,
                                                IntPtr.Zero);
         thumb.Save(imageout, ImageFormat.Png);
         _storage.Store(thumbnailFilename, imageout.ToArray(), true);
     }
 }
Example #7
0
        public static void ExtractImagesFromPDF(string sourcePdf, string outputPath)
        {
            // NOTE:  This will only get the first image it finds per page.
            PdfReader pdf = new PdfReader(sourcePdf);

            //RandomAccessFileOrArray raf = new iTextSharp.text.pdf.RandomAccessFileOrArray(sourcePdf);

            try
            {
                for (int pageNumber = 1; pageNumber <= pdf.NumberOfPages; pageNumber++)
                {
                    PdfDictionary pg = pdf.GetPageN(pageNumber);

                    // recursively search pages, forms and groups for images.
                    PdfObject obj = FindImageInPDFDictionary(pg);
                    if (obj != null)
                    {
                        int       XrefIndex = Convert.ToInt32(((PRIndirectReference)obj).Number.ToString(System.Globalization.CultureInfo.InvariantCulture));
                        PdfObject pdfObj    = pdf.GetPdfObject(XrefIndex);
                        PdfStream pdfStrem  = (PdfStream)pdfObj;
                        byte[]    bytes     = PdfReader.GetStreamBytesRaw((PRStream)pdfStrem);
                        if ((bytes != null))
                        {
                            using (System.IO.MemoryStream memStream = new System.IO.MemoryStream(bytes))
                            {
                                memStream.Position = 0;
                                System.Drawing.Image img = ImageHelper.ResizeImage(System.Drawing.Image.FromStream(memStream), .33M);
                                // must save the file while stream is open.
                                if (!Directory.Exists(outputPath))
                                {
                                    Directory.CreateDirectory(outputPath);
                                }

                                string path = Path.Combine(outputPath, String.Format(@"{0}.jpg", pageNumber));
                                System.Drawing.Imaging.EncoderParameters parms = new System.Drawing.Imaging.EncoderParameters(1);
                                parms.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 0);
                                var encoders = ImageCodecInfo.GetImageEncoders();
                                System.Drawing.Imaging.ImageCodecInfo jpegEncoder = encoders.FirstOrDefault(p => p.CodecName == "Built-in JPEG Codec");
                                img.Save(path, jpegEncoder, parms);
                            }
                        }
                    }
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                pdf.Close();
                //raf.Close();
            }
        }
        void AddImage(Document doc, System.Drawing.Image bmp)
        {
            Image logo = Image.GetInstance(bmp, System.Drawing.Imaging.ImageFormat.Bmp);

            //Resize image depend upon your need
            logo.ScaleToFit(doc.PageSize.Width * 0.8f, doc.PageSize.Height * 0.6f);
            //Give space before image
            logo.SpacingBefore = 20f;
            //Give some space after the image
            logo.SpacingAfter = 1f;
            logo.Alignment    = Element.ALIGN_CENTER;
            doc.Add(logo);
        }
Example #9
0
        public Image GenerateQRCode(string data)
        {
            MyBarcodeQRCode qrcode = new MyBarcodeQRCode(data, 100, 100, null);

            System.Drawing.Image qrOriginalImage = qrcode.GetImage();
            System.Drawing.Image img2            = ImageUtil.CropUnwantedBackground(new Bitmap(qrOriginalImage));
            Image newQrCodeImage = Image.GetInstance(imageToByteArray(img2));

            newQrCodeImage.ScaleAbsoluteWidth(UNIT * 2.88854286f);
            newQrCodeImage.ScaleAbsoluteHeight(UNIT * 2.88854286f);
            newQrCodeImage.IndentationLeft = 80f;
            return(newQrCodeImage);
        }
Example #10
0
        /// <summary>
        /// Converts the specified html documents to a single image.
        /// </summary>
        /// <param name="htmlDocuments"></param>
        /// <param name="pdfConverterLicenseKey"></param>
        /// <returns></returns>
        public static System.Drawing.Image ConvertHtmlToImage(IEnumerable <string> htmlDocuments, string pdfConverterLicenseKey)
        {
            var imgConverter = new ImgConverter();

            if (String.IsNullOrEmpty(pdfConverterLicenseKey) == false)
            {
                imgConverter.LicenseKey = pdfConverterLicenseKey;
            }

            System.Drawing.Image img = null;
            foreach (var htmlDocument in htmlDocuments)
            {
                if (img == null)
                {
                    img = imgConverter.GetImageFromHtmlString(htmlDocument, ImageFormat.Png);
                }
                else
                {
                    using (System.Drawing.Image tempImage = imgConverter.GetImageFromHtmlString(htmlDocument, ImageFormat.Png))
                    {
                        int newImageHeight = img.Height + tempImage.Height;
                        int newImageWidth  = img.Width > tempImage.Width ? img.Width : tempImage.Width;

                        Bitmap newBitmap = new Bitmap(newImageWidth, newImageHeight);
                        using (Graphics newImageGraphics = Graphics.FromImage(newBitmap))
                        {
                            newImageGraphics.DrawImageUnscaled(img, 0, 0);
                            newImageGraphics.DrawImageUnscaled(tempImage, 0, newImageHeight);
                        }
                        img.Dispose();
                        img = newBitmap;
                    }
                }
            }

            if (img != null)
            {
                return(img);
            }

            throw new InvalidOperationException("No image object was created.");
        }
Example #11
0
        /// <summary>
        /// Returns a high quality shrunken image from the supplied <paramref name="image"/> using the requested <paramref name="scaleFactor">scale factor</paramref>.
        /// </summary>
        /// <param name="image">The image to shrink.</param>
        /// <param name="scaleFactor">The scale factor to use.</param>
        /// <returns>The shrunken image.</returns>
        private static System.Drawing.Image ShrinkImage(System.Drawing.Image image, float scaleFactor)
        {
            // http://weblogs.asp.net/gunnarpeipman/archive/2009/04/02/resizing-images-without-loss-of-quality.aspx

            var width  = Convert.ToInt32(image.Width * scaleFactor);
            var height = Convert.ToInt32(image.Height * scaleFactor);

            var shrinkImage = new Bitmap(width, height);

            using (var graphics = Graphics.FromImage(shrinkImage))
            {
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.SmoothingMode      = SmoothingMode.HighQuality;
                graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;

                var rectangle = new System.Drawing.Rectangle(0, 0, width, height);
                graphics.DrawImage(image, rectangle);
            }
            return(shrinkImage);
        }
Example #12
0
        public static void AddWatermarkImage(string filename)
        {
            string text = "SỞ LAO ĐỘNG THƯƠNG BINH VÀ XÃ HỘI HẢI DƯƠNG";

            System.Drawing.Font font = new System.Drawing.Font("Arial", 20, FontStyle.Regular);

            System.Drawing.Image image = (System.Drawing.Image)Bitmap.FromFile(filename);
            using (Graphics g = Graphics.FromImage(image))
            {
                g.TranslateTransform(image.Width / 2, image.Height / 2);
                g.RotateTransform(45);
                SizeF textSize = g.MeasureString(text, font);
                g.DrawString(text, font, Brushes.Chocolate, -(textSize.Width / 2), -(textSize.Height / 2));
            }
            MemoryStream m = new MemoryStream();

            image.Save(m, ImageFormat.Jpeg);
            image.Dispose();
            byte[] convertedToBytes = m.ToArray();
            File.WriteAllBytes(filename, convertedToBytes);
        }
Example #13
0
            /// <summary>
            /// Resize the image to the specified width and height.
            /// </summary>
            /// <param name="image">The image to resize.</param>
            /// <param name="width">The width to resize to.</param>
            /// <param name="height">The height to resize to.</param>
            /// <returns>The resized image.</returns>
            public static Bitmap ResizeImage(System.Drawing.Image image, int width, int height)
            {
                var destRect  = new System.Drawing.Rectangle(0, 0, width, height);
                var destImage = new System.Drawing.Bitmap(width, height);

                destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

                using (var graphics = Graphics.FromImage(destImage))
                {
                    graphics.CompositingMode    = CompositingMode.SourceCopy;
                    graphics.CompositingQuality = CompositingQuality.HighQuality;
                    graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                    graphics.SmoothingMode      = SmoothingMode.HighQuality;
                    graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;

                    using (var wrapMode = new ImageAttributes())
                    {
                        wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                        graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
                    }
                }

                return(destImage);
            }
Example #14
0
        /// <summary>
        /// Converts the <paramref name="image"/> to a byte array.
        /// </summary>
        /// <param name="image">The image to convert.</param>
        /// <param name="compressionLevel">The compression level to use.</param>
        /// <returns>The converted byte array.</returns>
        private static byte[] ConvertImageToBytes(System.Drawing.Image image, long compressionLevel)
        {
            if (compressionLevel < 0)
            {
                compressionLevel = 0;
            }
            else if (compressionLevel > 100)
            {
                compressionLevel = 100;
            }

            var imageCodecInfo    = GetImageCodecInfo(ImageFormat.Jpeg);
            var encoder           = Encoder.Quality;
            var encoderParameters = new EncoderParameters(1);
            var encoderParameter  = new EncoderParameter(encoder, compressionLevel);

            encoderParameters.Param[0] = encoderParameter;

            using (var memoryStream = new MemoryStream())
            {
                image.Save(memoryStream, imageCodecInfo, encoderParameters);
                return(memoryStream.ToArray());
            }
        }
Example #15
0
 private static Image ConvertImage(System.Drawing.Image image)
 {
     return(Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Jpeg));
 }
        void WriteDocument(iTextSharp.text.Document doc, List <KeyValuePair <ISearchAlgorithm <string>, SearchReport <string> > > results, System.Drawing.Image initialGraph)
        {
            doc.AddCreationDate();
            doc.AddAuthor("GraphSEA");
            doc.AddCreator("GraphSEA");
            doc.AddHeader("Header", "GraphSEA - Graph search algorithms benchmark report");
            WriteHeader(doc);
            doc.NewPage();
            WriteGraph(doc, initialGraph, results[0].Value.Result.Start, results[0].Value.Result.End);
            doc.NewPage();
            WriteResultSummary(doc, results);
            doc.NewPage();
            // algorithms benchmarks
            foreach (var res in results)
            {
                CurrentReport = res.Value;
                WriteAlgorithmBenchmark(doc, res.Key, res.Value);
            }

            WriteTableOfContent(doc);
        }
Example #17
0
 /// <summary>
 /// Vykreslování čísla na podklad
 /// </summary>
 /// <param name="aNumber">Číslo, které se má na obrázek vložit</param>
 /// <param name="aImage">Obrázek (podklad) na který se vkládá</param>
 /// <param name="aXMove">Počet pixelů o které se má číslo na obrázku posunout v ose X</param>
 /// <param name="aYMove">Počet pixelů o které se má číslo na obrázku posunout v ose Y</param>
 private void DrawNumber(decimal aNumber, ref System.Drawing.Image aImage, int aXMove, int aYMove)
 {
     this.DrawNumber(aNumber, ref aImage, aXMove, aYMove, new Font("Comic Sans MS", 90f, FontStyle.Regular, GraphicsUnit.Point));
 }
        public void SaveReport(string file, List <KeyValuePair <ISearchAlgorithm <string>, SearchReport <string> > > results, System.Drawing.Image initialGraph)
        {
            try
            {
                if (File.Exists(file))
                {
                    File.Delete(file);
                }



                using (FileStream fs = File.OpenWrite(file))
                {
                    iTextSharp.text.Document document = new iTextSharp.text.Document();
                    var writer = PdfWriter.GetInstance(document, fs);
                    pageEventHelper  = new PageEventHelper();
                    writer.PageEvent = pageEventHelper;
                    document.Open();
                    WriteDocument(document, results, initialGraph);
                    document.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBoxEx.Show("Failed to export pdf report", "Benchmark reporter", MessageBoxButtons.OK,
                                  MessageBoxIcon.Error);
            }
        }
Example #19
0
        static void Main(string[] args)
        {
            Document  document        = new Document(PageSize.LETTER, 0f, 0f, 0f, 0f);
            string    inputFile       = "Heroes Unlimited RPG - 2E.pdf";
            string    destinationFile = "OUT" + inputFile;
            PdfWriter writer          = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));

            writer.SetFullCompression();
            PdfDate st = new PdfDate(DateTime.Today);

            document.Open();
            PdfContentByte cb = writer.DirectContent;

            PdfImportedPage page;

            int rotation;

            int iPageNo = 1;

            PdfReader reader = new PdfReader(inputFile);
            int       n      = reader.NumberOfPages;

            int i = 1;

            while (i <= n)
            {
                document.NewPage();

                PdfDictionary pg = reader.GetPageN(i);

                // recursively search pages, forms and groups for images.
                PdfObject obj = FindImageInPDFDictionary(pg);
                if (obj != null)
                {
                    int XrefIndex =
                        Convert.ToInt32(((PRIndirectReference)obj).Number.ToString(System.Globalization.CultureInfo
                                                                                   .InvariantCulture));
                    PdfObject pdfObj   = reader.GetPdfObject(XrefIndex);
                    PdfStream pdfStrem = (PdfStream)pdfObj;
                    byte[]    bytes    = PdfReader.GetStreamBytesRaw((PRStream)pdfStrem);
                    if ((bytes != null))
                    {
                        using (System.IO.MemoryStream memStream = new System.IO.MemoryStream(bytes))
                        {
                            memStream.Position = 0;
                            System.Drawing.Image img = i == 1 || i == n?System.Drawing.Image.FromStream(memStream) ://let the first and last page stay the same size.
                                                           BitmapToGrayscale(ImageHelper.ResizeImage(System.Drawing.Image.FromStream(memStream), .35M));


                            ImageFormat format = img.PixelFormat == PixelFormat.Format1bppIndexed ||
                                                 img.PixelFormat == PixelFormat.Format4bppIndexed ||
                                                 img.PixelFormat == PixelFormat.Format8bppIndexed
                                    ? ImageFormat.Tiff
                                    : ImageFormat.Jpeg;

                            var pdfImage = iTextSharp.text.Image.GetInstance(img, format);
                            pdfImage.Alignment = Element.ALIGN_CENTER;
                            pdfImage.ScaleToFit(document.PageSize.Width - 10, document.PageSize.Height - 10);
                            pdfImage.ColorTransform = 1;
                            //page = writer.GetImportedPage(reader, i);
                            document.Add(pdfImage);
                        }
                    }
                }

                i++;
                Console.SetCursorPosition(0, 0);
                Console.Write($"{((i*100)/(n)).ToString().PadLeft(3)}%");
            }
            Console.WriteLine("Complete");
            document.Close();

            // ExtractImagesFromPDF(inputFile, ".\\");
        }
        void WriteAlgorithmStep(iTextSharp.text.Document doc, KeyValuePair <INode <string>, NodeVisitAction> step, System.Drawing.Image graphImage)
        {
            if (step.Value == NodeVisitAction.PreVisit)
            {
                doc.Add(new Paragraph(new Chunk("Pre-Visit",
                                                new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 18,
                                                                         iTextSharp.text.Font.BOLDITALIC, iTextSharp.text.BaseColor.YELLOW))));


                doc.Add(new Paragraph(new Chunk("The algorithm has opened the node " + step.Key,
                                                new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12,
                                                                         iTextSharp.text.Font.ITALIC, iTextSharp.text.BaseColor.BLACK))));
            }
            else if (step.Value == NodeVisitAction.Visit)
            {
                doc.Add(new Paragraph(new Chunk("Visit",
                                                new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 18,
                                                                         iTextSharp.text.Font.BOLDITALIC, iTextSharp.text.BaseColor.GREEN))));


                doc.Add(new Paragraph(new Chunk("The algorithm has marked the node " + step.Key + " as visited",
                                                new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12,
                                                                         iTextSharp.text.Font.ITALIC, iTextSharp.text.BaseColor.BLACK))));
            }
            else if (step.Value == NodeVisitAction.PostVisit)
            {
                doc.Add(new Paragraph(new Chunk("Post-Visit",
                                                new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 18,
                                                                         iTextSharp.text.Font.BOLDITALIC, iTextSharp.text.BaseColor.BLUE))));


                doc.Add(new Paragraph(new Chunk("The algorithm has closed the node " + step.Key,
                                                new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12,
                                                                         iTextSharp.text.Font.ITALIC, iTextSharp.text.BaseColor.BLACK))));
            }
            else if (step.Value == NodeVisitAction.FoundResult)
            {
                doc.Add(new Paragraph(new Chunk("Result Found",
                                                new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 18,
                                                                         iTextSharp.text.Font.BOLDITALIC, iTextSharp.text.BaseColor.RED))));


                doc.Add(new Paragraph(new Chunk("The algorithm has found the target node " + step.Key,
                                                new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12,
                                                                         iTextSharp.text.Font.ITALIC, iTextSharp.text.BaseColor.BLACK))));
            }
            else if (step.Value == NodeVisitAction.Reset)
            {
                doc.Add(new Paragraph(new Chunk("Reset",
                                                new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 18,
                                                                         iTextSharp.text.Font.BOLDITALIC, iTextSharp.text.BaseColor.ORANGE))));


                doc.Add(new Paragraph(new Chunk("The algorithm is starting a new iteration with a different parameter (depth (IDLS) or Threshhold (IDA*))",
                                                new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12,
                                                                         iTextSharp.text.Font.ITALIC, iTextSharp.text.BaseColor.BLACK))));
            }

            doc.Add(new Paragraph(new Chunk("")));
            // add graph  state image
            AddImage(doc, graphImage);
            doc.NewPage();
        }
Example #21
0
        public static void ExtractImagesFromPDF(string sourcePdf, string outputPath, int index)
        {
            // NOTE:  This will only get the first image it finds per page.
            PdfReader pdf = new PdfReader(sourcePdf);
            RandomAccessFileOrArray raf = new iTextSharp.text.pdf.RandomAccessFileOrArray(sourcePdf);

            try
            {
                for (int pageNumber = 1; pageNumber <= pdf.NumberOfPages; pageNumber++)
                {
                    PdfDictionary pg  = pdf.GetPageN(pageNumber);
                    PdfDictionary res =
                        (PdfDictionary)PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES));
                    PdfDictionary xobj =
                        (PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT));
                    if (xobj != null)
                    {
                        foreach (PdfName name in xobj.Keys)
                        {
                            PdfObject obj = xobj.Get(name);
                            if (obj.IsIndirect())
                            {
                                PdfDictionary tg   = (PdfDictionary)PdfReader.GetPdfObject(obj);
                                PdfName       type =
                                    (PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE));
                                if (PdfName.IMAGE.Equals(type))
                                {
                                    int       XrefIndex = Convert.ToInt32(((PRIndirectReference)obj).Number.ToString(System.Globalization.CultureInfo.InvariantCulture));
                                    PdfObject pdfObj    = pdf.GetPdfObject(XrefIndex);
                                    PdfStream pdfStrem  = (PdfStream)pdfObj;
                                    byte[]    bytes     = PdfReader.GetStreamBytesRaw((PRStream)pdfStrem);
                                    if ((bytes != null))
                                    {
                                        using (System.IO.MemoryStream memStream = new System.IO.MemoryStream(bytes))
                                        {
                                            memStream.Position = 0;
                                            System.Drawing.Image img = System.Drawing.Image.FromStream(memStream);
                                            // must save the file while stream is open.
                                            if (!Directory.Exists(outputPath))
                                            {
                                                Directory.CreateDirectory(outputPath);
                                            }

                                            //string path = Path.Combine(outputPath, String.Format(@"{0}.jpg", pageNumber));
                                            string            _pageNumber = pageNumber.ToString().PadLeft(3, '0');
                                            string            path        = Path.Combine(outputPath, index + "_" + _pageNumber + ".jpg");
                                            EncoderParameters parms       = new EncoderParameters(1);
                                            parms.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 0);
                                            // GetImageEncoder is found below this method
                                            ImageCodecInfo jpegEncoder = GetImageEncoder("JPEG");
                                            img.Save(path, jpegEncoder, parms);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            catch
            {
                // throw;
            }
            finally
            {
                pdf.Close();
            }
        }
Example #22
0
        public void Generate(Indulgence indulgence, string fontsDirectory, string contentDirectory, string bkFilename,
                             string pdfFilename, string imageThumbnailFileName_1, string imageThumbnailFileName_2,
                             string imageThumbnailFileName_3, string imageThumbnailFileName_4)
        {
            string thumb1Filename = imageThumbnailFileName_1;
            string thumb2Filename = imageThumbnailFileName_2;
            string thumb3Filename = imageThumbnailFileName_3;
            string thumb4Filename = imageThumbnailFileName_4;

            Rectangle background = PageSize.LETTER.Rotate();

            background.BackgroundColor = new BaseColor(0, 0, 0, 0);
            Document doc = new Document(PageSize.LETTER.Rotate(), 20, 20, 0, 0); // 70, 70, 130, 70

            byte[] pdfData = null;
            using (var ms = new System.IO.MemoryStream())
            {
                var pdfWriter = PdfWriter.GetInstance(doc, ms);
                pdfWriter.PageEvent = new ParchmentPageEventHelper(_storage, contentDirectory, bkFilename);

                BaseFont uechiGothicBase = BaseFont.CreateFont(System.IO.Path.Combine(fontsDirectory, "UECHIGOT.ttf"),
                                                               BaseFont.CP1252, BaseFont.EMBEDDED);
                BaseFont trajanProBase =
                    BaseFont.CreateFont(System.IO.Path.Combine(fontsDirectory, "TrajanPro-Regular.otf"), BaseFont.CP1252,
                                        BaseFont.EMBEDDED);
                Font uechiGothic = new Font(uechiGothicBase, 150, iTextSharp.text.Font.NORMAL, new BaseColor(139, 0, 0));

                Font trajanProConfession = new Font(trajanProBase, 45, iTextSharp.text.Font.BOLDITALIC,
                                                    new BaseColor(139, 0, 0));

                Font trajanProBoldSmall   = new Font(trajanProBase, 24, Font.BOLD, new BaseColor(139, 54, 38));
                Font trajanProAttribution = new Font(trajanProBase, 24, iTextSharp.text.Font.NORMAL,
                                                     new BaseColor(139, 54, 38));

                doc.Open();

                var t = new PdfPTable(1);
                t.WidthPercentage = 100;
                var c = new PdfPCell();
                c.VerticalAlignment = Element.ALIGN_MIDDLE;
                c.MinimumHeight     = doc.PageSize.Height - (doc.BottomMargin + doc.TopMargin);


                // confession
                Phrase firstLetterPhrase   = new Phrase(indulgence.Confession.Substring(0, 1).ToUpper(), uechiGothic);
                Phrase confessionPhrase    = new Phrase(indulgence.Confession.Substring(1), trajanProConfession);
                var    confessionParagraph = new Paragraph(firstLetterPhrase);
                confessionParagraph.Add(confessionPhrase);
                confessionParagraph.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
                confessionParagraph.Leading   = 45;


                // attribution
                List <Phrase> phrases = new List <Phrase>();
                phrases.Add(new Phrase("On this ", trajanProAttribution));
                phrases.Add(new Phrase(TextUtils.DayOfMonth(indulgence.DateConfessed), trajanProBoldSmall));
                phrases.Add(new Phrase(" day of ", trajanProAttribution));
                phrases.Add(new Phrase(string.Format("{0:MMMM}", indulgence.DateConfessed), trajanProBoldSmall));
                phrases.Add(new Phrase(" in the year of our Lord ", trajanProAttribution));
                phrases.Add(new Phrase(indulgence.DateConfessed.Year.ToString(), trajanProBoldSmall));
                phrases.Add(new Phrase(", ", trajanProAttribution));
                var attributionName = indulgence.Name;
                if (string.IsNullOrWhiteSpace(attributionName))
                {
                    attributionName = "An Anonymous Believer";
                }
                phrases.Add(new Phrase(attributionName, trajanProBoldSmall));
                phrases.Add(new Phrase(" selflessly gave the sum of ", trajanProAttribution));
                phrases.Add(new Phrase(string.Format("{0:c}", indulgence.AmountDonated), trajanProBoldSmall));
                phrases.Add(new Phrase(" to the deserving organisation ", trajanProAttribution));
                phrases.Add(new Phrase(indulgence.CharityName, trajanProBoldSmall));
                phrases.Add(new Phrase(" and received this plenary indulgence", trajanProAttribution));

                var attribution = new Paragraph();
                confessionParagraph.Add(Environment.NewLine);
                foreach (var phrase in phrases)
                {
                    confessionParagraph.Add(phrase);
                }
                attribution.Leading = 24;

                /*attribution.Insert(0, attributionName);
                 * attribution.Add(attributionDonation);
                 * attribution.Add(attributionTo);
                 * attribution.Add(attributionCharity);*/
                attribution.SpacingBefore = 30;
                c.AddElement(confessionParagraph);
                t.AddCell(c);
                doc.Add(t);

                doc.Close();
                pdfData = ms.ToArray();
            }

            _storage.Store(pdfFilename, pdfData, true);

            System.Drawing.Image img = null;
            using (MemoryStream pdfStream = new MemoryStream(pdfData))
                using (MemoryStream pngStream = new MemoryStream())
                {
                    GhostscriptVersionInfo gvi =
                        new GhostscriptVersionInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"gsdll32.dll"));
                    using (var rasterizer = new Ghostscript.NET.Rasterizer.GhostscriptRasterizer())
                    {
                        rasterizer.Open(pdfStream, gvi, true);
                        rasterizer.EPSClip = false;
                        img = rasterizer.GetPage(96, 96, 1);
                        img.RotateFlip(RotateFlipType.Rotate90FlipNone);
                        img.Save(pngStream, ImageFormat.Png);
                        _storage.Store(thumb1Filename, pngStream.ToArray(), true);
                    }
                }

            float ratio = (float)img.Height / (float)img.Width;

            SaveThumbnail(img, new SizeF(800, 800 * ratio), thumb2Filename);
            SaveThumbnail(img, new SizeF(300, 300 * ratio), thumb3Filename);
            SaveThumbnail(img, new SizeF(150, 150 * ratio), thumb4Filename);

            // TODO: generate thumbnails as byte arrays and store to IFileStorage
        }