Exemple #1
0
        private void button_Click(object sender, RoutedEventArgs e)
        {
            var retangulo = new iTextSharp.text.Rectangle(765, 765);
            var documento = new Document(retangulo);

            var writer = PdfWriter.GetInstance(documento, new FileStream(@"c:\teste\teste.pdf", FileMode.Create));

            documento.Open();

            var imagemDoTopo = iTextSharp.text.Image.GetInstance(@"c:\teste\imagem.png");

            imagemDoTopo.SetAbsolutePosition(0, 100);
            documento.Add(imagemDoTopo);

            PdfContentByte cb         = writer.DirectContent;
            BaseFont       outraFonte = BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, false, false);

            cb.BeginText();
            cb.SetFontAndSize(outraFonte, 12);
            cb.SetColorFill(new BaseColor(51, 51, 51));
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "TESTE", 50, 35, 50);
            cb.EndText();

            var paramQR = new Dictionary <EncodeHintType, object>();

            paramQR.Add(EncodeHintType.CHARACTER_SET, CharacterSetECI.GetCharacterSetECIByName("UTF-8"));
            BarcodeQRCode qrCodigo = new BarcodeQRCode("https://www.youtube.com/channel/UCcOGfx3w8BRxkfSyZFsW5fQ",
                                                       150, 150, paramQR);

            iTextSharp.text.Image imgBarCode = qrCodigo.GetImage();
            imgBarCode.SetAbsolutePosition(200, 200);
            documento.Add(imgBarCode);

            BarcodeEAN codeEAN13 = null;

            codeEAN13                  = new BarcodeEAN();
            codeEAN13.CodeType         = Barcode.EAN13;
            codeEAN13.ChecksumText     = true;
            codeEAN13.GenerateChecksum = true;
            codeEAN13.BarHeight        = 12;
            codeEAN13.Code             = "1234567890123";
            imgBarCode                 = codeEAN13.CreateImageWithBarcode(cb, null, null);
            imgBarCode.SetAbsolutePosition(150, 150);
            imgBarCode.Alignment = iTextSharp.text.Image.TEXTWRAP;
            documento.Add(imgBarCode);



            documento.Close();
        }
        private void btPdf_Click(object sender, EventArgs e)
        {
            try
            {
                /* ============ PRIMEIRA FORMA ============
                 * //var retangulo = new iTextSharp.text.Rectangle(765, 765);
                 * var documento = new Document(PageSize.A4, 10, 10, 10, 10);
                 *
                 * var writer = PdfWriter.GetInstance(documento, new FileStream(@"c:\teste\teste.pdf", FileMode.Create));
                 *
                 * documento.Open();
                 *
                 * var imagem = iTextSharp.text.Image.GetInstance(@"C:\teste\robin.png");
                 * imagem.SetAbsolutePosition(10,60);
                 * documento.Add(imagem);
                 *
                 * PdfContentByte cb = writer.DirectContent;
                 * BaseFont fonte = BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, false, false);
                 *
                 * cb.BeginText();
                 * cb.SetFontAndSize(fonte, 12);
                 * cb.SetColorFill(new BaseColor(51, 51, 51));
                 * cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Damian Wayne\nTeste", 20, 800, 0);
                 *
                 * int linhas = dgvDados.RowCount;
                 * int colunas = dgvDados.ColumnCount;
                 *
                 * for (int i = 0; i < linhas; i++)
                 * {
                 *  for (int x = 0; x < colunas; x++)
                 *  {
                 *      cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, Convert.ToString(dgvDados.Rows[i].Cells[x].Value), 20, 400, 0);
                 *  }
                 * }
                 *
                 * cb.EndText();
                 * documento.Close();
                 *
                 * MessageBox.Show("PDF gerado com sucesso!", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information);
                 */

                /*========== SEGUNDA FORMA ==========
                 * CHUNK: é a menor parte de um texto a ser inserido (palavra)
                 * PHRASE: é um conjunto de palavras (frases)
                 * PARAGRAPH: é um paragrafo (conjunto de frases)
                 */
                var documento = new Document(PageSize.A4, 10, 10, 10, 10);

                Stream str;

                SaveFileDialog salvarRelatorioPDF = new SaveFileDialog();

                salvarRelatorioPDF.Filter = "PDF (*.pdf) | *.pdf";

                salvarRelatorioPDF.FilterIndex      = 2;
                salvarRelatorioPDF.Title            = "Salvar Relatorio em PDF";
                salvarRelatorioPDF.RestoreDirectory = true;
                var salvar_dir = "";


                if (salvarRelatorioPDF.ShowDialog() == DialogResult.OK)
                {
                    if ((str = salvarRelatorioPDF.OpenFile()) != null)
                    {
                        salvar_dir = salvarRelatorioPDF.FileName;
                    }
                    else
                    {
                        DialogResult x = MessageBox.Show("Não Foi possivel salvar", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    str.Close();
                }


                var writer = PdfWriter.GetInstance(documento, new FileStream(salvar_dir, FileMode.Create));

                documento.Open();

                var imagem = iTextSharp.text.Image.GetInstance(@"../../../image.png");
                imagem.SetAbsolutePosition(20, 775);
                documento.Add(imagem);

                var imagem2 = iTextSharp.text.Image.GetInstance(@"../../../image2.png");
                imagem2.SetAbsolutePosition(500, 775);
                documento.Add(imagem2);


                // Definindo as fontes
                var titulo = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 16, 2, BaseColor.RED);

                var fonte = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 12, 0, BaseColor.BLACK);

                var letra = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 10, 0, BaseColor.BLACK);

                var rodape = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.SYMBOL, 13, 0, BaseColor.BLUE);

                documento.Add(new Paragraph(""));
                documento.Add(new Paragraph(""));
                documento.Add(new Paragraph(""));
                //criando parágrafo
                var paragrafo1 = new Paragraph("R E L A T O R Í O", titulo);
                paragrafo1.Alignment = Element.ALIGN_CENTER;
                documento.Add(paragrafo1);

                var nome1 = new Paragraph("Lucas Anselmo", fonte);
                nome1.Alignment = Element.ALIGN_CENTER;
                documento.Add(nome1);

                var nome2 = new Paragraph("João Vinicius" + "\n" + "_____________________________________________________________________________", fonte);
                nome2.Alignment = Element.ALIGN_CENTER;
                documento.Add(nome2);

                //data do relatorio
                var paragrafo2 = new Paragraph("ITU, " + DateTime.Now.ToLongDateString());
                paragrafo2.Alignment = Element.ALIGN_RIGHT;
                documento.Add(paragrafo2);

                int  linhas  = dgvDados.RowCount;
                int  colunas = dgvDados.ColumnCount;
                var  frase   = new Phrase();
                bool flag    = false;

                for (int i = 0; i < linhas; i++)
                {
                    for (int x = 0; x < colunas; x++)
                    {
                        frase = new Phrase(Convert.ToString(dgvDados.Rows[i].Cells[x].Value) + " - ", letra);
                        //documento.Add(frase);
                        flag = documento.Add(frase);
                    }
                    frase = new Phrase("\n");
                    flag  = documento.Add(frase);
                }

                //gerar codigo de barras
                PdfContentByte cb = writer.DirectContent;
                cb.BeginText();
                iTextSharp.text.Image imgBarCode;

                BarcodeEAN codeEAN = null;
                codeEAN                  = new BarcodeEAN();
                codeEAN.CodeType         = Barcode.EAN13;
                codeEAN.ChecksumText     = true;
                codeEAN.GenerateChecksum = true;
                codeEAN.BarHeight        = 12;
                codeEAN.Code             = "1234567890123";
                imgBarCode               = codeEAN.CreateImageWithBarcode(cb, null, null);
                imgBarCode.SetAbsolutePosition(20, 350);
                imgBarCode.Alignment = iTextSharp.text.Image.TEXTWRAP;
                documento.Add(imgBarCode);
                cb.EndText();

                //Gerar QRCODE
                var paramQR = new Dictionary <EncodeHintType, object>();
                paramQR.Add(EncodeHintType.CHARACTER_SET, CharacterSetECI.GetCharacterSetECIByName("UTF-8"));
                BarcodeQRCode         qrcodigo  = new BarcodeQRCode("http://www.etecitu.com.br", 150, 150, paramQR);
                iTextSharp.text.Image imgQrCode = qrcodigo.GetImage();
                imgQrCode.SetAbsolutePosition(410, 300);
                documento.Add(imgQrCode);

                documento.Close();

                if (flag == true)
                {
                    DialogResult d = MessageBox.Show("Relatorio gerado com sucesso!\nDeseja abri-lo?", "Aviso", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                    if (d.ToString() == "Yes")
                    {
                        System.Diagnostics.Process.Start(@salvar_dir);
                    }
                }
                else
                {
                    MessageBox.Show("Não foi gerado");
                }
            }
            catch (Exception erro)
            {
                MessageBox.Show(erro.Message);
            }
        }
Exemple #3
0
        /// <summary>
        /// Encodes the specified content.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <param name="ecLevel">The ec level.</param>
        /// <param name="hints">The hints.</param>
        /// <returns></returns>
        public static QRCode Encode(String content, ErrorCorrectionLevel ecLevel)
        {
            var encoding = DEFAULT_BYTE_MODE_ENCODING;
            var generateECI = !DEFAULT_BYTE_MODE_ENCODING.Equals(encoding);

            // Pick an encoding mode appropriate for the content. Note that this will not attempt to use
            // multiple modes / segments even if that were more efficient. Twould be nice.
            var mode = ChooseMode(content, encoding);

            // This will store the header information, like mode and
            // length, as well as "header" segments like an ECI segment.
            var headerBits = new BitArray();

            // Append ECI segment if applicable
            if (mode == Mode.BYTE && generateECI)
            {
                var eci = CharacterSetECI.GetCharacterSetECIByName(encoding);
                if (eci != null)
                {
                    AppendECI(eci, headerBits);
                }
            }

            // (With ECI in place,) Write the mode marker
            AppendModeInfo(mode, headerBits);

            // Collect data within the main segment, separately, to count its size if needed. Don't add it to
            // main payload yet.
            var dataBits = new BitArray();
            AppendBytes(content, mode, dataBits, encoding);

            Version version = RecommendVersion(ecLevel, mode, headerBits, dataBits);

            var headerAndDataBits = new BitArray();
            headerAndDataBits.AppendBitArray(headerBits);
            // Find "length" of main segment and write it
            var numLetters = mode == Mode.BYTE ? dataBits.SizeInBytes : content.Length;
            AppendLengthInfo(numLetters, version, mode, headerAndDataBits);
            // Put data together into the overall payload
            headerAndDataBits.AppendBitArray(dataBits);

            var ecBlocks = version.GetECBlocksForLevel(ecLevel);
            var numDataBytes = version.TotalCodewords - ecBlocks.TotalECCodewords;

            // Terminate the bits properly.
            TerminateBits(numDataBytes, headerAndDataBits);

            // Interleave data bits with error correction code.
            var finalBits = InterleaveWithECBytes(headerAndDataBits,
                                                       version.TotalCodewords,
                                                       numDataBytes,
                                                       ecBlocks.NumBlocks);

            var qrCode = new QRCode
            {
                ECLevel = ecLevel,
                Mode = mode,
                Version = version
            };

            //  Choose the mask pattern and set to "qrCode".
            var dimension = version.DimensionForVersion;
            var matrix = new ByteMatrix(dimension, dimension);
            var maskPattern = ChooseMaskPattern(finalBits, ecLevel, version, matrix);
            qrCode.MaskPattern = maskPattern;

            // Build the matrix and set it to "qrCode".
            MatrixUtil.BuildMatrix(finalBits, ecLevel, version, maskPattern, matrix);
            qrCode.Matrix = matrix;

            return qrCode;
        }