Exemple #1
0
    public void Write(Stream stream)
    {
        using (Document document = new Document()) {
            PdfWriter writer = PdfWriter.GetInstance(document, stream);

            document.Open();
            document.Add(new Paragraph("This document contains a collection of PDFs"));

            PdfIndirectReference parentFolderObjectReference = writer.PdfIndirectReference;
            PdfIndirectReference childFolder1ObjectReference = writer.PdfIndirectReference;
            PdfIndirectReference childFolder2ObjectReference = writer.PdfIndirectReference;

            PdfDictionary parentFolderObject = GetFolderDictionary(0);
            parentFolderObject.Put(new PdfName("Child"), childFolder1ObjectReference);
            parentFolderObject.Put(PdfName.NAME, new PdfString());

            PdfDictionary childFolder1Object = GetFolderDictionary(1);
            childFolder1Object.Put(PdfName.NAME, new PdfString("Folder 1"));
            childFolder1Object.Put(PdfName.PARENT, parentFolderObjectReference);
            childFolder1Object.Put(PdfName.NEXT, childFolder2ObjectReference);

            PdfDictionary childFolder2Object = GetFolderDictionary(2);
            childFolder2Object.Put(PdfName.NAME, new PdfString("Folder 2"));
            childFolder2Object.Put(PdfName.PARENT, parentFolderObjectReference);

            PdfCollection       collection = new PdfCollection(PdfCollection.DETAILS);
            PdfCollectionSchema schema     = CollectionSchema();
            collection.Schema = schema;
            collection.Sort   = new PdfCollectionSort(keys);
            collection.Put(new PdfName("Folders"), parentFolderObjectReference);
            writer.Collection = collection;

            PdfFileSpecification fs;
            PdfCollectionItem    item;

            fs   = PdfFileSpecification.FileEmbedded(writer, file1Path, File1, null);
            item = new PdfCollectionItem(schema);
            item.AddItem("Type", "pdf");
            fs.AddCollectionItem(item);
            // the description is apparently used to place the
            // file in a particular folder.  The number between the < and >
            // is used to put the file in the folder that has the matching id
            fs.AddDescription(GetDescription(1, File1), false);
            writer.AddFileAttachment(fs);

            fs   = PdfFileSpecification.FileEmbedded(writer, file2Path, File2, null);
            item = new PdfCollectionItem(schema);
            item.AddItem("Type", "pdf");
            fs.AddCollectionItem(item);
            fs.AddDescription(GetDescription(2, File2), false);
            writer.AddFileAttachment(fs);

            writer.AddToBody(parentFolderObject, parentFolderObjectReference);
            writer.AddToBody(childFolder1Object, childFolder1ObjectReference);
            writer.AddToBody(childFolder2Object, childFolder2ObjectReference);

            document.Close();
        }
    }
        public void CreatePdf(String dest)
        {
            Document  document = new Document();
            PdfWriter writer   = PdfWriter.GetInstance(document, new FileStream(dest, FileMode.Create));

            document.Open();
            document.Add(new Paragraph("Portable collection"));
            PdfCollection collection = new PdfCollection(PdfCollection.TILE);

            writer.Collection = collection;
            PdfFileSpecification fileSpec = PdfFileSpecification.FileEmbedded(writer, DATA, "united_states.csv", null);

            writer.AddFileAttachment("united_states.csv", fileSpec);
            fileSpec = PdfFileSpecification.FileEmbedded(writer, HELLO, "hello.pdf", null);
            writer.AddFileAttachment("hello.pdf", fileSpec);
            fileSpec = PdfFileSpecification.FileEmbedded(writer, IMG, "berlin2013.jpg", null);
            writer.AddFileAttachment("berlin2013.jpg", fileSpec);
            document.Close();
        }
 /// <summary>
 /// Adds all of the file attachments.
 /// </summary>
 public void AddFileAttachments()
 {
     if (PageSetup.FileAttachments == null || !PageSetup.FileAttachments.Any())
     {
         return;
     }
     foreach (var file in PageSetup.FileAttachments)
     {
         var fileInfo      = new FileInfo(file.FilePath);
         var pdfDictionary = new PdfDictionary();
         pdfDictionary.Put(PdfName.Moddate, new PdfDate(fileInfo.LastWriteTime));
         var fs = PdfFileSpecification.FileEmbedded(PdfWriter, file.FilePath, fileInfo.Name, null, true, null, pdfDictionary);
         PdfWriter.AddFileAttachment(file.Description, fs);
     }
 }
Exemple #4
0
// ---------------------------------------------------------------------------
        public void Write(Stream stream)
        {
            // step 1
            using (Document document = new Document()) {
                // step 2
                PdfWriter writer = PdfWriter.GetInstance(document, stream);
                // step 3
                document.Open();
                // step 4
                document.Add(new Paragraph(
                                 "This document contains a collection of PDFs,"
                                 + " one per Stanley Kubrick movie."
                                 ));

                PdfCollection       collection = new PdfCollection(PdfCollection.DETAILS);
                PdfCollectionSchema schema     = _collectionSchema();
                collection.Schema = schema;
                PdfCollectionSort sort = new PdfCollectionSort("YEAR");
                sort.SetSortOrder(false);
                collection.Sort            = sort;
                collection.InitialDocument = "Eyes Wide Shut";
                writer.Collection          = collection;

                PdfCollectionItem   item;
                IEnumerable <Movie> movies = PojoFactory.GetMovies(1);
                foreach (Movie movie in movies)
                {
                    PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(
                        writer, null,
                        String.Format("kubrick_{0}.pdf", movie.Imdb),
                        CreateMoviePage(movie)
                        );
                    fs.AddDescription(movie.Title, false);

                    item = new PdfCollectionItem(schema);
                    item.AddItem("TITLE", movie.GetMovieTitle(false));
                    if (movie.GetMovieTitle(true) != null)
                    {
                        item.SetPrefix("TITLE", movie.GetMovieTitle(true));
                    }
                    item.AddItem("DURATION", movie.Duration.ToString());
                    item.AddItem("YEAR", movie.Year.ToString());
                    fs.AddCollectionItem(item);
                    writer.AddFileAttachment(fs);
                }
            }
        }
Exemple #5
0
        internal void ExtractAttachments(string file_name, string folderName, PdfWriter write)
        {
            PdfDictionary documentNames = null;
            PdfDictionary embeddedFiles = null;
            PdfDictionary fileArray     = null;
            PdfDictionary file          = null;
            PRStream      stream        = null;

            PdfReader     reader  = new PdfReader(file_name);
            PdfDictionary catalog = reader.Catalog;

            documentNames = (PdfDictionary)PdfReader.GetPdfObject(catalog.Get(PdfName.NAMES));

            if (documentNames != null)
            {
                embeddedFiles = (PdfDictionary)PdfReader.GetPdfObject(documentNames.Get(PdfName.EMBEDDEDFILES));
                if (embeddedFiles != null)
                {
                    PdfArray filespecs = embeddedFiles.GetAsArray(PdfName.NAMES);

                    for (int i = 0; i < filespecs.Size; i++)
                    {
                        i++;
                        fileArray = filespecs.GetAsDict(i);
                        file      = fileArray.GetAsDict(PdfName.EF);

                        foreach (PdfName key in file.Keys)
                        {
                            stream = (PRStream)PdfReader.GetPdfObject(file.GetAsIndirectObject(key));
                            string attachedFileName  = folderName + fileArray.GetAsString(key).ToString();
                            byte[] attachedFileBytes = PdfReader.GetStreamBytes(stream);
                            //graba el anexo extraido
                            System.IO.File.WriteAllBytes(attachedFileName, attachedFileBytes);
                            //adjunta los anexos
                            PdfFileSpecification pfs = PdfFileSpecification.FileEmbedded(write, attachedFileName, fileArray.GetAsString(key).ToString(), null);
                            write.AddFileAttachment(pfs);
                            //borramos los archivos extraidos
                            System.IO.File.Delete(attachedFileName);
                        }
                    }
                }
            }
        }
Exemple #6
0
// ---------------------------------------------------------------------------

        /**
         * Creates the PDF.
         * @return the bytes of a PDF file.
         */
        public byte[] CreatePdf()
        {
            IEnumerable <Movie> movies = PojoFactory.GetMovies(1);

            using (MemoryStream ms = new MemoryStream()) {
                using (Document document = new Document()) {
                    PdfWriter writer = PdfWriter.GetInstance(document, ms);
                    document.Open();
                    document.Add(new Paragraph(
                                     "'Stanley Kubrick: A Life in Pictures'"
                                     + " is a documentary about Stanley Kubrick and his films:"
                                     ));
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("<movies>");
                    List list = new List(List.UNORDERED, 20);
                    foreach (Movie movie in movies)
                    {
                        sb.AppendLine("<movie>");
                        sb.AppendLine(String.Format(
                                          "<title>{0}</title>",
                                          XMLUtil.EscapeXML(movie.MovieTitle, true)
                                          ));
                        sb.AppendLine(String.Format("<year>{0}</year>", movie.Year));
                        sb.AppendLine(String.Format(
                                          "<duration>{0}</duration>", movie.Duration
                                          ));
                        sb.AppendLine("</movie>");
                        ListItem item = new ListItem(movie.MovieTitle);
                        list.Add(item);
                    }
                    document.Add(list);
                    sb.Append("</movies>");
                    PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(
                        writer, null, "kubrick.xml", Encoding.UTF8.GetBytes(sb.ToString())
                        //txt.toByteArray()
                        );
                    writer.AddFileAttachment(fs);
                }
                return(ms.ToArray());
            }
        }
Exemple #7
0
// ---------------------------------------------------------------------------
        public void Write(Stream stream)
        {
            // step 1
            using (Document document = new Document()) {
                // step 2
                PdfWriter writer = PdfWriter.GetInstance(document, stream);
                // step 3
                document.Open();
                // step 4
                Image img = Image.GetInstance(IMG_BOX);
                document.Add(img);
                List           list = new List(List.UNORDERED, 20);
                PdfDestination dest = new PdfDestination(PdfDestination.FIT);
                dest.AddFirst(new PdfNumber(1));
                IEnumerable <Movie> box = PojoFactory.GetMovies(1)
                                          .Concat(PojoFactory.GetMovies(4))
                ;
                foreach (Movie movie in box)
                {
                    if (movie.Year > 1960)
                    {
                        PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(
                            writer, null,
                            String.Format("kubrick_{0}.pdf", movie.Imdb),
                            CreateMoviePage(movie)
                            );
                        fs.AddDescription(movie.Title, false);
                        writer.AddFileAttachment(fs);
                        ListItem            item   = new ListItem(movie.MovieTitle);
                        PdfTargetDictionary target = new PdfTargetDictionary(true);
                        target.EmbeddedFileName = movie.Title;
                        PdfAction action = PdfAction.GotoEmbedded(null, target, dest, true);
                        Chunk     chunk  = new Chunk(" (see info)");
                        chunk.SetAction(action);
                        item.Add(chunk);
                        list.Add(item);
                    }
                }
                document.Add(list);
            }
        }
        public void Write(Stream stream, string[] pfade)
        {
            using (Document document = new Document())
            {
                PdfWriter writer = PdfWriter.GetInstance(document, stream);

                document.Open();
                document.Add(new Paragraph(" "));

                PdfIndirectReference parentFolderObjectReference = writer.PdfIndirectReference;

                PdfCollection       collection = new PdfCollection(PdfCollection.DETAILS);
                PdfCollectionSchema schema     = CollectionSchema();
                collection.Schema = schema;
                collection.Sort   = new PdfCollectionSort(keys);
                collection.Put(new PdfName("Vorlagen BA"), parentFolderObjectReference);
                writer.Collection = collection;

                PdfFileSpecification fs;
                PdfCollectionItem    item;

                int nummer = 1;

                foreach (string pfad in pfade)
                {
                    String Filename = Path.GetFileName(pfad);
                    fs   = PdfFileSpecification.FileEmbedded(writer, pfad, string.Format("{0} - {1}", nummer, Filename), null);
                    item = new PdfCollectionItem(schema);
                    item.AddItem("Type", "pdf");
                    fs.AddCollectionItem(item);
                    fs.AddDescription(GetDescription(Filename), false);
                    writer.AddFileAttachment(fs);

                    nummer++;
                }

                document.Close();
            }
        }
Exemple #9
0
// ---------------------------------------------------------------------------
        public void Write(Stream stream)
        {
            // step 1
            using (Document document = new Document()) {
                // step 2
                PdfWriter writer = PdfWriter.GetInstance(document, stream);
                // step 3
                document.Open();


                // step 4
                PdfCollection       collection = new PdfCollection(PdfCollection.HIDDEN);
                PdfCollectionSchema schema     = _collectionSchema();
                collection.Schema = schema;
                PdfCollectionSort sort = new PdfCollectionSort(KEYS);
                collection.Sort   = sort;
                writer.Collection = collection;

                PdfCollectionItem    collectionitem = new PdfCollectionItem(schema);
                PdfFileSpecification fs             = PdfFileSpecification.FileEmbedded(
                    writer, IMG_KUBRICK, "kubrick.jpg", null
                    );
                fs.AddDescription("Stanley Kubrick", false);
                collectionitem.AddItem(TYPE_FIELD, "JPEG");
                fs.AddCollectionItem(collectionitem);
                writer.AddFileAttachment(fs);

                Image img = Image.GetInstance(IMG_BOX);
                document.Add(img);
                List           list = new List(List.UNORDERED, 20);
                PdfDestination dest = new PdfDestination(PdfDestination.FIT);
                dest.AddFirst(new PdfNumber(1));
                PdfTargetDictionary intermediate;
                PdfTargetDictionary target;
                Chunk     chunk;
                ListItem  item;
                PdfAction action = null;

                IEnumerable <Movie> box = PojoFactory.GetMovies(1)
                                          .Concat(PojoFactory.GetMovies(4))
                ;
                StringBuilder sb = new StringBuilder();
                foreach (Movie movie in box)
                {
                    if (movie.Year > 1960)
                    {
                        sb.AppendLine(String.Format(
                                          "{0};{1};{2}", movie.MovieTitle, movie.Year, movie.Duration
                                          ));
                        item = new ListItem(movie.MovieTitle);
                        if (!"0278736".Equals(movie.Imdb))
                        {
                            target = new PdfTargetDictionary(true);
                            target.EmbeddedFileName          = movie.Title;
                            intermediate                     = new PdfTargetDictionary(true);
                            intermediate.FileAttachmentPage  = 1;
                            intermediate.FileAttachmentIndex = 1;
                            intermediate.AdditionalPath      = target;
                            action = PdfAction.GotoEmbedded(null, intermediate, dest, true);
                            chunk  = new Chunk(" (see info)");
                            chunk.SetAction(action);
                            item.Add(chunk);
                        }
                        list.Add(item);
                    }
                }
                document.Add(list);

                fs = PdfFileSpecification.FileEmbedded(
                    writer, null, "kubrick.txt",
                    Encoding.UTF8.GetBytes(sb.ToString())
                    );
                fs.AddDescription("Kubrick box: the movies", false);
                collectionitem.AddItem(TYPE_FIELD, "TXT");
                fs.AddCollectionItem(collectionitem);
                writer.AddFileAttachment(fs);

                PdfPTable table = new PdfPTable(1);
                table.SpacingAfter = 10;
                PdfPCell cell = new PdfPCell(new Phrase("All movies by Kubrick"));
                cell.Border = PdfPCell.NO_BORDER;
                fs          = PdfFileSpecification.FileEmbedded(
                    writer, null, KubrickMovies.FILENAME,
                    Utility.PdfBytes(new KubrickMovies())
                    //new KubrickMovies().createPdf()
                    );
                collectionitem.AddItem(TYPE_FIELD, "PDF");
                fs.AddCollectionItem(collectionitem);
                target = new PdfTargetDictionary(true);
                target.FileAttachmentPagename = "movies";
                target.FileAttachmentName     = "The movies of Stanley Kubrick";
                cell.CellEvent = new PdfActionEvent(
                    writer, PdfAction.GotoEmbedded(null, target, dest, true)
                    );
                cell.CellEvent = new FileAttachmentEvent(
                    writer, fs, "The movies of Stanley Kubrick"
                    );
                cell.CellEvent = new LocalDestinationEvent(writer, "movies");
                table.AddCell(cell);
                writer.AddFileAttachment(fs);

                cell        = new PdfPCell(new Phrase("Kubrick DVDs"));
                cell.Border = PdfPCell.NO_BORDER;
                fs          = PdfFileSpecification.FileEmbedded(
                    writer, null,
                    KubrickDvds.RESULT, new KubrickDvds().CreatePdf()
                    );
                collectionitem.AddItem(TYPE_FIELD, "PDF");
                fs.AddCollectionItem(collectionitem);
                cell.CellEvent = new FileAttachmentEvent(writer, fs, "Kubrick DVDs");
                table.AddCell(cell);
                writer.AddFileAttachment(fs);

                cell        = new PdfPCell(new Phrase("Kubrick documentary"));
                cell.Border = PdfPCell.NO_BORDER;
                fs          = PdfFileSpecification.FileEmbedded(
                    writer, null,
                    KubrickDocumentary.RESULT, new KubrickDocumentary().CreatePdf()
                    );
                collectionitem.AddItem(TYPE_FIELD, "PDF");
                fs.AddCollectionItem(collectionitem);
                cell.CellEvent = new FileAttachmentEvent(
                    writer, fs, "Kubrick Documentary"
                    );
                table.AddCell(cell);
                writer.AddFileAttachment(fs);

                document.NewPage();
                document.Add(table);
            }
        }
Exemple #10
0
        public void GerarPdf()
        {
            var       doc1     = new Document(PageSize.A4, 40.0f, 20.0f, 30.0f, 30.0f);//Margens - Margem direita precisa ser 20 para poder caber valores acima de R$ 100.000,00 nas contratações
            string    filename = null;
            PdfWriter writer   = null;

            try
            {
                SaveFileDialog saveFileDialog1 = new SaveFileDialog
                {
                    InitialDirectory = PdfFolder,
                    Filter           = "Arquivo PDF|*.pdf",
                    Title            = "Salvar como",
                    FileName         = Cota.Cliente + ".pdf"
                };
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    if (saveFileDialog1.FileName != "")
                    {
                        filename = saveFileDialog1.FileName;
                        writer   = PdfWriter.GetInstance(doc1, new FileStream(saveFileDialog1.FileName, FileMode.Create));
                        Relatório.SalvaUtilizacao(Cota);
                    }
                }
                else
                {
                    return;
                }

                Home.preferencias.PastaPDF = saveFileDialog1.FileName.Substring(0, saveFileDialog1.FileName.LastIndexOf('\\') + 1);
                WebFile.Prefs = Home.preferencias;
            }
            catch (IOException)
            {
                Relatório.AdicionarAoRelatorio("Há um arquivo de mesmo nome aberto");
                MessageBox.Show("Não foi possível criar o arquivo PDF,\r\nverifique se há um arquivo de mesmo nome aberto.\r\nFeche-o e tente novamente.",
                                "Carta de Cotação",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }

            doc1.Open();
            iTextSharp.text.Font normal = FontFactory.GetFont("Helvetica", 11);

            iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(ConverteImageParaByteArray(Properties.Resources.Bragaseg));
            jpg.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
            jpg.ScaleToFit(250f, 250f);
            //jpg.SetAbsolutePosition(500f, 750f);

            //Como colocar marca d'água:
            //jpg.SetAbsolutePosition(doc1.PageSize.Width - 500f, 750f);
            //jpg.Rotation = (float)Math.PI / 2;
            //jpg.RotationDegrees = 90f;

            doc1.Add(jpg);

            doc1.Add(new Paragraph("\r\n", normal));
            Paragraph pfcity = new Paragraph("Passo Fundo, " + DataPorExtenso(Cota.Data) + ".", normal);

            //pfcity.Alignment = iTextSharp.text.Image.ALIGN_RIGHT;
            //pfcity.IndentationLeft = 230;
            doc1.Add(pfcity);
            doc1.Add(new Paragraph("\r\n", normal));
            if (Home.excedeuLinhas)
            {
                doc1.Add(new Paragraph("A " + Cota.Cliente, normal));
            }
            else
            {
                doc1.Add(new Paragraph("A", normal));
                doc1.Add(new Paragraph(Cota.Cliente, normal));
            }
            doc1.Add(new Paragraph("\r\n", normal));
            doc1.Add(new Paragraph("Estamos encaminhando a cotação do veículo abaixo:", normal));
            doc1.Add(new Paragraph(Cota.Marca + " - " + Cota.Modelo, normal));
            doc1.Add(new Paragraph("Ano de fabricação: " + Cota.AnoFabricacao + "      Ano modelo: " + Cota.AnoModelo, normal));
            doc1.Add(new Paragraph("\r\n", normal));

            //Início das contratações:
            decimal        valorfipecont = Cota.ValorFipe * Cota.PorContratada / 100m;
            List <string>  contrat       = new List <string>();
            List <decimal> listvalores   = new List <decimal>();

            if (Cota.Rcf != true)
            {
                if (Cota.Vd != true)
                {
                    contrat.Add("Casco - " + Cota.PorContratada + "% da Fipe:");
                }
                else
                {
                    contrat.Add("Valor Determinado:");
                }
                listvalores.Add(valorfipecont);
            }
            else
            {
                contrat.Add("Sem casco contratado");
                listvalores.Add(-1.0m);
            }

            contrat.Add("Danos Materiais:");
            listvalores.Add(Cota.DanosMateriais);

            contrat.Add("Danos Corporais:");
            listvalores.Add(Cota.DanosCorporais);

            contrat.Add("Danos Morais:");
            listvalores.Add(Cota.DanosMorais);

            if (Cota.Seguradora != "Itaú")
            {
                contrat.Add("APP Morte:");
            }
            else
            {
                contrat.Add("APP:");
            }
            listvalores.Add(Cota.APPMorte);

            //AQUI: ESSE NÃO APARECE SE FOR ITAÚ
            contrat.Add("APP Invalidez:");
            listvalores.Add(Cota.APPInvalidez);

            if (Cota.Tipo == FipeType.Caminhão)
            {
                contrat.Add("Equipamento:");
                listvalores.Add(Cota.Equipamento);

                contrat.Add("Carroceria:");
                listvalores.Add(Cota.Carroceria);
            }

            bool semdecimais = listvalores.Exists(d => d > 999999);

            PdfPTable valores = new PdfPTable(5);

            valores.HorizontalAlignment = 0;
            float[] widthvalores = { 45f, 30f, 9f, 40f, 30f };
            valores.SetWidths(widthvalores);
            valores.DefaultCell.BorderColor = iTextSharp.text.BaseColor.WHITE;

            int c    = 0;  //contador de valores não zero na listvalores
            int n    = 0;  //num linhas
            int MODO = 0;  //<--MODO 0 divide os itens entre as colunas 1 e 2

            if (MODO == 0) //MODO 1 sempre preenche a coluna 1 inteira (3 itens ou 4 se caminhão) e depois preenche a coluna 2
            {
                foreach (decimal d in listvalores)
                {
                    if (d != 0.0m)
                    {
                        c++;
                        if (c % 2 != 0)
                        {
                            n++;
                        }
                    }
                }
            }
            else
            {
                n = 3;//num linhas se não caminhão
                if (Cota.Tipo == FipeType.Caminhão)
                {
                    n = 4;//num linhas se caminhão
                }
            }

            int[] col1 = new int[] { -1, -1, -1, -1 }; //posições na coluna 1, inicializa com -1 = não preenchido
            int[] col2 = new int[] { -1, -1, -1, -1 }; //posições na coluna 2, inicializa com -1 = não preenchido

            c = 0;                                     //reinicia contador
            int i = 0;                                 //contador de índice da listvalores

            foreach (decimal d in listvalores)
            {
                if (d != 0.0m)
                {
                    if (c < n)       //preenchimento da coluna 1
                    {
                        col1[c] = i; //guarda a posição de d na listvalores e contrat
                    }
                    else//preenchimento da coluna 2, após coluna 1 estar cheia
                    {
                        col2[c - n] = i;//guarda a posição de d na listvalores e contrat, c - n porque o índice deve iniciar no zero
                    }
                    c++;
                }
                i++;
            }

            for (i = 0; i < n; i++)
            {
                if (col1[i] != -1)                                         //testa se a posição na coluna 1 tem valor a ser preenchido
                {
                    valores.AddCell(new Phrase(contrat[col1[i]], normal)); //preenche com a string de contrat na posição guardada em col1

                    if (listvalores[col1[i]] != -1.0m)                     // testa se é o caso "sem casco"
                    {
                        if (!semdecimais)
                        {
                            valores.AddCell(new Phrase(listvalores[col1[i]].ToString("C2", CultureInfo.CurrentCulture)));//converte valor para string
                        }
                        else
                        {
                            valores.AddCell(new Phrase(listvalores[col1[i]].ToString("C0", CultureInfo.CurrentCulture)));//converte valor para string
                        }
                    }
                    else
                    {
                        valores.AddCell(new Phrase("", normal)); //se for "sem casco" preenche com vazio
                    }
                    valores.AddCell(new Phrase("", normal));     //preenche a coluna do meio com vazio
                }

                if (col2[i] != -1)                                         //testa se a posição na coluna 2 tem valor a ser preenchido
                {
                    valores.AddCell(new Phrase(contrat[col2[i]], normal)); //preenche com a string de contrat na posição guardada em col2
                    // como "sem casco" nunca vai cair na coluna 2, não precisa testar
                    if (!semdecimais)
                    {
                        valores.AddCell(new Phrase(listvalores[col2[i]].ToString("C2", CultureInfo.CurrentCulture)));//converte valor para string
                    }
                    else
                    {
                        valores.AddCell(new Phrase(listvalores[col2[i]].ToString("C0", CultureInfo.CurrentCulture)));//converte valor para string
                    }
                }
                else
                {
                    valores.AddCell(new Phrase("", normal)); //se a posição na coluna 2 não tem valor, preenche com vazio
                    valores.AddCell(new Phrase("", normal)); //idem acima para o valor
                }
            }
            doc1.Add(valores);
            //Fim das contratações

            int colunas = 3;
            if (Cota.Seguradora == "Bradesco" || Cota.Seguradora == "Generale" || (Cota.Seguradora == "Mapfre" && Cota.DebitoBB == true))
            {
                colunas = 2;
            }
            float[] width  = { 15f, 15f, 15f };
            float[] width2 = { 15f, 15f };

            //Tabela Franquia Básica
            if (Cota.FranquiaBasica + Cota.ValFranqBasicaAVista != 0)
            {
                PdfPTable table = new PdfPTable(colunas);

                if (colunas == 3)
                {
                    table.SetWidths(width);
                }
                else
                {
                    table.SetWidths(width2);
                }
                table.HorizontalAlignment = 0;
                PdfPCell cell = new PdfPCell(new Phrase(""));
                cell.Colspan             = 1;
                cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
                table.AddCell(cell);
                doc1.Add(new Paragraph("\r\n", normal));
                if (Cota.Rcf != true)
                {
                    doc1.Add(new Paragraph("Franquia básica: " + Cota.FranquiaBasica.ToString("C2", CultureInfo.CurrentCulture), normal));
                    doc1.Add(new Paragraph("\r\n", normal));
                }

                if (Cota.Seguradora == "Mapfre" && Cota.DebitoBB)
                {
                    table.AddCell(new Phrase("Débito", normal));
                }
                else
                {
                    table.AddCell(new Phrase("Carnê", normal));
                }

                if (colunas != 2)
                {
                    if (Cota.Seguradora == "Sul América")
                    {
                        table.AddCell(new Phrase("Débito BB", normal));
                    }
                    else
                    {
                        table.AddCell(new Phrase("Débito", normal));
                    }
                }

                foreach (Parcelamento parc in Cota.TabelaParcelamento.FindAll(p => (p.TipoFranq == "Básica" && !(p.Seguradora == "Bradesco" && p.FormaPagto == "Débito")) && /* ADICIONADO */ !(p.Seguradora == "Generale" && p.FormaPagto == "Débito") && (p.TipoFranq == "Básica" && !(p.Seguradora == "Mapfre" && p.FormaPagto == "Carnê" && Cota.DebitoBB == true))))
                {
                    if (parc.FormaPagto == "Carnê" || (parc.FormaPagto == "Débito" && Cota.DebitoBB && parc.ValParcela != 0.0m))
                    {
                        table.AddCell(new Phrase(parc.Descricao.ToString(), normal));
                    }

                    if (parc.ValParcela == 0.0m)
                    {
                        table.AddCell(new Phrase("", normal));
                    }
                    else
                    {
                        table.AddCell(new Phrase(parc.ValParcela.ToString("C2", CultureInfo.CurrentCulture), normal));
                    }
                }
                doc1.Add(table);
            }
            //Tabela Franquia Reduzida
            if (Cota.FranquiaReduzida + Cota.ValFranqReduzidaAVista != 0.0m && Cota.Rcf != true)
            {
                PdfPTable table2 = new PdfPTable(colunas);
                if (colunas == 3)
                {
                    table2.SetWidths(width);
                }
                else
                {
                    table2.SetWidths(width2);
                }
                table2.HorizontalAlignment = 0;
                PdfPCell cell2 = new PdfPCell(new Phrase(""))
                {
                    Colspan             = 1,
                    HorizontalAlignment = 1
                };
                //0=Left, 1=Centre, 2=Right
                table2.AddCell(cell2);
                doc1.Add(new Paragraph("\r\n"));
                doc1.Add(new Paragraph("Franquia reduzida: " + Cota.FranquiaReduzida.ToString("C2", CultureInfo.CurrentCulture), normal));
                doc1.Add(new Paragraph("\r\n"));

                if (Cota.Seguradora == "Mapfre" && Cota.DebitoBB)
                {
                    table2.AddCell(new Phrase("Débito", normal));
                }
                else
                {
                    table2.AddCell(new Phrase("Carnê", normal));
                }

                if (colunas != 2)
                {
                    if (Cota.Seguradora == "Sul América")
                    {
                        table2.AddCell(new Phrase("Débito BB", normal));
                    }
                    else
                    {
                        table2.AddCell(new Phrase("Débito", normal));
                    }
                }

                foreach (Parcelamento parc in Cota.TabelaParcelamento.FindAll(p => (p.TipoFranq == "Reduzida" && !(p.Seguradora == "Bradesco" && p.FormaPagto == "Débito")) && /* ADICIONADO */ !(p.Seguradora == "Generale" && p.FormaPagto == "Débito") && (p.TipoFranq == "Reduzida" && !(p.Seguradora == "Mapfre" && p.FormaPagto == "Carnê" && Cota.DebitoBB == true))))
                {
                    if (parc.FormaPagto == "Carnê" || (parc.FormaPagto == "Débito" && Cota.DebitoBB && parc.ValParcela != 0.0m))
                    {
                        table2.AddCell(new Phrase(parc.Descricao.ToString(), normal));
                    }

                    if (parc.ValParcela == 0.0m)
                    {
                        table2.AddCell(new Phrase("", normal));
                    }
                    else
                    {
                        table2.AddCell(new Phrase(parc.ValParcela.ToString("C2", CultureInfo.CurrentCulture), normal));
                    }
                }
                doc1.Add(table2);
            }
            //Final Tabelas

            doc1.Add(new Paragraph("\r\n", normal));
            doc1.Add(new Paragraph(Cota.Observacoes, normal));

            if (Cota.MostrarValidade == true)
            {
                string textovalidade = "*Validade da cotação: " + Cota.Validade.ToShortDateString();
                doc1.Add(new Paragraph(textovalidade, normal));
            }

            doc1.Add(new Paragraph("\r\n", normal));
            iTextSharp.text.Font negrito = FontFactory.GetFont("Helvetica", 11, iTextSharp.text.Font.BOLD);

            //Testes das exibições

            /*if (Cota.NomeClaudio == true)
             *  exib += "1";
             * else
             *  exib += "0";
             *
             * if (Cota.CelClaudio == true)
             *  exib += "1";
             * else
             *  exib += "0";
             *
             * if (Cota.NomeFuncionario == true && Cota.Funcionario != "")
             *  exib += "1";
             * else
             *  exib += "0";
             *
             * switch (exib)
             * {
             *  case "001":
             *      doc1.Add(new Paragraph(Cota.Funcionario, negrito));
             *      break;
             *  case "010":
             *      doc1.Add(new Paragraph("(54) 9981-4797", negrito));
             *      break;
             *  case "011":
             *      doc1.Add(new Paragraph("(54) 9981-4797 / " + Cota.Funcionario, negrito));
             *      break;
             *  case "100":
             *      doc1.Add(new Paragraph("Cláudio Zanchet", negrito));
             *      break;
             *  case "101":
             *      doc1.Add(new Paragraph("Cláudio Zanchet / " + Cota.Funcionario, negrito));
             *      break;
             *  case "110":
             *      doc1.Add(new Paragraph("Cláudio Zanchet" + " - (54) 9981-4797", negrito));
             *      break;
             *  case "111":
             *      doc1.Add(new Paragraph("Cláudio Zanchet" + " - (54) 9981-4797 / " + Cota.Funcionario, negrito));
             *      break;
             * }*/
            //Fim dos testes das exibições
            doc1.Add(new Paragraph(Cota.Funcionario, negrito));

            if (Cota.NomeFuncionario)
            {
                doc1.Add(new Paragraph("Bragaseg Corretora de Seguros", normal));
            }
            else
            {
                doc1.Add(new Paragraph("Bragaseg Corretora de Seguros", negrito));
            }
            doc1.Add(new Paragraph("Rua Uruguai, 1763 - Bairro Centro", normal));
            doc1.Add(new Paragraph("Passo Fundo - RS    CEP: 99010-112", normal));
            doc1.Add(new Paragraph("Telefone: (54) 3045-5300", normal));

            doc1.AddCreator("Carta de Cotação");
            File.Create(WebFile.AppData + "TempFill.bin").Close();
            WebFile.Serialize(Cota.Preenchimento, WebFile.AppData + "TempFill.bin");
            PdfFileSpecification pfs = PdfFileSpecification.FileEmbedded(writer, WebFile.AppData + "TempFill.bin", "TempFill.bin", null);
            writer.AddFileAttachment(pfs);
            doc1.Close();
            File.Delete(WebFile.AppData + "TempFill.bin");

            if (MessageBox.Show("Arquivo PDF gerado com sucesso!\r\nVocê deseja visualizá-lo agora?", "Carta de Cotação", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
            {
                Process.Start(filename);
            }
        }
Exemple #11
0
        static void Main(string[] args)
        {
            int
                MaxCell;

            string
                CurrentDirectory = System.IO.Directory.GetCurrentDirectory();

            CurrentDirectory = CurrentDirectory.Substring(0, CurrentDirectory.LastIndexOf("bin", CurrentDirectory.Length - 1));

            string
                OutputFileName = CurrentDirectory + "wdpt.pdf",
                ImageName      = CurrentDirectory + "TestImage.jpg";

            Document
                pdfDocument = new Document(PageSize.A4);

            PdfWriter
                writer = PdfWriter.GetInstance(pdfDocument, new FileStream(OutputFileName, FileMode.Create));

            pdfDocument.Open();

            Phrase
                phrase = new Phrase(DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + " GMT", new Font(Font.FontFamily.COURIER, 8));

            Rectangle
                page = pdfDocument.PageSize;

            PdfPTable
                head = new PdfPTable(1);

            head.TotalWidth = page.Width;

            PdfPCell
                cell = new PdfPCell(phrase);

            cell.Border              = Rectangle.NO_BORDER;
            cell.VerticalAlignment   = Element.ALIGN_TOP;
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            head.AddCell(cell);
            head.WriteSelectedRows(
                // first/last row; -1 writes all rows
                0, -1,
                // left offset
                0,
                // ** bottom** yPos of the table
                page.Height - pdfDocument.TopMargin + head.TotalHeight + 20,
                writer.DirectContent
                );

            pdfDocument.Add(new Paragraph("Here is a test of creating a PDF"));

            Paragraph
                p = new Paragraph();

            Font
                font = FontFactory.GetFont("Times New Roman", 16, Font.NORMAL);

            p.Font = font;
            p.Add("Times New Roman");
            pdfDocument.Add(p);

            Chunk
                c = new Chunk("Times New Roman", FontFactory.GetFont("Times New Roman", 16));

            c.SetCharacterSpacing(10);
            p = new Paragraph(c);
            pdfDocument.Add(p);

            BaseFont
                bfComic = BaseFont.CreateFont("c:\\windows\\fonts\\comic.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

            font = new Font(bfComic, 12);
            pdfDocument.Add(new Paragraph("Some cyrillic characters: \u0418\u044f", font));

            c = new Chunk("Some text in Verdana \n", FontFactory.GetFont("Verdana", 12));

            Chunk
                c2 = new Chunk("More text in Tahoma", FontFactory.GetFont("Tahoma", 14));

            p = new Paragraph();
            p.Add(c);
            p.Add(c2);
            pdfDocument.Add(p);

            Image
                image = Image.GetInstance(ImageName);

            c = new Chunk("Check out this wicked graphic: \n", FontFactory.GetFont("Verdana", 12));
            p = new Paragraph();
            p.Add(c);
            p.Add(image);
            pdfDocument.Add(p);

            PdfPTable
                table = new PdfPTable(3);

            cell                     = new PdfPCell(new Phrase("Header spanning 3 columns"));
            cell.Colspan             = 3;
            cell.HorizontalAlignment = 1;             //0=Left, 1=Centre, 2=Right
            table.AddCell(cell);
            table.AddCell("Col 1 Row 1");
            table.AddCell("Col 2 Row 1");
            table.AddCell("Col 3 Row 1");
            table.AddCell("Col 1 Row 2");
            table.AddCell("Col 2 Row 2");
            table.AddCell("Col 3 Row 2");
            pdfDocument.Add(table);

            table = new PdfPTable(2);
            //actual width of table in points
            table.TotalWidth = 216f;
            //fix the absolute width of the table
            table.LockedWidth = true;

            //relative col widths in proportions - 1/3 and 2/3
            float[] widths = new float[] { 1f, 2f };
            table.SetWidths(widths);
            table.HorizontalAlignment = 0;
            //leave a gap before and after the table
            table.SpacingBefore = 20f;
            table.SpacingAfter  = 30f;

            cell                     = new PdfPCell(new Phrase("Products"));
            cell.Colspan             = 2;
            cell.Border              = 0;
            cell.HorizontalAlignment = 1;
            table.AddCell(cell);

            string
            //connect = "Server=NOZHENKO-PC\\SQLEXPRESS;database=testdb;Integrated Security=SSPI";
                connect = "Server=nozhenko-s8k;Database=testdb;Trusted_Connection=True;";

            using (SqlConnection conn = new SqlConnection(connect))
            {
                string
                    query = "SELECT ID, Name FROM Staff";

                SqlCommand
                    cmd = new SqlCommand(query, conn);

                try
                {
                    conn.Open();
                    using (SqlDataReader rdr = cmd.ExecuteReader())
                    {
                        BaseFont
                            baseFont = BaseFont.CreateFont("c:\\windows\\fonts\\arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

                        font = new iTextSharp.text.Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.NORMAL);

                        while (rdr.Read())
                        {
                            table.AddCell(rdr[0].ToString());
                            table.AddCell(new Paragraph(rdr[1].ToString(), font));
                        }
                    }
                }
                catch (Exception eException)
                {
                    Console.WriteLine(eException.GetType().FullName + Environment.NewLine + "Message: " + eException.Message + Environment.NewLine + "StackTrace:" + Environment.NewLine + eException.StackTrace);
                }

                pdfDocument.Add(table);
            }

            table = new PdfPTable(3);

            cell        = new PdfPCell();
            cell.Phrase = new Phrase("Cell 1");
            cell.Image  = Image.GetInstance(CurrentDirectory + "pdf.gif");
            table.AddCell(cell);

            cell = new PdfPCell(new Phrase("Cell 2", new Font(Font.FontFamily.HELVETICA, 8f, Font.NORMAL, BaseColor.YELLOW)));
            cell.BackgroundColor   = new BaseColor(0, 150, 0);
            cell.BorderColor       = new BaseColor(255, 242, 0);
            cell.Border            = Rectangle.BOTTOM_BORDER | Rectangle.TOP_BORDER;
            cell.BorderWidthBottom = 3f;
            cell.BorderWidthTop    = 3f;
            cell.PaddingBottom     = 10f;
            cell.PaddingLeft       = 20f;
            cell.PaddingTop        = 4f;
            table.AddCell(cell);
            table.AddCell("Cell 3");
            pdfDocument.Add(table);

            table             = new PdfPTable(4);
            table.TotalWidth  = 400f;
            table.LockedWidth = true;

            PdfPCell
                header = new PdfPCell(new Phrase("Header"));

            header.Colspan = 4;
            table.AddCell(header);
            table.AddCell("Cell 1");
            table.AddCell("Cell 2");
            table.AddCell("Cell 3");
            table.AddCell("Cell 4");

            PdfPTable
                nested = new PdfPTable(1);

            nested.AddCell("Nested Row 1");
            nested.AddCell("Nested Row 2");
            nested.AddCell("Nested Row 3");

            PdfPCell
                nesthousing = new PdfPCell(nested);

            nesthousing.Padding = 0f;
            table.AddCell(nesthousing);

            PdfPCell
                bottom = new PdfPCell(new Phrase("bottom"));

            bottom.Colspan = 3;
            table.AddCell(bottom);
            pdfDocument.Add(table);

            table                     = new PdfPTable(3);
            table.TotalWidth          = 144f;
            table.LockedWidth         = true;
            table.HorizontalAlignment = 0;

            PdfPCell
                left = new PdfPCell(new Paragraph("Rotated"));

            left.Rotation = 90;
            table.AddCell(left);

            PdfPCell
                middle = new PdfPCell(new Paragraph("Rotated"));

            middle.Rotation = -90;
            table.AddCell(middle);
            table.AddCell("Not Rotated");
            pdfDocument.Add(table);

            string
                text = "This is a paragraph. It is represted" +
                       " by a Paragraph object in the iTextSharp " +
                       "library. Here, we're creating paragraphs with " +
                       "various styles in order to test out iTextSharp." +
                       " This paragraph will take up multiple lines " +
                       "and allow for a more complete example.";

            // Add a basic paragraph
            pdfDocument.Add(new Paragraph(text));


            // Add a paragraph that's underlined and indented
            Paragraph
                p2 = new Paragraph(text);

            p2.IndentationLeft = 36;
            p2.Font.SetStyle(Font.UNDERLINE);
            pdfDocument.Add(p2);

            // Add a paragraph that's underlined and in bold
            pdfDocument.Add(new Paragraph(text, FontFactory.GetFont("Courier", Font.DEFAULTSIZE, Font.UNDERLINE | Font.BOLD)));

            // Add a really big paragraph
            pdfDocument.Add(new Paragraph(text, new Font(Font.FontFamily.HELVETICA, 36)));

            // Add a green, centered paragraph
            Paragraph
                p5 = new Paragraph(text, new Font(Font.FontFamily.TIMES_ROMAN, Font.DEFAULTSIZE, Font.NORMAL, BaseColor.GREEN));

            p5.Alignment = Element.ALIGN_CENTER;
            pdfDocument.Add(p5);

            // Add a double-spaced paragraph with
            // an indented first line
            Paragraph
                p6 = new Paragraph(text);

            p6.FirstLineIndent   = 36;
            p6.MultipliedLeading = 2;
            pdfDocument.Add(p6);

            // Add a paragraph with multiple styles
            // Each word gets bigger
            Paragraph
                ascending = new Paragraph();

            ascending.SpacingBefore = 72;
            for (int i = 1; i <= 5; i++)
            {
                ascending.Add(new Chunk("Hello", new Font(Font.FontFamily.HELVETICA, i * 5)));
            }
            pdfDocument.Add(ascending);

            Paragraph
                hello = new Paragraph("Hello. This is a paragraph.");

            hello.Font.SetStyle(Font.ITALIC);
            pdfDocument.Add(hello);

            Paragraph
                fancy = new Paragraph();

            Chunk
                bold = new Chunk("This ");

            bold.Font.SetStyle(Font.BOLD);
            fancy.Add(bold);

            Chunk
                italics = new Chunk("is a");

            italics.Font.SetStyle(Font.ITALIC);
            fancy.Add(italics);

            Chunk
                big = new Chunk("fancy");

            big.Font.Size = 20;
            big.Font.SetStyle(Font.BOLD);
            fancy.Add(big);

            Chunk
                struck = new Chunk("paragraph.");

            struck.Font.SetStyle(Font.STRIKETHRU);
            fancy.Add(struck);
            pdfDocument.Add(fancy);

            Paragraph
                spaced = new Paragraph("This has a lot of space around it.");

            spaced.SpacingBefore    = 72;
            spaced.SpacingAfter     = 72;
            spaced.IndentationLeft  = 72;
            spaced.IndentationRight = 72;
            pdfDocument.Add(spaced);

            p = new Paragraph("p.FirstLineIndent = 36");
            p.FirstLineIndent = 36;
            pdfDocument.Add(p);

            p           = new Paragraph("p.Alignment = Element.ALIGN_JUSTIFIED;");
            p.Alignment = Element.ALIGN_LEFT;
            p.Alignment = Element.ALIGN_CENTER;
            p.Alignment = Element.ALIGN_RIGHT;
            p.Alignment = Element.ALIGN_JUSTIFIED;
            pdfDocument.Add(p);

            Paragraph
                spacy = new Paragraph();

            spacy.Leading = 72;
            pdfDocument.Add(spacy);

            Paragraph
                spacy2 = new Paragraph(72);

            Paragraph
                spacy3 = new Paragraph(72, "The leading is an inch.");

            pdfDocument.Add(spacy2);
            pdfDocument.Add(spacy3);

            Paragraph
                doubleSpaced = new Paragraph("doubleSpaced.MultipliedLeading = 2");

            doubleSpaced.MultipliedLeading = 2;
            pdfDocument.Add(doubleSpaced);

            Chunk
                boo = new Chunk("Boo!");

            boo.Font.SetStyle(Font.BOLD);
            boo.Font.Size = 72;
            boo.Font.SetStyle("bold");

            Font
                small = new Font(Font.FontFamily.TIMES_ROMAN, 5);

            Chunk
                smallText = new Chunk("This is small.", small);

            Font
                redItalic = new Font(Font.FontFamily.HELVETICA, Font.DEFAULTSIZE, Font.ITALIC, BaseColor.RED);

            Chunk
                hey = new Chunk("Hey.", FontFactory.GetFont("Courier", 12, Font.ITALIC));

            table = new PdfPTable(3);
            table.AddCell(new PdfPCell(new Phrase("Cell# 1")));
            table.AddCell(new PdfPCell(new Phrase("Cell# 2")));
            table.AddCell(new PdfPCell(new Phrase("Cell# 3")));
            pdfDocument.Add(table);

            #if TEST_ATTACHMENTS
            PdfFileSpecification
                pdfFileSpecification = PdfFileSpecification.FileEmbedded(writer, ImageName, Path.GetFileName(ImageName), null);

            writer.AddFileAttachment("Description", pdfFileSpecification);

            FileStream
                fs = File.OpenRead(ImageName);

            byte[]
            img = new byte[fs.Length];

            fs.Read(img, 0, img.Length);
            pdfFileSpecification = PdfFileSpecification.FileEmbedded(writer, ImageName, Path.GetFileName(ImageName), img);
            writer.AddFileAttachment("DescriptionDescription", pdfFileSpecification);
            #endif

            PdfContentByte
                pdfContentByte;

            float
                x,
                y;

            #if TEST_DIRECT_CONTENT
            pdfDocument.NewPage();

            pdfContentByte = writer.DirectContent;

            pdfContentByte.MoveTo(x = 400f, 0f);
            pdfContentByte.LineTo(x, page.Height);
            pdfContentByte.MoveTo(x = 300f, 0f);
            pdfContentByte.LineTo(x, page.Height);
            pdfContentByte.MoveTo(0f, y = 10f);
            pdfContentByte.LineTo(page.Width, y);
            pdfContentByte.MoveTo(0f, y = 50f);
            pdfContentByte.LineTo(page.Width, y);
            pdfContentByte.MoveTo(0f, y = 90f);
            pdfContentByte.LineTo(page.Width, y);
            pdfContentByte.MoveTo(0f, y = 130f);
            pdfContentByte.LineTo(page.Width, y);
            pdfContentByte.MoveTo(0f, y = 170f);
            pdfContentByte.LineTo(page.Width, y);
            pdfContentByte.MoveTo(0f, y = 600f);
            pdfContentByte.LineTo(page.Width, y);
            pdfContentByte.MoveTo(0f, y = 700f);
            pdfContentByte.LineTo(page.Width, y);
            pdfContentByte.Stroke();

            pdfContentByte.BeginText();
            pdfContentByte.SetFontAndSize(BaseFont.CreateFont(/*BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED*/), iTextSharp.text.Font.DEFAULTSIZE);
            pdfContentByte.ShowText("pdfContentByte.ShowText()");
            pdfContentByte.SetTextMatrix(x, 170f);
            pdfContentByte.ShowText("pdfContentByte.ShowText()");
            pdfContentByte.ShowText(string.Format("Width: {0}, Height: {1}", page.Width, page.Height));
            pdfContentByte.ShowTextAlignedKerned(PdfContentByte.ALIGN_RIGHT, "pdfContentByte.ShowTextAlignedKerned(RIGHT)", x, 130f, 0f);
            pdfContentByte.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "pdfContentByte.ShowTextAligned(RIGHT)", x, 90f, 0f);
            pdfContentByte.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "pdfContentByte.ShowTextAligned(CENTER)", x, 50f, 0f);
            pdfContentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "pdfContentByte.ShowTextAligned(LEFT)", x, 10f, 0f);

            pdfContentByte.SetTextMatrix(0, 1, -1, 0, 300, 600);
            pdfContentByte.ShowText("Position 300,600, rotated 90 degrees.");

            for (int i = 0; i < 360; i += 30)
            {
                pdfContentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Rotated Text", 400f, 700f, i);
            }

            pdfContentByte.EndText();
            #endif

            #if TEST_NESTED_TABLES
            pdfDocument.NewPage();

            table = new PdfPTable(3);
            for (int i = 0; i < 3; ++i)
            {
                nested           = new PdfPTable(1);
                cell             = new PdfPCell(new Phrase(i.ToString()));
                cell.BorderColor = BaseColor.RED;
                nested.AddCell(cell);
                nesthousing             = new PdfPCell(nested);
                nesthousing.BorderColor = BaseColor.BLUE;
                nesthousing.Padding     = 10;
                table.AddCell(nesthousing);
            }
            pdfDocument.Add(table);
            #endif

            #if TEST_LEADING
            pdfDocument.NewPage();

            table = new PdfPTable(10);
            cell  = new PdfPCell(new Paragraph("Quick brown fox jumps over the lazy dog.\nQuick brown fox jumps over the lazy dog."));
            table.AddCell("default leading / spacing");
            table.AddCell(cell);
            table.AddCell("absolute leading: 20");
            cell.SetLeading(20f, 0f);
            table.AddCell(cell);
            table.AddCell("absolute leading: 3; relative leading: 1.2");
            cell.SetLeading(3f, 1.2f);
            table.AddCell(cell);
            table.AddCell("absolute leading: 0; relative leading: 1.2");
            cell.SetLeading(0f, 1.2f);
            table.AddCell(cell);
            table.AddCell("no leading at all");
            cell.SetLeading(0f, 0f);
            table.AddCell(cell);
            pdfDocument.Add(table);
            #endif

            #if TEST_DIRECT_TEXT_IN_CELL
            pdfDocument.NewPage();

            table = new PdfPTable(MaxCell = 3);
            for (int i = 0; i < MaxCell; ++i)
            {
                cell = new PdfPCell(new Paragraph(i.ToString()));
                table.AddCell(cell);
            }
            pdfDocument.Add(table);

            pdfContentByte = writer.DirectContent;
            pdfContentByte.BeginText();
            pdfContentByte.SetFontAndSize(BaseFont.CreateFont(), iTextSharp.text.Font.DEFAULTSIZE);
            pdfContentByte.SetTextMatrix(230, 792);
            pdfContentByte.ShowText(string.Format("Width: {0}, Height: {1} - blah-blah-blah", page.Width, page.Height));
            pdfContentByte.EndText();
            #endif

            #if TEST_TABLE_WITH_ABSOLUTE_WIDTH_OF_CELL
            pdfDocument.NewPage();

            widths = new float[] { (PageSize.A4.Width * 50) / 210f, (PageSize.A4.Width * 25) / 210f, (PageSize.A4.Width * 25) / 210f };
            table  = new PdfPTable(MaxCell = 3);
            table.SetTotalWidth(widths);
            table.LockedWidth = true;
            for (int i = 0; i < MaxCell; ++i)
            {
                cell = new PdfPCell(new Paragraph(i.ToString()));
                table.AddCell(cell);
            }
            pdfDocument.Add(table);
            #endif

            ColumnText
                columnText;

            #if TEST_COLUMN_TEXT
            pdfDocument.NewPage();

            pdfContentByte = writer.DirectContent;

            pdfContentByte.MoveTo(x = 80f, 0f);
            pdfContentByte.LineTo(x, page.Height);
            pdfContentByte.MoveTo(0f, y = 80f);
            pdfContentByte.LineTo(page.Width, y);
            pdfContentByte.Stroke();

            columnText = new ColumnText(pdfContentByte);
            phrase     = new Phrase("blah-blah-blah1\nblah-blah-blah2 blah-blah-blah3 blah-blah-blah4 blah-blah-blah5");
            columnText.AddText(phrase);
            //columnText.AddElement(phrase);
            columnText.SetSimpleColumn(0, 0, x, y);
            columnText.Go();
            #endif

            pdfDocument.Close();
        }