GetInstance() public static méthode

Gets an instance of an Image.
public static GetInstance ( Image image ) : Image
image Image an Image
Résultat Image
Exemple #1
0
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            try
            {
                base.OnEndPage(writer, document);
                PdfPTable pagetable = new PdfPTable(3);
                pagetable.SetWidths(new float[] { 24f, 24f, 2f });
                pagetable.TotalWidth              = 527;
                pagetable.HorizontalAlignment     = Element.ALIGN_CENTER;
                pagetable.DefaultCell.FixedHeight = 20f;
                pagetable.DefaultCell.Border      = PdfPCell.TOP_BORDER;

                pagetable.AddCell("");
                pagetable.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;

                pagetable.AddCell($"Page {writer.PageNumber} of ");
                PdfPCell cell = new PdfPCell(Image.GetInstance(total));
                cell.Border = PdfPCell.TOP_BORDER;
                pagetable.AddCell(cell);
                pagetable.WriteSelectedRows(0, -1, 34, 34, writer.DirectContent);
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemple #2
0
        public string ConvertImageToPdf(string srcFilename, string dstFilename)
        {
            var document = new Document(PageSize.A4, 25, 25, 25, 25);

            using (var stream = new FileStream(dstFilename, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                PdfWriter.GetInstance(document, stream);
                document.Open();
                using (var imageStream = new FileStream(srcFilename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    var image = Image.GetInstance(imageStream);
                    if (image.Height > PageSize.A4.Height - 25)
                    {
                        image.ScaleToFit(PageSize.A4.Width - 25, PageSize.A4.Height - 25);
                    }
                    else if (image.Width > PageSize.A4.Width - 25)
                    {
                        image.ScaleToFit(PageSize.A4.Width - 25, PageSize.A4.Height - 25);
                    }
                    image.Alignment = Element.ALIGN_MIDDLE;
                    document.Add(image);
                }

                document.Close();
                return(dstFilename);
            }
        }
        private void GenerateTitle(Document doc)
        {
            doc.NewPage();
            Image img = Image.GetInstance(Path.Combine(Environment.CurrentDirectory, "mg-logo.png"));

            img.ScaleToFit(125f, 60F);
            doc.Add(img);
            iTextSharp.text.Font font = FontFactory.GetFont(FontFactory.COURIER_BOLD, 14);
            Paragraph            p    = new Paragraph(reportTitle, font)
            {
                SpacingBefore = -35,
                SpacingAfter  = 0,
                Alignment     = 1
            };

            doc.Add(p);
            doc.Add(Chunk.NEWLINE);

            iTextSharp.text.Font font1 = FontFactory.GetFont(FontFactory.COURIER_BOLD, 12);
            Paragraph            p1    = new Paragraph(rolId.Equals(3) ? "Clientes externos" : "Clientes internos", font1)
            {
                SpacingBefore = -25,
                SpacingAfter  = 3,
                Alignment     = 1
            };

            doc.Add(p1);
            doc.Add(Chunk.NEWLINE);
        }
Exemple #4
0
        private static void AddLogoToPdf(AgencyOwnerFixedPriceProposalDetailsOutput proposal, PdfPTable layoutTable)
        {
            PdfPCell orgImageCell = new PdfPCell
            {
                Border = Rectangle.NO_BORDER,
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_TOP,
                MinimumHeight       = 80
            };

            if (!string.IsNullOrEmpty(proposal.AccountManagerOrganizationImageUrl?.Trim()))
            {
                Image orgImage = Image.GetInstance(proposal.AccountManagerOrganizationImageUrl);
                orgImage.ScaleToFit(70, 70);
                orgImage.Alignment = Element.ALIGN_LEFT | Element.ALIGN_TOP;
                orgImageCell.AddElement(orgImage);
            }

            layoutTable.AddCell(orgImageCell);

            var fontHeader = GetCommonFont(22);

            AddCellToTable(layoutTable, fontHeader, "Proposal", Element.ALIGN_RIGHT, 1, 2);
            AddCellToTable(layoutTable, fontHeader, "", Element.ALIGN_RIGHT, 1, 3);
        }
Exemple #5
0
        private static byte[] CreateImagePdf()
        {
            MemoryStream byteStream = new MemoryStream();


            Document  document = new Document();
            PdfWriter writer   = PdfWriter.GetInstance(document, byteStream);

            document.SetPageSize(PageSize.LETTER);

            document.Open();


            Bitmap   awtImg = new Bitmap(100, 100, PixelFormat.Format32bppRgb);
            Graphics g      = Graphics.FromImage(awtImg);

            g.FillRectangle(new SolidBrush(Color.Green), 10, 10, 80, 80);
            g.Save();
            Image itextImg = Image.GetInstance(awtImg, (BaseColor)null);

            document.Add(itextImg);

            document.Close();

            byte[] pdfBytes = byteStream.ToArray();

            return(pdfBytes);
        }
        private void AddCover()
        {
            try
            {
                byte[] cover = WebCrawler.DownloadCover(lnParameters.urlCover);

                PdfImage pic = PdfImage.GetInstance(cover);

                if (pic.Height > pic.Width)
                {
                    //Maximum height is 800 pixels.
                    float percentage = 0.0f;
                    percentage = 700 / pic.Height;
                    pic.ScalePercent(percentage * 100);
                }
                else
                {
                    //Maximum width is 600 pixels.
                    float percentage = 0.0f;
                    percentage = 540 / pic.Width;
                    pic.ScalePercent(percentage * 100);
                }

                pic.Border      = Rectangle.BOX;
                pic.BorderColor = BaseColor.BLACK;
                pic.BorderWidth = 3f;
                pdf.NewPage();
                pdf.Add(pic);
            }
            catch (CoverException)
            {}
        }
        public void BarcodesPDF()// Штрих код генерация
        {
            /// Для отображения русских букв
            var baseFont = BaseFont.CreateFont(@"C:\Windows\Fonts\Arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            var font     = new iTextSharp.text.Font(baseFont, 12);
            var barcode  = new BarcodeLib.Barcode();
            var sfd      = new SaveFileDialog {
                FileName = "Barcodes", Filter = "PDF file (*.pdf)|*.pdf"
            };

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                var Doc    = new Document(new iTextSharp.text.Rectangle(165, 1000), 1f, 1f, 1f, 1f);/// для чека - 58мм на 38мм
                var Stream = new FileStream(sfd.FileName, FileMode.Create, FileAccess.Write, FileShare.None);
                PdfWriter.GetInstance(Doc, Stream);
                Doc.Open();

                for (int i = 0; i < Table.DtInvoice.Rows.Count; i++)
                {
                    var item         = Table.DtInvoice.Rows[i][2].ToString();
                    var imageBarcode = barcode.Encode(BarcodeLib.TYPE.CODE128B, item, Color.Black, Color.White, 165, 50);/// CODE39
                    var image        = Image.GetInstance(imageBarcode, ImageFormat.Jpeg);
                    Doc.Add(new Paragraph($"Спецсвязь {item}", font));
                    Doc.Add(image);
                }
                Doc.Close();
                // Открытие созданного файла
                Process.Start(sfd.FileName);
            }
        }
Exemple #8
0
        //通过Url方式获取图片
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Document document = new Document();

            PdfWriter.GetInstance(document, new FileStream("Url获取图片.pdf",
                                                           FileMode.OpenOrCreate));

            document.Open();

            //uri方式
            //Image image = Image.GetInstance(new Uri("images/11.jpg",UriKind.Absolute));

            //document.Add(image);


            //路径
            Image image2 = Image.GetInstance("11.jpg"); //图片放在/bin/debug下

            image2.ScaleToFit(document.PageSize);       //缩放图片
            //Chunk chunk=new Chunk(image2,);

            document.Add(image2);

            document.Close();

            Title = "图片";
        }
        private Image GetImage(string cardName, Settings settings)
        {
            var imagesDir = settings.BoosterImageDir ?? string.Format("images\\{0}", settings.Set);
            var files     = Directory.GetFiles(imagesDir);
            var names     = files.Select(f => new KeyValuePair <string, string>(ExtractName(f), f)).ToArray();
            var match     = names.Where(n => n.Key.Equals(cardName, StringComparison.InvariantCultureIgnoreCase)).ToArray();

            if (match.Length == 0)
            {
                return(null);
            }
            string imagePath;

            if (match.Length == 1)
            {
                imagePath = match[0].Value;
            }
            else
            {
                imagePath = match[_rnd.Next(match.Length)].Value;
            }
            //imagePath = "Empty\\Empty.jpg";
            if (!_imagesCache.ContainsKey(imagePath))
            {
                var imageStream = File.Open(imagePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                _imagesCache[imagePath] = Image.GetInstance(imageStream);
            }
            return(_imagesCache[imagePath]);
        }
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            //-------------------------------------------------Foo-------------------------------------------
            PdfPTable tbHeader = new PdfPTable(3);

            tbHeader.TotalWidth         = document.PageSize.Width - document.LeftMargin - document.RightMargin;
            tbHeader.DefaultCell.Border = 0;
            tbHeader.AddCell(new Paragraph());

            PdfPCell _cell = new PdfPCell(new Paragraph("Comprobante de Pago Salarial"));

            _cell.HorizontalAlignment = Element.ALIGN_CENTER;
            _cell.Border = 0;

            tbHeader.AddCell(_cell);

            _cell = new PdfPCell(new Paragraph("N°" + NumeroComprobante));
            _cell.HorizontalAlignment = Element.ALIGN_RIGHT;
            _cell.Border = 0;

            tbHeader.AddCell(_cell);
            tbHeader.AddCell(new Paragraph());
            tbHeader.WriteSelectedRows(0, -1, document.LeftMargin, writer.PageSize.GetTop(document.TopMargin) + 30, writer.DirectContent);



            //-------------------------------------------------Footer-------------------------------------------
            PdfPTable tbFooder = new PdfPTable(3);

            tbFooder.TotalWidth         = document.PageSize.Width - document.LeftMargin - document.RightMargin;
            tbFooder.DefaultCell.Border = 0;
            tbFooder.AddCell(new Paragraph());


            _cell = new PdfPCell(new Paragraph("Coorporación Los negritos S.A"));
            _cell.HorizontalAlignment = Element.ALIGN_CENTER;
            _cell.Border = 0;

            tbFooder.AddCell(_cell);


            _cell = new PdfPCell(new Paragraph("Pagina" + writer.PageNumber));
            _cell.HorizontalAlignment = Element.ALIGN_RIGHT;
            _cell.Border = 0;

            tbFooder.AddCell(_cell);
            tbFooder.WriteSelectedRows(0, -1, document.LeftMargin, writer.PageSize.GetBottom(document.BottomMargin) - 5, writer.DirectContent);

            //Inicio imagen

            Image logo = Image.GetInstance(PathImage);

            logo.SetAbsolutePosition(document.LeftMargin, writer.PageSize.GetTop(document.TopMargin + 40));
            logo.ScaleAbsolute(135f, 135f);
            document.Add(logo);


            //final de imagen
        }
        /// <summary>
        /// Adds the image to the pdf document
        /// </summary>
        /// <param name="document">The document to annotate</param>
        /// <param name="imageDocument">The image document</param>
        public void AddImageToPdfDocument(Document document, Document imageDocument)
        {
            // Get image information
            var documentTypeImageCoOrdinates = document.Type.DocumentTypeImageCoOrdinates.FirstOrDefault(e => e.ImageDocumentType.Id == imageDocument.Type.Id);

            if (documentTypeImageCoOrdinates == null)
            {
                return;
            }

            // Create a pdf reader to read the document content, and a pdf stamper to modify it and output to a memory stream
            var reader  = new PdfReader(document.LatestRevision.Content.Content);
            var oStream = new MemoryStream();
            var stamper = new PdfStamper(reader, oStream);

            // Get the image page of the PDF document object
            var pdfContentByte = stamper.GetOverContent(documentTypeImageCoOrdinates.PageNumber);

            // Create a white rectangle bitmap for the background image
            var bitmap = new Bitmap(documentTypeImageCoOrdinates.MaxWidth, documentTypeImageCoOrdinates.MaxHeight);

            using (var graphics = Graphics.FromImage(bitmap))
            {
                var rectangle = new System.Drawing.Rectangle(0, 0, documentTypeImageCoOrdinates.MaxWidth, documentTypeImageCoOrdinates.MaxHeight);
                graphics.FillRectangle(Brushes.White, rectangle);
            }

            // Draw the background image onto the pdf to clear any previous image
            var image = Image.GetInstance(bitmap, ImageFormat.Bmp);

            image.SetAbsolutePosition(documentTypeImageCoOrdinates.OriginX, documentTypeImageCoOrdinates.OriginY);
            pdfContentByte.AddImage(image);

            // Draw the image onto the pdf
            image = Image.GetInstance(imageDocument.LatestRevision.Content.Content);
            image.ScaleToFit(documentTypeImageCoOrdinates.MaxWidth, documentTypeImageCoOrdinates.MaxHeight);
            var differenceX = documentTypeImageCoOrdinates.MaxWidth - image.ScaledWidth;
            var differenceY = documentTypeImageCoOrdinates.MaxHeight - image.ScaledHeight;

            image.SetAbsolutePosition(
                differenceX > 0 ? documentTypeImageCoOrdinates.OriginX + (differenceX / 2) : documentTypeImageCoOrdinates.OriginX,
                differenceY > 0 ? documentTypeImageCoOrdinates.OriginY + (differenceY / 2) : documentTypeImageCoOrdinates.OriginY
                );
            pdfContentByte.AddImage(image);

            // Close the pdf stamper to flush the output memory stream
            stamper.Writer.CloseStream = false;
            stamper.Close();

            // Move the stream position to the beginning
            oStream.Seek(0, SeekOrigin.Begin);

            // Update content, length and checksum
            var content = oStream.ToArray();

            document.LatestRevision.Content.Content      = content;
            document.LatestRevision.Content.FileChecksum = GenerateFileChecksum(content);
            document.LatestRevision.Bytes = content.Length;
        }
 private Image GetPdfImage(Bitmap image)
 {
     using (var stream = new MemoryStream())
     {
         image.Save(stream, ImageFormat.Bmp);
         stream.Position = 0;
         return(Image.GetInstance(stream));
     }
 }
Exemple #13
0
        public Image GenerateLogo()
        {
            Image image = Image.GetInstance(LOGO.GetLogoPath());

            //原长度为1.5f
            image.ScaleAbsoluteHeight(UNIT * 1.3f);
            image.ScaleAbsoluteWidth(UNIT * 1.3f);
            return(image);
        }
Exemple #14
0
        public void GuardarPdf(List <DetalleFacturaCompra> detalles, List <Proveedor> compras, string path)
        {
            FileStream stream   = new FileStream(path, FileMode.Create);
            Document   document = new Document(iTextSharp.text.PageSize.LETTER, 40, 40, 40, 40);
            PdfWriter  writer   = PdfWriter.GetInstance(document, stream);

            document.AddAuthor("Aplicacion de inventario");
            document.Open();
            document.Add(new Paragraph("DETALLE FACTURA REGISTRADA"));

            document.Add(new Paragraph("  SK SHOP TU TIENDA "));
            document.Add(new Paragraph("\n"));
            var        imagepath = @"C:IMG-9593.PNG";
            FileStream stream1   = new FileStream(imagepath, FileMode.Open);
            {
                var png = Image.GetInstance(System.Drawing.Image.FromStream(stream1), ImageFormat.Png);
                png.ScalePercent(5f);
                png.SetAbsolutePosition(document.Left, document.Top);
                document.Add(png);
            }
            var spacer = new Paragraph("")
            {
                SpacingBefore = 10f,
                SpacingAfter  = 10f,
            };

            document.Add(spacer);

            //var headerTable = new PdfPTable(new[] { .75f, 2f })
            //{
            //    HorizontalAlignment = Left,
            //    WidthPercentage = 75,
            //    DefaultCell = { MinimumHeight = 22f }
            //};


            //headerTable.AddCell("Fecha");
            //headerTable.AddCell(DateTime.Now.ToString());
            //headerTable.AddCell("Razon social");
            //headerTable.AddCell(proveedor.RazonSocial);
            //headerTable.AddCell("Telefono");
            //headerTable.AddCell(proveedor.Telefono);
            //headerTable.AddCell("Direccion");
            //headerTable.AddCell(proveedor.Direccion);



            document.Add(llenarTablaEncabezado(compras));
            document.Add(spacer);
            var columnWidths = new[] { 1f, 1f, 2f, 1f };

            document.Add(new Paragraph("                  LISTA DE PRODUCTOS"));
            document.Add(new Paragraph("\n"));
            document.Add(LlenarTabla(detalles));
            document.Close();
        }
Exemple #15
0
        /// <summary>
        /// Vytvoření PDF dokumentu + nasypání obrázky v řadě s očíslováním. EatDrink ticket.
        /// </summary>
        private void mBtnEatDrinkTicketCreate_Click(object sender, EventArgs e)
        {
            mImages.Clear();
            try
            {
                var lPath       = mTbOutputPath.Text;
                var lOriginFile = mTbInputPath.Text;

                var lImage = System.Drawing.Image.FromFile(lOriginFile);

                int   lXMove    = Convert.ToInt32(mNumUDEatDrinkTicketXMove.Value);
                int   lYMove    = Convert.ToInt32(mNumUDEatDrinkTicketYMove.Value);
                float lFontSize = (float)(mNumUDEatDrinkFontSize.Value);

                for (var i = mNumUDEatDrinkTicketFrom.Value; i <= mNumUDEatDrinkTicketTo.Value; i++)
                {
                    this.UpdateProgress(this.mProgressBarEatDrinkTicketCreated, i, mNumUDEatDrinkTicketTo.Value);

                    var nCopyOfImage = (System.Drawing.Image)lImage.Clone();
                    DrawNumber(i, ref nCopyOfImage, lXMove, lYMove, new Font("Comic Sans MS", lFontSize, FontStyle.Regular, GraphicsUnit.Point));
                    mImages.Add(Image.GetInstance(nCopyOfImage, ImageFormat.Jpeg));
                    //mImages.Add(Image.GetInstance(nCopyOfImage, BaseColor.PINK));
                }

                var lFS     = new FileStream(lPath, FileMode.Create);
                var lDoc    = new Document();
                var lWriter = PdfWriter.GetInstance(lDoc, lFS);
                //if (mCheckLandscape.Checked)
                //{
                //    //lDoc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
                //    lDoc.SetPageSize(new Rectangle(2230, 3008).Rotate());
                //}
                //else
                //{
                //lDoc.SetPageSize(iTextSharp.text.PageSize.A4);
                lDoc.SetPageSize(new Rectangle(3150, 4150));
                //}

                lDoc.Open();
                foreach (var item in mImages)
                {
                    lDoc.Add(new iTextSharp.text.Chunk(item, 0, 0, true));
                }
                lDoc.Close();

                Process.Start(lPath);

                this.UpdateProgress(mProgressBarEatDrinkTicketCreated, -1, -1);
            }
            catch (Exception exc)
            {
                MessageBox.Show(
                    @"Neco se nezdarilo! Pravdepodobne mate otevreny soubor, do ktereho se maji vstupenky ulozit.\nZobrazte toto prosím autorovi aplikace:\n" +
                    exc);
            }
        }
Exemple #16
0
        private void SavePDF_Click(object sender, RoutedEventArgs e)
        {
            DataAccess db = new DataAccess();

            int count = measurementID.Count - 1;

            for (int i = 0; i < count; i++)
            {
                MakeModels(measurementID[i].PK);//measurement from a date is stored in that list
            }


            using (SaveFileDialog sfd = new SaveFileDialog {
                Filter = "PDF file|*.pdf", ValidateNames = true
            })
            {
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    /* Create PDF Document */
                    iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4);
                    try
                    {
                        Image png;

                        PdfWriter.GetInstance(doc, new FileStream(sfd.FileName, FileMode.Create));
                        doc.Open();

                        doc.Add(new iTextSharp.text.Phrase("    "));
                        doc.Add(new iTextSharp.text.Phrase($" AMKA:{AMKAtxt.Text}   Sex:{sextxt.Text}   "));
                        doc.Add(new Paragraph("Histograms"));


                        for (int i = 0; i < count; i++)
                        {
                            OxyPlot.Wpf.PngExporter.Export(model[i], "test.png", 1500, 800, OxyColors.White, 200);
                            png = Image.GetInstance("test.png");
                            png.ScalePercent(24f);
                            png.Alignment = Image.ALIGN_CENTER;
                            doc.Add(png);
                        }

                        doc.Close();
                    }
                    catch (Exception ex)
                    {
                        System.Windows.MessageBox.Show(ex.Message, "Message");
                    }
                    finally
                    {
                        doc.Close();
                    }
                }
            }
        }
Exemple #17
0
        public IHttpActionResult CreatePdfForCreator(string fullName, string profession, string workPhone, string text, string signDate, string qrCodeLocation, string fileLocation)
        {
            using (var fileStream = new FileStream(fileLocation, FileMode.Create, FileAccess.Write))
            {
                iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.A4, 25, 25, 30, 30);
                var writer = PdfWriter.GetInstance(document, fileStream);
                document.Open();

                var arialFontPath = HttpContext.Current.Server.MapPath("/Template/ARIALUNI.TTF");
                FontFactory.Register(arialFontPath);
                var baseFont = BaseFont.CreateFont(arialFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

                var contentByte = writer.DirectContent;
                contentByte.BeginText();
                contentByte.SetFontAndSize(baseFont, 12f);

                string executorName = $"{fullName}";
                string prof         = $"{profession}";
                string phone        = $"{workPhone}";
                string docNumber    = $"{text}";
                string date         = $"{signDate}";

                Rectangle pageSize = new Rectangle(document.PageSize);

                contentByte.EndText();
                contentByte.SetLineWidth(0f);
                contentByte.MoveTo(50, document.Bottom + 27f);
                contentByte.LineTo(553, document.Bottom + 27f);
                contentByte.Stroke();
                contentByte.BeginText();
                contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "İcraçı:", 50, 130, 0);
                contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, prof + " " + executorName, 50, 105, 0);
                contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Telefon: " + phone, 50, 80, 0);
                contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, docNumber, 50, 42, 0);
                contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, date, 50, 27, 0);


                Image image = Image.GetInstance(qrCodeLocation);
                image.ScaleAbsoluteWidth(54.5f);
                image.ScaleAbsoluteHeight(48.5f);
                image.SetAbsolutePosition(pageSize.Width - 96, 5);
                contentByte.AddImage(image, false);

                contentByte.EndText();


                document.Close();
                writer.Close();
                fileStream.Close();
            }

            return(Ok(true));
        }
Exemple #18
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);
        }
        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);
        }
Exemple #20
0
        public static string CreatePDF(ItemCollection files, string fileName)
        {
            try
            {
                var document = new Document(PageSize.LETTER);

                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }

                PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));

                // step 3: we open the document
                document.Open();

                foreach (var file in files)
                {
                    var pic = Image.GetInstance(file.ToString());

                    if (pic.Height > pic.Width)
                    {
                        //Maximum height is 800 pixels.
                        float percentage = 0.0f;
                        percentage = 700 / pic.Height;
                        pic.ScalePercent(percentage * 100);
                    }
                    else
                    {
                        //Maximum width is 600 pixels.
                        float percentage = 0.0f;
                        percentage = 540 / pic.Width;
                        pic.ScalePercent(percentage * 100);
                    }

                    pic.Border      = Rectangle.BOX;
                    pic.BorderColor = BaseColor.BLACK;
                    pic.BorderWidth = 3f;
                    document.Add(pic);
                    document.NewPage();
                }

                document.Close();
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }

            return("Success");
        }
        /// <summary>
        /// Crea la seccion donde vienen los comentarios del Supervisor
        /// </summary>
        private void CrearSupervisor()
        {
            var tblSupervisor = new PdfPTable(2)
            {
                TotalWidth = 558f, LockedWidth = true
            };
            var supervisor          = new Phrase("Supervisor", _fontDoceBold);
            var valueDateSupervisor = new Phrase("21 Apr, 2017", _fontDoceBold);
            var date = new Phrase(_informacion.Date.ToString(CultureInfo.CurrentCulture) /*"21 Apr, 2017"*/, _fontDoce);

            var cellSupervisor          = new PdfPCell(supervisor);
            var cellDateSupervisor      = new PdfPCell(date);
            var cellValueDateSupervisor = new PdfPCell(valueDateSupervisor);
            var firma = Image.GetInstance("C:/Users/mario.chan/Documents/GitHub/Benchmark/Library_benchmark/Content/images/firma.PNG");

            firma.ScalePercent(2);
            var cellFirma = new PdfPCell(firma, true);


            cellSupervisor.Rowspan         = 2;
            cellSupervisor.Border          = 0;
            cellSupervisor.BackgroundColor = _baseColorBackground;
            cellSupervisor.BorderWidthTop  = _borderWidth;
            cellSupervisor.BorderColor     = _baseColorLines;
            cellSupervisor.FixedHeight     = _fixedHeight;

            cellDateSupervisor.Border          = 0;
            cellDateSupervisor.BackgroundColor = _baseColorBackground;
            cellDateSupervisor.BorderWidthTop  = _borderWidth;
            cellDateSupervisor.BorderColor     = _baseColorLines;
            cellDateSupervisor.FixedHeight     = _fixedHeight;

            cellValueDateSupervisor.Border          = 0;
            cellValueDateSupervisor.BackgroundColor = _baseColorBackground;
            cellValueDateSupervisor.BorderColor     = _baseColorLines;
            cellValueDateSupervisor.FixedHeight     = _fixedHeight;

            cellFirma.Colspan           = 2;
            cellFirma.Border            = 0;
            cellFirma.BackgroundColor   = _baseColorBackground;
            cellFirma.BorderWidthBottom = _borderWidth;
            cellFirma.BorderColor       = _baseColorLines;


            tblSupervisor.AddCell(cellSupervisor);
            tblSupervisor.AddCell(cellDateSupervisor);
            tblSupervisor.AddCell(cellValueDateSupervisor);
            tblSupervisor.AddCell(cellFirma);

            _doc.Add(tblSupervisor);
        }
Exemple #22
0
        private PointF AddLabelImage(Document doc,
                                     PdfWriter writer,
                                     string image,
                                     PrintLabelSizeType labelSize,
                                     PrintLabelInfo labelInfo,
                                     int number)
        {
            var imageObj = Image.GetInstance(image);

            imageObj.CompressionLevel = PdfStream.BEST_COMPRESSION;

            if (imageObj.Height < imageObj.Width)
            {
                if (labelInfo.RotationAngle.HasValue)
                {
                    imageObj.Rotation = (float)(labelInfo.RotationAngle.Value / (float)360 * (2 * Math.PI));
                }
                //if (labelInfo.ShippingMethodId == ShippingUtils.IBCCEPePocketMethodId)
                //    imageObj.Rotation = -(float) Math.PI/2;
                else
                {
                    imageObj.Rotation = -(float)Math.PI / 2;
                }
                imageObj.Rotate();
            }

            //image1.SetImageQuality(80); //before 50%

            var width  = doc.PageSize.Width - 2 * LabelPaddingX;
            var height = doc.PageSize.Height / 2 - 2 * LabelPaddingY;

            if (labelSize == PrintLabelSizeType.FullPage)
            {
                height = doc.PageSize.Height - 2 * LabelPaddingY;
            }

            imageObj.ScaleToFit(width, height);

            PointF startPoint;
            var    dy = (doc.PageSize.Height - imageObj.ScaledHeight) / 2;
            var    dx = (doc.PageSize.Width - imageObj.ScaledWidth) / 2;

            startPoint = new PointF(dx, dy);

            imageObj.SetAbsolutePosition(startPoint.X, startPoint.Y);

            doc.Add(imageObj);

            return(new PointF(imageObj.ScaledWidth, imageObj.ScaledHeight));
        }
        private Image[,] SameImage(string path)
        {
            var images = new Image[3, 3];

            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    var imageStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
                    images[i, j] = Image.GetInstance(imageStream);
                }
            }
            return(images);
        }
        private Image[,] RandomImages(string dir)
        {
            var rnd    = _rnd;
            var files  = Directory.GetFiles(dir, "*.jpg");
            var images = new Image[3, 3];

            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    var path        = files[rnd.Next(files.Length)];
                    var imageStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
                    images[i, j] = Image.GetInstance(imageStream);
                }
            }
            return(images);
        }
        public Image ReziseImg(string path)
        {
            Image img = Image.GetInstance(path);

            //img.ScaleAbsolute(159f, 159f); //-->absoluto(llena todo el espacio disponible)
            //img.ScalePercent(5f);
            //Rectangle rec = new Rectangle(80f, 80f, 80f, 50f);
            img.ScaleAbsolute(100, 100);
            img.Border = Rectangle.NO_BORDER;

            img.BorderColor = BaseColor.WHITE;

            img.BorderWidth = 5f;
            //PdfPTable table = new PdfPTable(1);
            //table.AddCell(img);
            return(img);
        }
Exemple #26
0
        public void Export()
        {
            if (pnControls.Controls.Count <= 0)
            {
                return;
            }

            var obj = new SaveFileDialog
            {
                Filter = @"PDF (*.pdf)|*.pdf"
            };

            if (obj.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            if (obj.FileName != "")
            {
                var document = new Document();
                PdfWriter.GetInstance(document, new FileStream(obj.FileName, FileMode.Create));
                document.Open();
                GotoPage(0);

                for (var i = 0; i <= totalpages; i++)
                {
                    if (i != 0)
                    {
                        document.NewPage();
                        NextPage();
                    }

                    var bitmap = new Bitmap(pnControls.Width, pnControls.Height);
                    bitmap.SetResolution(300, 300);
                    pnControls.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
                    var layerImage = Image.GetInstance(bitmap, ImageFormat.Bmp);
                    layerImage.ScaleToFit(document.PageSize.Width, document.PageSize.Height);
                    document.Add(layerImage);
                }


                document.Close();

                GotoPage(CurrentPage);
            }
        }
Exemple #27
0
        /// <summary>
        /// 将Html文字 输出到PDF档里
        /// </summary>
        /// <param name="htmlText">html文本</param>
        /// <param name="param">pdf大小</param>
        /// <param name="waterMark">水印</param>
        /// <param name="stampPoint">模拟盖章</param>
        /// <returns></returns>
        public static byte[] ConvertHtmlTextToPdf(string htmlText, DocumentParam param, WatermarkSetting waterMark = null, StampPoint stampPoint = null)
        {
            if (string.IsNullOrEmpty(htmlText))
            {
                return(null);
            }
            //避免当htmlText无任何html tag标签的纯文字时,转PDF时会挂掉,所以一律加上<p>标签
            htmlText = "<p>" + htmlText + "</p>";

            MemoryStream outputStream = new MemoryStream();                                                                                 //要把PDF写到哪个串流

            byte[]       data    = Encoding.UTF8.GetBytes(htmlText.ToCharArray());                                                          //字串转成byte[]
            MemoryStream msInput = new MemoryStream(data);
            Document     doc     = new Document(param.PageSize, param.MarginLeft, param.MarginRight, param.MarginTop, param.MarginBottom);; //要写PDF的文件,建构子没填的话预设直式A4
            PdfWriter    writer  = PdfWriter.GetInstance(doc, outputStream);
            //writer.SetViewerPreferences(PdfWriter.HideMenubar | PdfWriter.HideToolbar);
            //指定文件预设开档时的缩放为100%

            PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f);

            //开启Document文件
            doc.Open();
            if (stampPoint != null && !string.IsNullOrEmpty(stampPoint.Path))
            {
                var img = Image.GetInstance(stampPoint.Path);
                img.SetAbsolutePosition(doc.PageSize.Width - img.Width - stampPoint.X, img.Height + stampPoint.Y);
                doc.Add(img);
            }

            //使用XMLWorkerHelper把Html parse到PDF档里
            XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory());
            //XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8);

            //将pdfDest设定的资料写到PDF档
            var action = PdfAction.GotoLocalPage(1, pdfDest, writer);

            writer.SetOpenAction(action);
            doc.Close();
            msInput.Close();
            outputStream.Close();

            return(SetWatermark(waterMark, outputStream.ToArray()));
        }
Exemple #28
0
        protected void AuditReportHeader(PdfPTable headingtable, AuditReportHeaderFields headerFields)
        {
            Image logo = Image.GetInstance(global::Common.Properties.Resources.logo, BaseColor.WHITE);

            //I used a large version of the logo to maintain the quality when the size was reduced. I guess you could reduce the size manually and use a smaller version, but I used iTextSharp to reduce the scale. As you can see, I reduced it down to 7% of original size.
            logo.ScalePercent(25);

            PdfPCell cell = new PdfPCell();

            //  row 1
            cell        = new PdfPCell(logo);
            cell.Border = Rectangle.NO_BORDER;
            cell.HorizontalAlignment = Element.ALIGN_LEFT;
            cell.VerticalAlignment   = Element.ALIGN_TOP;
            cell.Colspan             = 1;
            headingtable.AddCell(cell);

            cell        = new PdfPCell(new Paragraph(string.Empty, ReportFont));
            cell.Border = Rectangle.NO_BORDER;
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            cell.VerticalAlignment   = Element.ALIGN_TOP;
            cell.Colspan             = 6;
            headingtable.AddCell(cell);

            WriteCell(headingtable, string.Empty, ReportFontMedium, 5, Element.ALIGN_LEFT, Rectangle.NO_BORDER, false);
            WriteCell(headingtable, headerFields.ReportStore, ReportFontRegular, 2, Element.ALIGN_LEFT, Rectangle.NO_BORDER, false);

            WriteCell(headingtable, string.Empty, ReportFont, 5, Element.ALIGN_LEFT, Rectangle.NO_BORDER, false);
            WriteCell(headingtable, "Shop Number: #" + headerFields.StoreNumber.ToString(), ReportFontRegular, 2, Element.ALIGN_LEFT, Rectangle.NO_BORDER, false);

            WriteCell(headingtable, string.Empty, ReportFont, 5, Element.ALIGN_LEFT, Rectangle.NO_BORDER, false);
            WriteCell(headingtable, "Inventory Audit Date: " + headerFields.InventoryAuditDate.ToShortDateString(), ReportFontRegular, 2, Element.ALIGN_LEFT, Rectangle.NO_BORDER, false);

            WriteCell(headingtable, string.Empty, ReportFont, 2, Element.ALIGN_LEFT, Rectangle.NO_BORDER, false);
            WriteCell(headingtable, headerFields.ReportTitle, ReportFontHeading, 2, Element.ALIGN_CENTER, Rectangle.NO_BORDER, false);
            WriteCell(headingtable, string.Empty, ReportFont, 1, Element.ALIGN_LEFT, Rectangle.NO_BORDER, false);
            WriteCell(headingtable, "Report #: " + headerFields.ReportNumber.ToString(), ReportFontRegular, 2, Element.ALIGN_LEFT, Rectangle.NO_BORDER, false);

            WriteCell(headingtable, string.Empty, ReportFont, 7, Element.ALIGN_CENTER, Rectangle.NO_BORDER, false);
            WriteCell(headingtable, string.Empty, ReportFont, 7, Element.ALIGN_CENTER, Rectangle.NO_BORDER, false);
        }
Exemple #29
0
        public virtual void RenderImage(ImageRenderInfo renderInfo)
        {
            IList <Rectangle> areasToBeCleaned = GetImageAreasToBeCleaned(renderInfo);

            if (areasToBeCleaned == null)
            {
                chunks.Add(new PdfCleanUpContentChunk.Image(false, null));
            }
            else
            {
                PdfImageObject pdfImage   = renderInfo.GetImage();
                byte[]         imageBytes = ProcessImage(pdfImage.GetImageAsBytes(), areasToBeCleaned);

                if (renderInfo.GetRef() == null && pdfImage != null)   // true => inline image
                {
                    PdfDictionary dict      = pdfImage.GetDictionary();
                    PdfObject     imageMask = dict.Get(PdfName.IMAGEMASK);
                    Image         image     = Image.GetInstance(imageBytes);

                    if (imageMask == null)
                    {
                        imageMask = dict.Get(PdfName.IM);
                    }

                    if (imageMask != null && imageMask.Equals(PdfBoolean.PDFTRUE))
                    {
                        image.MakeMask();
                    }

                    PdfContentByte canvas = Context.Canvas;
                    canvas.AddImage(image, 1, 0, 0, 1, 0, 0, true);
                }
                else if (pdfImage != null && imageBytes != pdfImage.GetImageAsBytes())
                {
                    chunks.Add(new PdfCleanUpContentChunk.Image(true, imageBytes));
                }
            }
        }
        public async void ExportFile()
        {
            var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage);

            if (status != PermissionStatus.Granted)
            {
                if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Storage))
                {
                    await Application.Current.MainPage.DisplayAlert("Need storage", "Request storage permission", "OK");
                }

                var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Storage);

                //Best practice to always check that the key exists
                if (results.ContainsKey(Permission.Storage))
                {
                    status = results[Permission.Storage];
                }
            }

            if (status == PermissionStatus.Granted)
            {
                try
                {
                    string documentsPath = DependencyService.Get <IOSDependency>().GetPath();
                    string localFilename = string.Format("{0}.pdf", DateTime.Now.ToLongDateString());
                    string localPath     = Path.Combine(documentsPath, localFilename);
                    //File.WriteAllBytes(localPath, bytes);
                    FileStream fs = new FileStream(localPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);

                    // Create an instance of the document class which represents the PDF document itself.
                    Document document = new Document(PageSize.A4, 25, 25, 30, 30);

                    // Create an instance to the PDF file by creating an instance of the PDF Writer class, using the document and the filestrem in the constructor.
                    PdfWriter writer = PdfWriter.GetInstance(document, fs);

                    // Open the document to enable you to write to the document
                    document.Open();
                    PdfContentByte cb = writer.DirectContent;

                    // Set text font and size
                    cb.BeginText();
                    cb.SetFontAndSize(bfComic, 9);

                    // Create header of doc
                    BaseFont  bfTimes   = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
                    Font      times     = new Font(bfTimes, 38, Font.BOLDITALIC, Color.MAGENTA);
                    Paragraph paragraph = new Paragraph("Diabee", times);
                    paragraph.Alignment    = Element.ALIGN_CENTER;
                    paragraph.SpacingAfter = 10f;

                    // Add header to doc
                    document.Add(paragraph);

                    paragraph = new Paragraph("The simplest glucose and weight monitoring app",
                                              new Font(Font.HELVETICA, 24f, Font.BOLD));
                    paragraph.IndentationLeft  = 20f;
                    paragraph.IndentationRight = 20f;
                    paragraph.Alignment        = Element.ALIGN_CENTER;
                    paragraph.SpacingAfter     = 18f;
                    document.Add(paragraph);

                    // Add the app image on the top left
                    Stream s = null;
                    s = DependencyService.Get <IOSDependency>().GetStream();

                    Image img = Image.GetInstance(s);
                    img.SetAbsolutePosition(20, 700);
                    img.ScalePercent(75);
                    img.Alignment = Image.TEXTWRAP | Image.ALIGN_RIGHT;
                    cb.AddImage(img);

                    // Retrieve glucose data first
                    List <GlucoseHistoryDataModel> glucoseData = Constants.ReadGlucoseData(Constants.GlucoseFileName).ToList();
                    PdfPTable glucoseTable      = new PdfPTable(3);
                    PdfPCell  glucoseHeaderCell = new PdfPCell(new Phrase("Glucose Readings",
                                                                          new Font(Font.HELVETICA, 10f, Font.BOLD)));
                    glucoseHeaderCell.Colspan             = 3;
                    glucoseHeaderCell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
                    glucoseHeaderCell.Padding             = 5f;
                    glucoseTable.AddCell(glucoseHeaderCell);

                    // Setup proper header labels
                    glucoseTable.AddCell("Date");
                    glucoseTable.AddCell("Time");
                    glucoseTable.AddCell("Glucose Value (mmol/l)");

                    foreach (var glucoseEntry in glucoseData)
                    {
                        glucoseTable.AddCell(glucoseEntry.HistoryDate);
                        glucoseTable.AddCell(glucoseEntry.HistoryTime.ToString());
                        glucoseTable.AddCell(glucoseEntry.GlucoseValue);
                    }

                    glucoseTable.SpacingBefore = 20f;
                    glucoseTable.SpacingAfter  = 30f;

                    // Add glucose table to document
                    document.Add(glucoseTable);

                    // Then retrieve weight data
                    List <WeightHistoryDataModel> weightData = Constants.ReadWeightData(Constants.WeightFileName).ToList();
                    PdfPTable weightTable      = new PdfPTable(3);
                    PdfPCell  weightHeaderCell = new PdfPCell(new Phrase("Weight Readings",
                                                                         new Font(Font.HELVETICA, 10f, Font.BOLD)));
                    weightHeaderCell.Colspan             = 3;
                    weightHeaderCell.Padding             = 5f;
                    weightHeaderCell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
                    weightTable.AddCell(weightHeaderCell);

                    // Setup proper header labels
                    weightTable.AddCell("Date");
                    weightTable.AddCell("Time");
                    weightTable.AddCell("Weight Value (Kg)");

                    foreach (var weightEntry in weightData)
                    {
                        weightTable.AddCell(weightEntry.HistoryDate);
                        weightTable.AddCell(weightEntry.HistoryTime.ToString());
                        weightTable.AddCell(weightEntry.WeightValue);
                    }

                    weightTable.SpacingBefore = 20f;
                    weightTable.SpacingAfter  = 30f;

                    // End text
                    cb.EndText();

                    // Add weight table to document
                    document.Add(weightTable);

                    // Close the document
                    s.Close();
                    document.Close();

                    // Close the writer instance
                    writer.Close();
                    // Always close open file handles explicitly
                    fs.Close();
                    DependencyService.Get <IMessage>().ShortAlert("Exported!");
                }
                catch
                {
                }
            }
        }