Example #1
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 #2
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();
            }
        }
Example #3
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 #4
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 #5
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
        }
Example #6
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();
            }
        }