AddElement() публичный метод

public AddElement ( IElement element ) : void
element IElement
Результат void
Пример #1
0
 /** Constructs a <CODE>PdfPCell</CODE> with a <CODE>PdfPtable</CODE>.
  * This constructor allows nested tables.
  *
  * @param table The <CODE>PdfPTable</CODE>
  * @param style  The style to apply to the cell (you could use getDefaultCell())
  * @since 2.1.0
  */
 public PdfPCell(PdfPTable table, PdfPCell style) : base(0, 0, 0, 0)
 {
     borderWidth = 0.5f;
     border      = BOX;
     column.SetLeading(0, 1);
     this.table            = table;
     table.WidthPercentage = 100;
     table.ExtendLastRow   = true;
     column.AddElement(table);
     if (style != null)
     {
         CloneNonPositionParameters(style);
         verticalAlignment = style.verticalAlignment;
         paddingLeft       = style.paddingLeft;
         paddingRight      = style.paddingRight;
         paddingTop        = style.paddingTop;
         paddingBottom     = style.paddingBottom;
         colspan           = style.colspan;
         rowspan           = style.rowspan;
         cellEvent         = style.cellEvent;
         useDescender      = style.useDescender;
         useBorderPadding  = style.useBorderPadding;
         rotation          = style.rotation;
     }
     else
     {
         Padding = 0;
     }
 }
Пример #2
0
        public void Render(PdfContentByte itextContent)
        {
            iTextSharp.text.pdf.ColumnText itextText = new iTextSharp.text.pdf.ColumnText(itextContent);
            itextText.SetSimpleColumn(ObjectLayoutContainer.Layout.Left.Points, ObjectLayoutContainer.Layout.Top.Points,
                                      ObjectLayoutContainer.Layout.Right.Points,
                                      ObjectLayoutContainer.Layout.Bottom.Points);

            Paragraph pdfContentParagraph = new Paragraph();

            itextText.AddElement(pdfContentParagraph);

            if (_textlines.Count > 0)
            {
                Models.Text.Paragraph currentParagraph = _textlines.First().ParagraphModel;
                pdfContentParagraph.Leading   = currentParagraph.Leading.Points;
                pdfContentParagraph.Alignment = (int)currentParagraph.Alignment;
                foreach (Textline textline in _textlines)
                {
                    if (currentParagraph != textline.ParagraphModel)
                    {
                        pdfContentParagraph           = new Paragraph(textline.ParagraphModel.Leading.Points);
                        pdfContentParagraph.Alignment = (int)textline.ParagraphModel.Alignment;
                        itextText.AddElement(pdfContentParagraph);
                    }
                    textline.Render(pdfContentParagraph);
                    currentParagraph = textline.ParagraphModel;
                }
                itextText.Go();
            }
        }
Пример #3
0
 /** Constructs a <CODE>PdfPCell</CODE> with a <CODE>PdfPtable</CODE>.
  * This constructor allows nested tables.
  * The default padding is 0.
  * @param table The <CODE>PdfPTable</CODE>
  */
 public PdfPCell(PdfPTable table) : base(0, 0, 0, 0)
 {
     borderWidth = 0.5f;
     border      = BOX;
     column.SetLeading(0, 1);
     Padding               = 0;
     this.table            = table;
     table.WidthPercentage = 100;
     table.ExtendLastRow   = true;
     column.AddElement(table);
 }
Пример #4
0
// ---------------------------------------------------------------------------    
    /**
     * Add content to a ColumnText object.
     * @param ct the ColumnText object
     * @param movie a Movie object
     * @param img the poster of the image
     */
    public void AddContent(ColumnText ct, Movie movie, Image img) {
      ct.AddElement(img);
      ct.AddElement(new Paragraph(movie.Title, FilmFonts.BOLD));
      if (!string.IsNullOrEmpty(movie.OriginalTitle)) {
        ct.AddElement(new Paragraph(movie.OriginalTitle, FilmFonts.ITALIC));
      }
      ct.AddElement(PojoToElementFactory.GetDirectorList(movie));
      ct.AddElement(PojoToElementFactory.GetYearPhrase(movie));
      ct.AddElement(PojoToElementFactory.GetDurationPhrase(movie));
      ct.AddElement(PojoToElementFactory.GetCountryList(movie));
      ct.AddElement(Chunk.NEWLINE);
    }    
Пример #5
0
 // ===========================================================================
 public void Write(Stream stream)
 {
     // step 1
     using (Document document = new Document(PageSize.A4.Rotate()))
     {
         // step 2
         PdfWriter writer = PdfWriter.GetInstance(document, stream);
         // step 3
         document.Open();
         // step 4
         ColumnText column = new ColumnText(writer.DirectContent);
         List<string> days = PojoFactory.GetDays();
         // COlumn definition
         float[][] x = {
   new float[] { document.Left, document.Left + 380 },
   new float[] { document.Right - 380, document.Right }
 };
         // Loop over the festival days
         foreach (string day in days)
         {
             // add content to the column
             column.AddElement(GetTable(day));
             int count = 0;
             float height = 0;
             // iText-ONLY, 'Initial value of the status' => 0
             // iTextSharp **DOES NOT** include this member variable
             // int status = ColumnText.START_COLUMN;
             int status = 0;
             // render the column as long as it has content
             while (ColumnText.HasMoreText(status))
             {
                 // add the top-level header to each new page
                 if (count == 0)
                 {
                     height = AddHeaderTable(document, day, writer.PageNumber);
                 }
                 // set the dimensions of the current column
                 column.SetSimpleColumn(
                   x[count][0], document.Bottom,
                   x[count][1], document.Top - height - 10
                 );
                 // render as much content as possible
                 status = column.Go();
                 // go to a new page if you've reached the last column
                 if (++count > 1)
                 {
                     count = 0;
                     document.NewPage();
                 }
             }
             document.NewPage();
         }
     }
 }
Пример #6
0
// ---------------------------------------------------------------------------    
    /**
     * Add content to a ColumnText object.
     * @param ct the ColumnText object
     * @param movie a Movie object
     * @param img the poster of the image
     */
    public void AddContent(ColumnText ct, Movie movie) {
      Paragraph p;
      p = new Paragraph(new Paragraph(movie.Title, FilmFonts.BOLD));
      p.Alignment = Element.ALIGN_CENTER;
      p.SpacingBefore = 16;
      ct.AddElement(p);
      if (!string.IsNullOrEmpty(movie.OriginalTitle)) {
        p = new Paragraph(movie.OriginalTitle, FilmFonts.ITALIC);
        p.Alignment = Element.ALIGN_RIGHT;
        ct.AddElement(p);
      }
      p = new Paragraph();
      p.Add(PojoToElementFactory.GetYearPhrase(movie));
      p.Add(" ");
      p.Add(PojoToElementFactory.GetDurationPhrase(movie));
      p.Alignment = Element.ALIGN_JUSTIFIED_ALL;
      ct.AddElement(p);
      p = new Paragraph(new Chunk(new StarSeparator()));
      p.SpacingAfter = 12;
      ct.AddElement(p);
  }    
Пример #7
0
        // ---------------------------------------------------------------------------
        /**
         * Manipulates a PDF file src
         * @param src the original PDF
         * @param stationery the resulting PDF
         */
        public byte[] ManipulatePdf(byte[] src, byte[] stationery)
        {
            ColumnText ct = new ColumnText(null);
            string SQL =
      @"SELECT country, id FROM film_country 
ORDER BY country
";
            using (var c = AdoDB.Provider.CreateConnection())
            {
                c.ConnectionString = AdoDB.CS;
                using (DbCommand cmd = c.CreateCommand())
                {
                    cmd.CommandText = SQL;
                    c.Open();
                    using (var r = cmd.ExecuteReader())
                    {
                        while (r.Read())
                        {
                            ct.AddElement(new Paragraph(
                              24, new Chunk(r["country"].ToString())
                            ));
                        }
                    }
                }
            }
            // Create a reader for the original document and for the stationery
            PdfReader reader = new PdfReader(src);
            PdfReader rStationery = new PdfReader(stationery);
            using (MemoryStream ms = new MemoryStream())
            {
                // Create a stamper
                using (PdfStamper stamper = new PdfStamper(reader, ms))
                {
                    // Create an imported page for the stationery
                    PdfImportedPage page = stamper.GetImportedPage(rStationery, 1);
                    int i = 0;
                    // Add the content of the ColumnText object 
                    while (true)
                    {
                        // Add a new page
                        stamper.InsertPage(++i, reader.GetPageSize(1));
                        // Add the stationary to the new page
                        stamper.GetUnderContent(i).AddTemplate(page, 0, 0);
                        // Add as much content of the column as possible
                        ct.Canvas = stamper.GetOverContent(i);
                        ct.SetSimpleColumn(36, 36, 559, 770);
                        if (!ColumnText.HasMoreText(ct.Go()))
                            break;
                    }
                }
                return ms.ToArray();
            }
        }
Пример #8
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
        BaseFont bf = BaseFont.CreateFont(
          "c:/windows/fonts/arialuni.ttf", 
          BaseFont.IDENTITY_H, BaseFont.EMBEDDED
        );
        Font font = new Font(bf, 20);
        document.Add(new Paragraph("Movie title: Lawrence of Arabia (UK)"));
        document.Add(new Paragraph("directed by David Lean"));
        document.Add(new Paragraph("Wrong: " + MOVIE, font));
        ColumnText column = new ColumnText(writer.DirectContent);
        column.SetSimpleColumn(36, 730, 569, 36);
        column.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
        column.AddElement(new Paragraph("Wrong: " + MOVIE_WITH_SPACES, font));
        column.AddElement(new Paragraph(MOVIE, font));
        column.Go();
      }
    }
Пример #9
0
 /// <summary>
 /// Add an element to be rendered in a column.
 /// Note that you can only add a  Phrase
 /// or a  Chunk  if the columns are
 /// not all simple.  This is an underlying restriction in
 /// {@link com.lowagie.text.pdf.ColumnText}
 /// @throws DocumentException if element can't be added
 /// </summary>
 /// <param name="element">element to add</param>
 public void AddElement(IElement element)
 {
     if (_simple)
     {
         _columnText.AddElement(element);
     }
     else if (element is Phrase)
     {
         _columnText.AddText((Phrase)element);
     }
     else if (element is Chunk)
     {
         _columnText.AddText((Chunk)element);
     }
     else
     {
         throw new DocumentException("Can't add " + element.GetType() + " to MultiColumnText with complex columns");
     }
 }
// ---------------------------------------------------------------------------
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document(PageSize.A4)) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        BaseFont bf = BaseFont.CreateFont(
          "c:/windows/fonts/arial.ttf", BaseFont.IDENTITY_H, true
        );
        Font font = new Font(bf, 14);
        document.Add(new Paragraph("Movie title: Nina's Tragedies"));
        document.Add(new Paragraph("directed by Savi Gabizon"));
        ColumnText column = new ColumnText(writer.DirectContent);
        column.SetSimpleColumn(36, 770, 569, 36);
        column.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
        column.AddElement(new Paragraph(MOVIE, font));
        column.Go();
      }
    }
Пример #11
0
        public void NestedTablesTest01() {
            String output = "nestedTablesTest.pdf";
            String cmp = "cmp_nestedTablesTest.pdf";

            Stopwatch timer = new Stopwatch();
            timer.Start();

            Document doc = new Document(PageSize.A4);
            PdfWriter writer = PdfWriter.GetInstance(doc, File.Create(outFolder + output));
            doc.Open();

            ColumnText column = new ColumnText(writer.DirectContent);
            column.SetSimpleColumn(72, 72, 523, 770);
            column.AddElement(CreateNestedTables(15));
            column.Go();

            doc.Close();

            timer.Stop();
            Console.WriteLine(timer.ElapsedMilliseconds);

            CompareDocuments(output, cmp, false);
        }
Пример #12
0
        virtual public void TabStopsColumnText() {
            Document document = new Document(PageSize.A4);
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(OUTABSTOPSC, FileMode.Create));
            document.Open();

            Font oFont1 = FontFactory.GetFont(BaseFont.ZAPFDINGBATS, 15, Font.UNDEFINED);
            Font oFont2 = FontFactory.GetFont(BaseFont.COURIER, 15, Font.UNDEFINED);
            Font oFont3 = FontFactory.GetFont(BaseFont.TIMES_ROMAN, 15, Font.UNDEFINED);
            Font oFont4 = FontFactory.GetFont(BaseFont.HELVETICA, 15, Font.UNDEFINED);
            Image oImg = Image.GetInstance(RESOURCES + "logo.gif");
            PdfContentByte canvas = writer.DirectContentUnder;

            List<TabStop> tabStops = new List<TabStop>();
            //tabStops.Add(new TabStop(100, new DottedLineSeparator()));
            //tabStops.Add(new TabStop(200, new DottedLineSeparator()));
            tabStops.Add(new TabStop(200, new DottedLineSeparator()));
            //tabStops.Add(new TabStop(300, new DottedLineSeparator()));
            tabStops.Add(new TabStop(400, new DottedLineSeparator()));
            //tabStops.Add(new TabStop(500, new DottedLineSeparator()));
            //tabStops.Add(new TabStop(550, new DottedLineSeparator()));

            Paragraph oPara = new Paragraph("Hello World! ", oFont1);
            oPara.TabSettings = new TabSettings(tabStops);
            oPara.Add(new Chunk("iText ® is a library that allows you to create and manipulate PDF documents.", oFont2));
            oPara.Add(
                new Chunk("It enables developers looking to enhance web- and other applications with dynamic PDF docu",
                          oFont3));
            oPara.Add(Chunk.TABBING);
            oPara.Add(new Chunk("ment generation and/or manipulation.", oFont3));
            oPara.Add(new Chunk(oImg, 0, 0, true));
            //oPara.Add(new Chunk(new TestVerticalPositionMark()));
            oPara.Add(Chunk.TABBING);
            oPara.Add(new Chunk("Developers can use iText to:", oFont4));

            ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT, new Phrase("|100"), 100, 500, 0);
            ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT, new Phrase("|200"), 200, 500, 0);
            ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT, new Phrase("|250"), 250, 500, 0);
            ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT, new Phrase("|300"), 300, 500, 0);
            ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT, new Phrase("|400"), 400, 500, 0);
            ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT, new Phrase("|500"), 500, 500, 0);
            ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT, new Phrase("|550"), 550, 500, 0);
            ColumnText oColTxt1 = new ColumnText(canvas);

            oColTxt1.SetSimpleColumn(0, 400, 595, 500);
            oColTxt1.AddElement(oPara);
            oColTxt1.Go();

            document.Close();
            Assert.IsTrue(CompareInnerText(SOURCE15, OUTABSTOPSC));
        }
Пример #13
0
        virtual public void TabColumnTextTest() {
            Font f = FontFactory.GetFont(FontFactory.COURIER, 11);
            Document doc = new Document();
            Paragraph p;
            FileStream fs = new FileStream(OUTABC, FileMode.Create);
            PdfWriter writer = PdfWriter.GetInstance(doc, fs);
            writer.CompressionLevel = 0;
            doc.Open();
            ColumnText ct = new ColumnText(writer.DirectContent);
            ct.SetSimpleColumn(36, 36, 436, 800);
            List<TabStop> tabStopsList = new List<TabStop>();
            tabStopsList.Add(new TabStop(100, new DottedLineSeparator()));
            tabStopsList.Add(new TabStop(200, new LineSeparator(), TabStop.Alignment.CENTER));
            tabStopsList.Add(new TabStop(300, new DottedLineSeparator(), TabStop.Alignment.RIGHT));
            p = new Paragraph(new Chunk("Hello world", f));
            p.TabSettings = new TabSettings(tabStopsList, 50);
            AddTabs(p, f, 0, "la|la");
            ct.AddElement(p);

            tabStopsList = new List<TabStop>();
            tabStopsList.Add(new TabStop(100, new DottedLineSeparator()));
            tabStopsList.Add(new TabStop(200, new LineSeparator(), TabStop.Alignment.ANCHOR));
            tabStopsList.Add(new TabStop(300, new DottedLineSeparator(), TabStop.Alignment.ANCHOR));
            p = new Paragraph(new Chunk("Hello World!!!"));
            p.TabSettings = new TabSettings(tabStopsList, 50);
            AddTabs(p, f, 12, "l.aal");
            AddTabs(p, f, 12, "laa.l");
            AddTabs(p, f, 12, "la.al");
            ct.AddElement(p);

            f.Size = 16;
            p = new Paragraph(new Chunk("Hello world", f));
            tabStopsList = new List<TabStop>();
            tabStopsList.Add(new TabStop(100, new DottedLineSeparator()));
            tabStopsList.Add(new TabStop(200, new LineSeparator(), TabStop.Alignment.ANCHOR, ','));
            tabStopsList.Add(new TabStop(300, new DottedLineSeparator(), TabStop.Alignment.ANCHOR));
            p.TabSettings = new TabSettings(tabStopsList, 50);
            AddTabs(p, f, 15, "l.aal");
            AddTabs(p, f, 13, "laa,l");
            AddTabs(p, f, 13, "laa.l");
            AddTabs(p, f, 13, "l,aal");
            ct.AddElement(p);

            f = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12);
            p = new Paragraph(new Chunk("Hello world", f));
            p.TabSettings = new TabSettings(38);
            AddTabs(p, f, 0);
            ct.AddElement(p);

            f.Size = 20;
            p = new Paragraph(new Chunk("Hello world", f));
            p.TabSettings = new TabSettings(38);
            AddTabs(p, f, 0);
            ct.AddElement(p);
            ct.Go();
            doc.Close();
            fs.Close();
            Assert.IsTrue(CompareInnerText(SOURCE14, OUTABC));

        }
Пример #14
0
        public void Run(Stream stream, CMSDataContext Db, IEnumerable<ContributorInfo> q, int set = 0)
        {
            pageEvents.set = set;
            IEnumerable<ContributorInfo> contributors = q;
            var toDate = ToDate.Date.AddHours(24).AddSeconds(-1);

            PdfContentByte dc;
            var font = FontFactory.GetFont(FontFactory.HELVETICA, 11);
            var boldfont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 11);

            var doc = new Document(PageSize.LETTER);
            doc.SetMargins(36f, 30f, 24f, 36f);
            var w = PdfWriter.GetInstance(doc, stream);
            w.PageEvent = pageEvents;
            doc.Open();
            dc = w.DirectContent;

            int prevfid = 0;
            var runningtotals = Db.ContributionsRuns.OrderByDescending(mm => mm.Id).FirstOrDefault();
            runningtotals.Processed = 0;
            Db.SubmitChanges();
            var count = 0;
            foreach (var ci in contributors)
            {
                if (set > 0 && pageEvents.FamilySet[ci.PeopleId] != set)
                    continue;
                doc.NewPage();
                if (prevfid != ci.FamilyId)
                {
                    prevfid = ci.FamilyId;
                    pageEvents.EndPageSet();
                }
                if (set == 0)
                    pageEvents.FamilySet[ci.PeopleId] = 0;
                count++;

                var css = @"
            <style>
            h1 { font-size: 24px; font-weight:normal; margin-bottom:0; }
            h2 { font-size: 11px; font-weight:normal; margin-top: 0; }
            p { font-size: 11px; }
            </style>
            ";

                //----Church Name
                var t1 = new PdfPTable(1);
                t1.TotalWidth = 72f * 5f;
                t1.DefaultCell.Border = Rectangle.NO_BORDER;
                string html1 = Db.ContentHtml("StatementHeader", Resource1.ContributionStatementHeader);
                string html2 = Db.ContentHtml("StatementNotice", Resource1.ContributionStatementNotice);

                var mh = new MyHandler();
                using (var sr = new StringReader(css + html1))
                    XMLWorkerHelper.GetInstance().ParseXHtml(mh, sr);

                var cell = new PdfPCell(t1.DefaultCell);
                foreach (var e in mh.elements)
                    if (e.Chunks.Count > 0)
                        cell.AddElement(e);
                //cell.FixedHeight = 72f * 1.25f;
                t1.AddCell(cell);
                t1.AddCell("\n");

                var t1a = new PdfPTable(1);
                t1a.TotalWidth = 72f * 5f;
                t1a.DefaultCell.Border = Rectangle.NO_BORDER;

                var ae = new PdfPTable(1);
                ae.DefaultCell.Border = Rectangle.NO_BORDER;
                ae.WidthPercentage = 100;

                var a = new PdfPTable(1);
                a.DefaultCell.Indent = 25f;
                a.DefaultCell.Border = Rectangle.NO_BORDER;
                a.AddCell(new Phrase(ci.Name, font));
                a.AddCell(new Phrase(ci.Address1, font));
                if (ci.Address2.HasValue())
                    a.AddCell(new Phrase(ci.Address2, font));
                a.AddCell(new Phrase(ci.CityStateZip, font));
                cell = new PdfPCell(a) { Border = Rectangle.NO_BORDER };
                //cell.FixedHeight = 72f * 1.0625f;
                ae.AddCell(cell);

                cell = new PdfPCell(t1a.DefaultCell);
                cell.AddElement(ae);
                t1a.AddCell(ae);

                //-----Notice
                var t2 = new PdfPTable(1);
                t2.TotalWidth = 72f * 3f;
                t2.DefaultCell.Border = Rectangle.NO_BORDER;
                t2.AddCell(new Phrase("\nPrint Date: {0:d}   (id:{1} {2})".Fmt(DateTime.Now, ci.PeopleId, ci.CampusId), font));
                t2.AddCell("");
                var mh2 = new MyHandler();
                using (var sr = new StringReader(css + html2))
                    XMLWorkerHelper.GetInstance().ParseXHtml(mh2, sr);
                cell = new PdfPCell(t1.DefaultCell);
                foreach (var e in mh2.elements)
                    if (e.Chunks.Count > 0)
                        cell.AddElement(e);
                t2.AddCell(cell);

                // POSITIONING OF ADDRESSES
                //----Header
                var yp = doc.BottomMargin +
                    Db.Setting("StatementRetAddrPos", "10.125").ToFloat() * 72f;
                t1.WriteSelectedRows(0, -1,
                    doc.LeftMargin - 0.1875f * 72f, yp, dc);

                yp = doc.BottomMargin +
                    Db.Setting("StatementAddrPos", "8.3375").ToFloat() * 72f;
                t1a.WriteSelectedRows(0, -1, doc.LeftMargin, yp, dc);

                yp = doc.BottomMargin + 10.125f * 72f;
                t2.WriteSelectedRows(0, -1, doc.LeftMargin + 72f * 4.4f, yp, dc);

                //----Contributions
                doc.Add(new Paragraph(" "));
                doc.Add(new Paragraph(" ") { SpacingBefore = 72f * 2.125f });

                doc.Add(new Phrase("\n  Period: {0:d} - {1:d}".Fmt(FromDate, toDate), boldfont));

                var pos = w.GetVerticalPosition(true);

                var ct = new ColumnText(dc);
                float gutter = 20f;
                float colwidth = (doc.Right - doc.Left - gutter) / 2;

                var t = new PdfPTable(new float[] { 10f, 24f, 10f });
                t.WidthPercentage = 100;
                t.DefaultCell.Border = Rectangle.NO_BORDER;
                t.HeaderRows = 2;

                cell = new PdfPCell(t.DefaultCell);
                cell.Colspan = 3;
                cell.Phrase = new Phrase("Contributions\n", boldfont);
                t.AddCell(cell);

                t.DefaultCell.Border = Rectangle.BOTTOM_BORDER;
                t.AddCell(new Phrase("Date", boldfont));
                t.AddCell(new Phrase("Description", boldfont));
                cell = new PdfPCell(t.DefaultCell);
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                cell.Phrase = new Phrase("Amount", boldfont);
                t.AddCell(cell);

                t.DefaultCell.Border = Rectangle.NO_BORDER;

                var total = 0m;
                foreach (var c in APIContribution.contributions(Db, ci, FromDate, toDate))
                {
                    t.AddCell(new Phrase(c.ContributionDate.ToShortDateString(), font));
                    t.AddCell(new Phrase(c.Fund, font));
                    cell = new PdfPCell(t.DefaultCell);
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    cell.Phrase = new Phrase(c.ContributionAmount.ToString("N2"), font);
                    t.AddCell(cell);
                    total += (c.ContributionAmount);
                }
                t.DefaultCell.Border = Rectangle.TOP_BORDER;
                cell = new PdfPCell(t.DefaultCell);
                cell.Colspan = 2;
                cell.Phrase = new Phrase("Total Contributions for period", boldfont);
                t.AddCell(cell);
                cell = new PdfPCell(t.DefaultCell);
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                cell.Phrase = new Phrase(total.ToString("N2"), font);
                t.AddCell(cell);

                ct.AddElement(t);

                //------Pledges
                var pledges = APIContribution.pledges(Db, ci, toDate).ToList();
                if (pledges.Count > 0)
                {
                    t = new PdfPTable(new float[] { 16f, 12f, 12f });
                    t.WidthPercentage = 100;
                    t.DefaultCell.Border = Rectangle.NO_BORDER;
                    t.HeaderRows = 2;

                    cell = new PdfPCell(t.DefaultCell);
                    cell.Colspan = 3;
                    cell.Phrase = new Phrase("\n\nPledges\n", boldfont);
                    t.AddCell(cell);

                    t.DefaultCell.Border = Rectangle.BOTTOM_BORDER;
                    t.AddCell(new Phrase("Fund", boldfont));
                    cell = new PdfPCell(t.DefaultCell);
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    cell.Phrase = new Phrase("Pledge", boldfont);
                    t.AddCell(cell);
                    cell = new PdfPCell(t.DefaultCell);
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    cell.Phrase = new Phrase("Given", boldfont);
                    t.AddCell(cell);

                    t.DefaultCell.Border = Rectangle.NO_BORDER;

                    foreach (var c in pledges)
                    {
                        t.AddCell(new Phrase(c.Fund, font));
                        cell = new PdfPCell(t.DefaultCell);
                        cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        cell.Phrase = new Phrase(c.PledgeAmount.ToString2("N2"), font);
                        t.AddCell(cell);
                        cell = new PdfPCell(t.DefaultCell);
                        cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        cell.Phrase = new Phrase(c.ContributionAmount.ToString2("N2"), font);
                        t.AddCell(cell);
                    }
                    ct.AddElement(t);
                }

                //------Gifts In Kind
                var giftsinkind = APIContribution.GiftsInKind(Db, ci, FromDate, toDate).ToList();
                if (giftsinkind.Count > 0)
                {
                    t = new PdfPTable(new float[] { 12f, 18f, 20f });
                    t.WidthPercentage = 100;
                    t.DefaultCell.Border = Rectangle.NO_BORDER;
                    t.HeaderRows = 2;

                    cell = new PdfPCell(t.DefaultCell);
                    cell.Colspan = 3;
                    cell.Phrase = new Phrase("\n\nGifts in Kind\n", boldfont);
                    t.AddCell(cell);

                    t.DefaultCell.Border = Rectangle.BOTTOM_BORDER;
                    t.AddCell(new Phrase("Date", boldfont));
                    cell = new PdfPCell(t.DefaultCell);
                    cell.Phrase = new Phrase("Fund", boldfont);
                    t.AddCell(cell);
                    cell = new PdfPCell(t.DefaultCell);
                    cell.Phrase = new Phrase("Description", boldfont);
                    t.AddCell(cell);

                    t.DefaultCell.Border = Rectangle.NO_BORDER;

                    foreach (var c in giftsinkind)
                    {
                        t.AddCell(new Phrase(c.ContributionDate.ToShortDateString(), font));
                        cell = new PdfPCell(t.DefaultCell);
                        cell.Phrase = new Phrase(c.Fund, font);
                        t.AddCell(cell);
                        cell = new PdfPCell(t.DefaultCell);
                        cell.Phrase = new Phrase(c.Description, font);
                        t.AddCell(cell);
                    }
                    ct.AddElement(t);
                }

                //-----Summary
                t = new PdfPTable(new float[] { 29f, 9f });
                t.WidthPercentage = 100;
                t.DefaultCell.Border = Rectangle.NO_BORDER;
                t.HeaderRows = 2;

                cell = new PdfPCell(t.DefaultCell);
                cell.Colspan = 2;
                cell.Phrase = new Phrase("\n\nPeriod Summary\n", boldfont);
                t.AddCell(cell);

                t.DefaultCell.Border = Rectangle.BOTTOM_BORDER;
                t.AddCell(new Phrase("Fund", boldfont));
                cell = new PdfPCell(t.DefaultCell);
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                cell.Phrase = new Phrase("Amount", boldfont);
                t.AddCell(cell);

                t.DefaultCell.Border = Rectangle.NO_BORDER;
                foreach (var c in APIContribution.quarterlySummary(Db, ci, FromDate, toDate))
                {
                    t.AddCell(new Phrase(c.Fund, font));
                    cell = new PdfPCell(t.DefaultCell);
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    cell.Phrase = new Phrase(c.ContributionAmount.ToString("N2"), font);
                    t.AddCell(cell);
                }
                t.DefaultCell.Border = Rectangle.TOP_BORDER;
                t.AddCell(new Phrase("Total contributions for period", boldfont));
                cell = new PdfPCell(t.DefaultCell);
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                cell.Phrase = new Phrase(total.ToString("N2"), font);
                t.AddCell(cell);
                ct.AddElement(t);

                var col = 0;
                var status = 0;
                while (ColumnText.HasMoreText(status))
                {
                    if (col == 0)
                        ct.SetSimpleColumn(doc.Left, doc.Bottom, doc.Left + colwidth, pos);
                    else if (col == 1)
                        ct.SetSimpleColumn(doc.Right - colwidth, doc.Bottom, doc.Right, pos);
                    status = ct.Go();
                    ++col;
                    if (col > 1)
                    {
                        col = 0;
                        pos = doc.Top;
                        doc.NewPage();
                    }
                }

                runningtotals.Processed += 1;
                runningtotals.CurrSet = set;
                Db.SubmitChanges();
            }

            if (count == 0)
            {
                doc.NewPage();
                doc.Add(new Phrase("no data"));
            }
            doc.Close();

            if (set == LastSet())
                runningtotals.Completed = DateTime.Now;
            Db.SubmitChanges();
        }
Пример #15
0
        private int FloatingLayout(List <IElement> floatingElements, bool simulate)
        {
            int   status     = ColumnText.NO_MORE_TEXT;
            float minYLine   = yLine;
            float leftWidth  = 0;
            float rightWidth = 0;

            ColumnText currentCompositeColumn = compositeColumn;

            if (simulate)
            {
                currentCompositeColumn = ColumnText.Duplicate(compositeColumn);
            }

            while (floatingElements.Count > 0)
            {
                IElement nextElement = floatingElements[0];
                floatingElements.RemoveAt(0);
                if (nextElement is PdfDiv)
                {
                    PdfDiv floatingElement = (PdfDiv)nextElement;
                    status = floatingElement.Layout(compositeColumn.Canvas, useAscender, true, floatLeftX, minY, floatRightX, yLine);
                    if ((status & ColumnText.NO_MORE_TEXT) == 0)
                    {
                        yLine       = minYLine;
                        floatLeftX  = leftX;
                        floatRightX = rightX;
                        status      = floatingElement.Layout(compositeColumn.Canvas, useAscender, true, floatLeftX, minY, floatRightX, yLine);
                        if ((status & ColumnText.NO_MORE_TEXT) == 0)
                        {
                            floatingElements.Insert(0, floatingElement);
                            break;
                        }
                    }
                    if (floatingElement.Float == PdfDiv.FloatType.LEFT)
                    {
                        status      = floatingElement.Layout(compositeColumn.Canvas, useAscender, simulate, floatLeftX, minY, floatRightX, yLine);
                        floatLeftX += floatingElement.getActualWidth();
                        leftWidth  += floatingElement.getActualWidth();
                    }
                    else if (floatingElement.Float == PdfDiv.FloatType.RIGHT)
                    {
                        status       = floatingElement.Layout(compositeColumn.Canvas, useAscender, simulate, floatRightX - floatingElement.getActualWidth() - 0.01f, minY, floatRightX, yLine);
                        floatRightX -= floatingElement.getActualWidth();
                        rightWidth  += floatingElement.getActualWidth();
                    }
                    minYLine = Math.Min(minYLine, yLine - floatingElement.getActualHeight());
                }
                else
                {
                    if (nextElement is ISpaceable)
                    {
                        yLine -= ((ISpaceable)nextElement).SpacingBefore;
                    }
                    if (simulate)
                    {
                        if (nextElement is PdfPTable)
                        {
                            currentCompositeColumn.AddElement(new PdfPTable((PdfPTable)nextElement));
                        }
                        else
                        {
                            currentCompositeColumn.AddElement(nextElement);
                        }
                    }
                    else
                    {
                        currentCompositeColumn.AddElement(nextElement);
                    }
                    if (yLine > minYLine)
                    {
                        currentCompositeColumn.SetSimpleColumn(floatLeftX, yLine, floatRightX, minYLine);
                    }
                    else
                    {
                        currentCompositeColumn.SetSimpleColumn(floatLeftX, yLine, floatRightX, minY);
                    }

                    currentCompositeColumn.FilledWidth = 0;

                    status = currentCompositeColumn.Go(simulate);
                    if (yLine > minYLine && (floatLeftX > leftX || floatRightX < rightX) && (status & ColumnText.NO_MORE_TEXT) == 0)
                    {
                        yLine       = minYLine;
                        floatLeftX  = leftX;
                        floatRightX = rightX;
                        if (leftWidth != 0 && rightWidth != 0)
                        {
                            filledWidth = rightX - leftX;
                        }
                        else
                        {
                            if (leftWidth > filledWidth)
                            {
                                filledWidth = leftWidth;
                            }
                            if (rightWidth > filledWidth)
                            {
                                filledWidth = rightWidth;
                            }
                        }

                        leftWidth  = 0;
                        rightWidth = 0;
                        if (simulate && nextElement is PdfPTable)
                        {
                            currentCompositeColumn.AddElement(new PdfPTable((PdfPTable)nextElement));
                        }

                        currentCompositeColumn.SetSimpleColumn(floatLeftX, yLine, floatRightX, minY);
                        status   = currentCompositeColumn.Go(simulate);
                        minYLine = currentCompositeColumn.YLine + currentCompositeColumn.Descender;
                        yLine    = minYLine;
                        if (compositeColumn.FilledWidth > filledWidth)
                        {
                            filledWidth = compositeColumn.FilledWidth;
                        }
                    }
                    else
                    {
                        if (rightWidth > 0)
                        {
                            rightWidth += currentCompositeColumn.FilledWidth;
                        }
                        else if (leftWidth > 0)
                        {
                            leftWidth += currentCompositeColumn.FilledWidth;
                        }
                        else if (currentCompositeColumn.FilledWidth > filledWidth)
                        {
                            filledWidth = currentCompositeColumn.FilledWidth;
                        }
                        minYLine = Math.Min(currentCompositeColumn.YLine + currentCompositeColumn.Descender, minYLine);
                        yLine    = currentCompositeColumn.YLine + currentCompositeColumn.Descender;
                    }

                    if ((status & ColumnText.NO_MORE_TEXT) == 0)
                    {
                        if (!simulate)
                        {
                            floatingElements.InsertRange(0, currentCompositeColumn.CompositeElements);
                            currentCompositeColumn.CompositeElements.Clear();
                        }
                        else
                        {
                            floatingElements.Insert(0, nextElement);
                            currentCompositeColumn.SetText(null);
                        }
                        break;
                    }
                    else
                    {
                        currentCompositeColumn.SetText(null);
                    }
                }
            }


            if (leftWidth != 0 && rightWidth != 0)
            {
                filledWidth = rightX - leftX;
            }
            else
            {
                if (leftWidth > filledWidth)
                {
                    filledWidth = leftWidth;
                }
                if (rightWidth > filledWidth)
                {
                    filledWidth = rightWidth;
                }
            }

            yLine       = minYLine;
            floatLeftX  = leftX;
            floatRightX = rightX;

            return(status);
        }
Пример #16
0
        /// <summary>
        /// Adds in worker information, Department(s), Unit(s), and PM/Lead Programmer
        /// </summary>
        /// <param name="cb"></param>
        /// <param name="doc"></param>
        /// <param name="project"></param>
        private void AddWorkerInformation(PdfContentByte cb, Document doc, Project project)
        {
            var x = doc.LeftMargin;
            // height to bottom of worker information box
            var y = doc.BottomMargin + 520;

            var department = new Paragraph(project.WorkgroupDepts, _coverFont);
            var workgroups = new Paragraph(project.WorkgroupNames, _coverFont);
            var pm = new Paragraph(string.Format("Project Manager: {0}", project.ProjectManager != null ? project.ProjectManager.FullName : "n/a"), _coverSmallFont);
            var lp = new Paragraph(string.Format("Lead Programmer: {0}", project.LeadProgrammer != null ? project.LeadProgrammer.FullName : "n/a"), _coverSmallFont);

            var ct = new ColumnText(cb);
            ct.SetSimpleColumn(x, y, x + _pageWidth, y + 98);
            ct.Alignment = Element.ALIGN_LEFT | Element.ALIGN_TOP;

            ct.AddElement(department);
            ct.AddElement(workgroups);
            ct.AddElement(pm);
            ct.AddElement(lp);

            ct.Go();
        }
Пример #17
0
        /**
         * Gets the main appearance layer.
         * <p>
         * Consult <A HREF="http://partners.adobe.com/asn/developer/pdfs/tn/PPKAppearances.pdf">PPKAppearances.pdf</A>
         * for further details.
         * @return the main appearance layer
         * @throws DocumentException on error
         */
        public PdfTemplate GetAppearance() {
            if (IsInvisible()) {
                PdfTemplate t = new PdfTemplate(writer);
                t.BoundingBox = new Rectangle(0, 0);
                writer.AddDirectTemplateSimple(t, null);
                return t;
            }
            if (app[0] == null && !reuseAppearance)
                CreateBlankN0();            
            if (app[1] == null && !acro6Layers) {
                PdfTemplate t = app[1] = new PdfTemplate(writer);
                t.BoundingBox = new Rectangle(100, 100);
                writer.AddDirectTemplateSimple(t, new PdfName("n1"));
                t.SetLiteral(questionMark);
            }
            if (app[2] == null) {
                String text;
                if (layer2Text == null) {
                    StringBuilder buf = new StringBuilder();
                    buf.Append("Digitally signed by ");
                    String name = null;
                    CertificateInfo.X509Name x500name = CertificateInfo.GetSubjectFields((X509Certificate)signCertificate);
                    if (x500name != null) {
                        name = x500name.GetField("CN");
                        if (name == null)
                            name = x500name.GetField("E");
                    }
                    if (name == null)
                        name = "";
                    buf.Append(name).Append('\n');
                    buf.Append("Date: ").Append(signDate.ToString("yyyy.MM.dd HH:mm:ss zzz"));
                    if (reason != null)
                        buf.Append('\n').Append(reasonCaption).Append(reason);
                    if (location != null)
                        buf.Append('\n').Append(locationCaption).Append(location);
                    text = buf.ToString();
                }
                else
                    text = layer2Text;
                PdfTemplate t = app[2] = new PdfTemplate(writer);
                t.BoundingBox = rect;
                writer.AddDirectTemplateSimple(t, new PdfName("n2"));
                if (image != null) {
                    if (imageScale == 0) {
                        t.AddImage(image, rect.Width, 0, 0, rect.Height, 0, 0);
                    }
                    else {
                        float usableScale = imageScale;
                        if (imageScale < 0)
                            usableScale = Math.Min(rect.Width / image.Width, rect.Height / image.Height);
                        float w = image.Width * usableScale;
                        float h = image.Height * usableScale;
                        float x = (rect.Width - w) / 2;
                        float y = (rect.Height - h) / 2;
                        t.AddImage(image, w, 0, 0, h, x, y);
                    }
                }
                Font font;
                if (layer2Font == null)
                    font = new Font();
                else
                    font = new Font(layer2Font);
                float size = font.Size;

                Rectangle dataRect = null;
                Rectangle signatureRect = null;

                if (renderingMode == RenderingMode.NAME_AND_DESCRIPTION || 
                    (renderingMode == RenderingMode.GRAPHIC_AND_DESCRIPTION && this.SignatureGraphic != null)) {
                    // origin is the bottom-left
                    signatureRect = new Rectangle(
                        MARGIN, 
                        MARGIN, 
                        rect.Width / 2 - MARGIN,
                        rect.Height - MARGIN);
                    dataRect = new Rectangle(
                        rect.Width / 2 +  MARGIN / 2, 
                        MARGIN, 
                        rect.Width - MARGIN / 2,
                        rect.Height - MARGIN);

                    if (rect.Height > rect.Width) {
                        signatureRect = new Rectangle(
                            MARGIN, 
                            rect.Height / 2, 
                            rect.Width - MARGIN,
                            rect.Height);
                        dataRect = new Rectangle(
                            MARGIN, 
                            MARGIN, 
                            rect.Width - MARGIN,
                            rect.Height / 2 - MARGIN);
                    }
                }
                else if (renderingMode == RenderingMode.GRAPHIC) {
                    if (signatureGraphic == null) {
                        throw new InvalidOperationException(MessageLocalization.GetComposedMessage("a.signature.image.should.be.present.when.rendering.mode.is.graphic.only"));
                    }
                    signatureRect = new Rectangle(
                            MARGIN,
                            MARGIN,
                            rect.Width - MARGIN, // take all space available
                            rect.Height - MARGIN);
                }
                else {
                    dataRect = new Rectangle(
                        MARGIN, 
                        MARGIN, 
                        rect.Width - MARGIN,
                        rect.Height * (1 - TOP_SECTION) - MARGIN);
                }

                if (renderingMode == RenderingMode.NAME_AND_DESCRIPTION) {
                    string signedBy = CertificateInfo.GetSubjectFields(signCertificate).GetField("CN");
                    if (signedBy == null)
                        signedBy = CertificateInfo.GetSubjectFields(signCertificate).GetField("E");
                    if (signedBy == null)
                        signedBy = "";
                    Rectangle sr2 = new Rectangle(signatureRect.Width - MARGIN, signatureRect.Height - MARGIN );
                    float signedSize = ColumnText.FitText(font, signedBy, sr2, -1, runDirection);

                    ColumnText ct2 = new ColumnText(t);
                    ct2.RunDirection = runDirection;
                    ct2.SetSimpleColumn(new Phrase(signedBy, font), signatureRect.Left, signatureRect.Bottom, signatureRect.Right, signatureRect.Top, signedSize, Element.ALIGN_LEFT);

                    ct2.Go();
                }
                else if (renderingMode == RenderingMode.GRAPHIC_AND_DESCRIPTION) {
                    if (signatureGraphic == null) {
                        throw new InvalidOperationException(MessageLocalization.GetComposedMessage("a.signature.image.should.be.present.when.rendering.mode.is.graphic.and.description"));
                    }
                    ColumnText ct2 = new ColumnText(t);
                    ct2.RunDirection = runDirection;
                    ct2.SetSimpleColumn(signatureRect.Left, signatureRect.Bottom, signatureRect.Right, signatureRect.Top, 0, Element.ALIGN_RIGHT);

                    Image im = Image.GetInstance(SignatureGraphic);
                    im.ScaleToFit(signatureRect.Width, signatureRect.Height);

                    Paragraph p = new Paragraph();
                    // must calculate the point to draw from to make image appear in middle of column
                    float x = 0;
                    // experimentation found this magic number to counteract Adobe's signature graphic, which
                    // offsets the y co-ordinate by 15 units
                    float y = -im.ScaledHeight + 15;

                    x = x + (signatureRect.Width - im.ScaledWidth) / 2;
                    y = y - (signatureRect.Height - im.ScaledHeight) / 2;
                    p.Add(new Chunk(im, x + (signatureRect.Width - im.ScaledWidth) / 2, y, false));
                    ct2.AddElement(p);
                    ct2.Go();
                }

                else if (renderingMode == RenderingMode.GRAPHIC) {
                    ColumnText ct2 = new ColumnText(t);
                    ct2.RunDirection = runDirection;
                    ct2.SetSimpleColumn(signatureRect.Left, signatureRect.Bottom, signatureRect.Right, signatureRect.Top, 0, Element.ALIGN_RIGHT);

                    Image im = Image.GetInstance(signatureGraphic);
                    im.ScaleToFit(signatureRect.Width, signatureRect.Height);

                    Paragraph p = new Paragraph(signatureRect.Height);
                    // must calculate the point to draw from to make image appear in middle of column
                    float x = (signatureRect.Width - im.ScaledWidth) / 2;
                    float y = (signatureRect.Height - im.ScaledHeight) / 2;
                    p.Add(new Chunk(im, x, y, false));
                    ct2.AddElement(p);
                    ct2.Go();
                }
                
                if (renderingMode != RenderingMode.GRAPHIC) {
                    if (size <= 0) {
                        Rectangle sr = new Rectangle(dataRect.Width, dataRect.Height);
                        size = ColumnText.FitText(font, text, sr, 12, runDirection);
                    }
                    ColumnText ct = new ColumnText(t);
                    ct.RunDirection = runDirection;
                    ct.SetSimpleColumn(new Phrase(text, font), dataRect.Left, dataRect.Bottom, dataRect.Right, dataRect.Top, size, Element.ALIGN_LEFT);
                    ct.Go();
                }
            }
            if (app[3] == null && !acro6Layers) {
                PdfTemplate t = app[3] = new PdfTemplate(writer);
                t.BoundingBox = new Rectangle(100, 100);
                writer.AddDirectTemplateSimple(t, new PdfName("n3"));
                t.SetLiteral("% DSBlank\n");
            }
            if (app[4] == null && !acro6Layers) {
                PdfTemplate t = app[4] = new PdfTemplate(writer);
                t.BoundingBox = new Rectangle(0, rect.Height * (1 - TOP_SECTION), rect.Right, rect.Top);
                writer.AddDirectTemplateSimple(t, new PdfName("n4"));
                Font font;
                if (layer2Font == null)
                    font = new Font();
                else
                    font = new Font(layer2Font);
                float size = font.Size;
                String text = "Signature Not Verified";
                if (layer4Text != null)
                    text = layer4Text;
                Rectangle sr = new Rectangle(rect.Width - 2 * MARGIN, rect.Height * TOP_SECTION - 2 * MARGIN);
                size = ColumnText.FitText(font, text, sr, 15, runDirection);
                ColumnText ct = new ColumnText(t);
                ct.RunDirection = runDirection;
                ct.SetSimpleColumn(new Phrase(text, font), MARGIN, 0, rect.Width - MARGIN, rect.Height - MARGIN, size, Element.ALIGN_LEFT);
                ct.Go();
            }
            int rotation = writer.reader.GetPageRotation(page);
            Rectangle rotated = new Rectangle(rect);
            int n = rotation;
            while (n > 0) {
                rotated = rotated.Rotate();
                n -= 90;
            }
            if (frm == null) {
                frm = new PdfTemplate(writer);
                frm.BoundingBox = rotated;
                writer.AddDirectTemplateSimple(frm, new PdfName("FRM"));
                float scale = Math.Min(rect.Width, rect.Height) * 0.9f;
                float x = (rect.Width - scale) / 2;
                float y = (rect.Height - scale) / 2;
                scale /= 100;
                if (rotation == 90)
                    frm.ConcatCTM(0, 1, -1, 0, rect.Height, 0);
                else if (rotation == 180)
                    frm.ConcatCTM(-1, 0, 0, -1, rect.Width, rect.Height);
                else if (rotation == 270)
                    frm.ConcatCTM(0, -1, 1, 0, 0, rect.Width);
                if (reuseAppearance) {
                    AcroFields af = writer.GetAcroFields();
                    PdfIndirectReference refe = af.GetNormalAppearance(FieldName);
                    if (refe != null) {
                	    frm.AddTemplateReference(refe, new PdfName("n0"), 1, 0, 0, 1, 0, 0);
                    }
                    else {
                	    reuseAppearance = false;
                        if (app[0] == null) {
                            CreateBlankN0();
                        }
                    }
                }
                if (!reuseAppearance) {
            	    frm.AddTemplate(app[0], 0, 0);
                }
                if (!acro6Layers)
                    frm.AddTemplate(app[1], scale, 0, 0, scale, x, y);
                frm.AddTemplate(app[2], 0, 0);
                if (!acro6Layers) {
                    frm.AddTemplate(app[3], scale, 0, 0, scale, x, y);
                    frm.AddTemplate(app[4], 0, 0);
                }
            }
            PdfTemplate napp = new PdfTemplate(writer);
            napp.BoundingBox = rotated;
            writer.AddDirectTemplateSimple(napp, null);
            napp.AddTemplate(frm, 0, 0);
            return napp;
        }
Пример #18
0
        public void CreateTaggedPdf2() {
            InitializeDocument("2");
            Paragraph paragraph = new Paragraph(text);
            ColumnText columnText = new ColumnText(writer.DirectContent);

            columnText.SetSimpleColumn(36, 36, 400, 800);
            columnText.AddElement(h1);
            columnText.AddElement(paragraph);
            columnText.Go();
            document.NewPage();
            columnText.SetSimpleColumn(36, 36, 400, 800);
            columnText.Go();
            document.Close();
            //        int[] nums = new int[]{237, 47} ;
            //        CheckNums("2", nums);
            CompareResults("2");
        }
Пример #19
0
        private int floatingLayout(List <IElement> floatingElements, bool simulate)
        {
            int   status     = ColumnText.NO_MORE_TEXT;
            float minYLine   = yLine;
            float leftWidth  = 0;
            float rightWidth = 0;

            while (floatingElements.Count > 0)
            {
                if (floatingElements[0] is PdfDiv)
                {
                    PdfDiv floatingElement = (PdfDiv)floatingElements[0];
                    status = floatingElement.layout(compositeColumn, true, floatLeftX, minY, floatRightX, yLine);
                    if ((status & ColumnText.NO_MORE_TEXT) == 0)
                    {
                        yLine       = minYLine;
                        floatLeftX  = leftX;
                        floatRightX = rightX;
                        status      = floatingElement.layout(compositeColumn, true, floatLeftX, minY, floatRightX, yLine);
                        //if ((status & ColumnText.NO_MORE_TEXT) == 0) {
                        //    break;
                        //}
                    }
                    if (floatingElement.Float == PdfDiv.FloatType.LEFT)
                    {
                        status      = floatingElement.layout(compositeColumn, simulate, floatLeftX, minY, floatRightX, yLine);
                        floatLeftX += floatingElement.getActualWidth();
                        leftWidth  += floatingElement.getActualWidth();
                    }
                    else if (floatingElement.Float == PdfDiv.FloatType.RIGHT)
                    {
                        status       = floatingElement.layout(compositeColumn, simulate, floatRightX - floatingElement.getActualWidth() - 0.01f, minY, floatRightX, yLine);
                        floatRightX -= floatingElement.getActualWidth();
                        rightWidth  += floatingElement.getActualWidth();
                    }
                    minYLine = Math.Min(minYLine, yLine - floatingElement.getActualHeight());
                }
                else
                {
                    IElement firstElement = floatingElements[0];
                    if (firstElement is ISpaceable)
                    {
                        yLine -= ((ISpaceable)firstElement).SpacingBefore;
                    }
                    compositeColumn.AddElement(firstElement);
                    if (yLine > minYLine)
                    {
                        compositeColumn.SetSimpleColumn(floatLeftX, yLine, floatRightX, minYLine);
                    }
                    else
                    {
                        compositeColumn.SetSimpleColumn(floatLeftX, yLine, floatRightX, minY);
                    }

                    compositeColumn.FilledWidth = 0;

                    status = compositeColumn.Go(simulate);
                    if (yLine > minYLine && (floatLeftX > leftX || floatRightX < rightX) && (status & ColumnText.NO_MORE_TEXT) == 0)
                    {
                        yLine       = minYLine;
                        floatLeftX  = leftX;
                        floatRightX = rightX;
                        if (leftWidth != 0 && rightWidth != 0)
                        {
                            filledWidth = rightX - leftX;
                        }
                        else
                        {
                            if (leftWidth > filledWidth)
                            {
                                filledWidth = leftWidth;
                            }
                            if (rightWidth > filledWidth)
                            {
                                filledWidth = rightWidth;
                            }
                        }

                        leftWidth  = 0;
                        rightWidth = 0;
                        compositeColumn.SetSimpleColumn(floatLeftX, yLine, floatRightX, minY);
                        status   = compositeColumn.Go(simulate);
                        minYLine = compositeColumn.YLine + compositeColumn.Descender;
                        yLine    = minYLine;
                        if (compositeColumn.FilledWidth > filledWidth)
                        {
                            filledWidth = compositeColumn.FilledWidth;
                        }
                    }
                    else
                    {
                        if (rightWidth > 0)
                        {
                            rightWidth += compositeColumn.FilledWidth;
                        }
                        else if (leftWidth > 0)
                        {
                            leftWidth += compositeColumn.FilledWidth;
                        }
                        else if (compositeColumn.FilledWidth > filledWidth)
                        {
                            filledWidth = compositeColumn.FilledWidth;
                        }
                        minYLine = Math.Min(compositeColumn.YLine + compositeColumn.Descender, minYLine);
                        yLine    = compositeColumn.YLine + compositeColumn.Descender;
                    }

                    compositeColumn.CompositeElements.Clear();
                    //if ((status & ColumnText.NO_MORE_TEXT) == 0) {
                    //    break;
                    //}
                }

                floatingElements.RemoveAt(0);
            }


            if (leftWidth != 0 && rightWidth != 0)
            {
                filledWidth = rightX - leftX;
            }
            else
            {
                if (leftWidth > filledWidth)
                {
                    filledWidth = leftWidth;
                }
                if (rightWidth > filledWidth)
                {
                    filledWidth = rightWidth;
                }
            }

            yLine       = minYLine;
            floatLeftX  = leftX;
            floatRightX = rightX;

            return(status);
        }
Пример #20
0
        /**
        * Gets the main appearance layer.
        * <p>
        * Consult <A HREF="http://partners.adobe.com/asn/developer/pdfs/tn/PPKAppearances.pdf">PPKAppearances.pdf</A>
        * for further details.
        * @return the main appearance layer
        * @throws DocumentException on error
        * @throws IOException on error
        */
        public PdfTemplate GetAppearance()
        {
            if (IsInvisible()) {
                PdfTemplate t = new PdfTemplate(writer);
                t.BoundingBox = new Rectangle(0, 0);
                writer.AddDirectTemplateSimple(t, null);
                return t;
            }
            if (app[0] == null) {
                PdfTemplate t = app[0] = new PdfTemplate(writer);
                t.BoundingBox = new Rectangle(100, 100);
                writer.AddDirectTemplateSimple(t, new PdfName("n0"));
                t.SetLiteral("% DSBlank\n");
            }
            if (app[1] == null && !acro6Layers) {
                PdfTemplate t = app[1] = new PdfTemplate(writer);
                t.BoundingBox = new Rectangle(100, 100);
                writer.AddDirectTemplateSimple(t, new PdfName("n1"));
                t.SetLiteral(questionMark);
            }
            if (app[2] == null) {
                String text;
                if (layer2Text == null) {
                    StringBuilder buf = new StringBuilder();
                    buf.Append("Digitally signed by ").Append(PdfPKCS7.GetSubjectFields((X509Certificate)certChain[0]).GetField("CN")).Append('\n');
                    buf.Append("Date: ").Append(signDate.ToString("yyyy.MM.dd HH:mm:ss zzz"));
                    if (reason != null)
                        buf.Append('\n').Append("Reason: ").Append(reason);
                    if (location != null)
                        buf.Append('\n').Append("Location: ").Append(location);
                    text = buf.ToString();
                }
                else
                    text = layer2Text;
                PdfTemplate t = app[2] = new PdfTemplate(writer);
                t.BoundingBox = rect;
                writer.AddDirectTemplateSimple(t, new PdfName("n2"));
                if (image != null) {
                    if (imageScale == 0) {
                        t.AddImage(image, rect.Width, 0, 0, rect.Height, 0, 0);
                    }
                    else {
                        float usableScale = imageScale;
                        if (imageScale < 0)
                            usableScale = Math.Min(rect.Width / image.Width, rect.Height / image.Height);
                        float w = image.Width * usableScale;
                        float h = image.Height * usableScale;
                        float x = (rect.Width - w) / 2;
                        float y = (rect.Height - h) / 2;
                        t.AddImage(image, w, 0, 0, h, x, y);
                    }
                }
                Font font;
                if (layer2Font == null)
                    font = new Font();
                else
                    font = new Font(layer2Font);
                float size = font.Size;

                Rectangle dataRect = null;
                Rectangle signatureRect = null;

                if (Render == SignatureRender.NameAndDescription ||
                    (Render == SignatureRender.GraphicAndDescription && this.SignatureGraphic != null)) {
                    // origin is the bottom-left
                    signatureRect = new Rectangle(
                        MARGIN,
                        MARGIN,
                        rect.Width / 2 - MARGIN,
                        rect.Height - MARGIN);
                    dataRect = new Rectangle(
                        rect.Width / 2 +  MARGIN / 2,
                        MARGIN,
                        rect.Width - MARGIN / 2,
                        rect.Height - MARGIN);

                    if (rect.Height > rect.Width) {
                        signatureRect = new Rectangle(
                            MARGIN,
                            rect.Height / 2,
                            rect.Width - MARGIN,
                            rect.Height);
                        dataRect = new Rectangle(
                            MARGIN,
                            MARGIN,
                            rect.Width - MARGIN,
                            rect.Height / 2 - MARGIN);
                    }
                }
                else {
                    dataRect = new Rectangle(
                        MARGIN,
                        MARGIN,
                        rect.Width - MARGIN,
                        rect.Height * (1 - TOP_SECTION) - MARGIN);
                }

                if (Render == SignatureRender.NameAndDescription) {
                    string signedBy = iTextSharp.text.pdf.PdfPKCS7.GetSubjectFields(this.certChain[0]).GetField("CN");
                    Rectangle sr2 = new Rectangle(signatureRect.Width - MARGIN, signatureRect.Height - MARGIN );
                    float signedSize = FitText(font, signedBy, sr2, -1, runDirection);

                    ColumnText ct2 = new ColumnText(t);
                    ct2.RunDirection = runDirection;
                    ct2.SetSimpleColumn(new Phrase(signedBy, font), signatureRect.Left, signatureRect.Bottom, signatureRect.Right, signatureRect.Top, signedSize, Element.ALIGN_LEFT);

                    ct2.Go();
                }
                else if (Render == SignatureRender.GraphicAndDescription) {
                    ColumnText ct2 = new ColumnText(t);
                    ct2.RunDirection = runDirection;
                    ct2.SetSimpleColumn(signatureRect.Left, signatureRect.Bottom, signatureRect.Right, signatureRect.Top, 0, Element.ALIGN_RIGHT);

                    Image im = Image.GetInstance(SignatureGraphic);
                    im.ScaleToFit(signatureRect.Width, signatureRect.Height);

                    Paragraph p = new Paragraph();
                    // must calculate the point to draw from to make image appear in middle of column
                    float x = 0;
                    // experimentation found this magic number to counteract Adobe's signature graphic, which
                    // offsets the y co-ordinate by 15 units
                    float y = -im.ScaledHeight + 15;

                    x = x + (signatureRect.Width - im.ScaledWidth) / 2;
                    y = y - (signatureRect.Height - im.ScaledHeight) / 2;
                    p.Add(new Chunk(im, x + (signatureRect.Width - im.ScaledWidth) / 2, y, false));
                    ct2.AddElement(p);
                    ct2.Go();
                }

                if (size <= 0) {
                    Rectangle sr = new Rectangle(dataRect.Width, dataRect.Height);
                    size = FitText(font, text, sr, 12, runDirection);
                }
                ColumnText ct = new ColumnText(t);
                ct.RunDirection = runDirection;
                ct.SetSimpleColumn(new Phrase(text, font), dataRect.Left, dataRect.Bottom, dataRect.Right, dataRect.Top, size, Element.ALIGN_LEFT);
                ct.Go();

            }
            if (app[3] == null && !acro6Layers) {
                PdfTemplate t = app[3] = new PdfTemplate(writer);
                t.BoundingBox = new Rectangle(100, 100);
                writer.AddDirectTemplateSimple(t, new PdfName("n3"));
                t.SetLiteral("% DSBlank\n");
            }
            if (app[4] == null && !acro6Layers) {
                PdfTemplate t = app[4] = new PdfTemplate(writer);
                t.BoundingBox = new Rectangle(0, rect.Height * (1 - TOP_SECTION), rect.Right, rect.Top);
                writer.AddDirectTemplateSimple(t, new PdfName("n4"));
                Font font;
                if (layer2Font == null)
                    font = new Font();
                else
                    font = new Font(layer2Font);
                float size = font.Size;
                String text = "Signature Not Verified";
                if (layer4Text != null)
                    text = layer4Text;
                Rectangle sr = new Rectangle(rect.Width - 2 * MARGIN, rect.Height * TOP_SECTION - 2 * MARGIN);
                size = FitText(font, text, sr, 15, runDirection);
                ColumnText ct = new ColumnText(t);
                ct.RunDirection = runDirection;
                ct.SetSimpleColumn(new Phrase(text, font), MARGIN, 0, rect.Width - MARGIN, rect.Height - MARGIN, size, Element.ALIGN_LEFT);
                ct.Go();
            }
            int rotation = writer.reader.GetPageRotation(page);
            Rectangle rotated = new Rectangle(rect);
            int n = rotation;
            while (n > 0) {
                rotated = rotated.Rotate();
                n -= 90;
            }
            if (frm == null) {
                frm = new PdfTemplate(writer);
                frm.BoundingBox = rotated;
                writer.AddDirectTemplateSimple(frm, new PdfName("FRM"));
                float scale = Math.Min(rect.Width, rect.Height) * 0.9f;
                float x = (rect.Width - scale) / 2;
                float y = (rect.Height - scale) / 2;
                scale /= 100;
                if (rotation == 90)
                    frm.ConcatCTM(0, 1, -1, 0, rect.Height, 0);
                else if (rotation == 180)
                    frm.ConcatCTM(-1, 0, 0, -1, rect.Width, rect.Height);
                else if (rotation == 270)
                    frm.ConcatCTM(0, -1, 1, 0, 0, rect.Width);
                frm.AddTemplate(app[0], 0, 0);
                if (!acro6Layers)
                    frm.AddTemplate(app[1], scale, 0, 0, scale, x, y);
                frm.AddTemplate(app[2], 0, 0);
                if (!acro6Layers) {
                    frm.AddTemplate(app[3], scale, 0, 0, scale, x, y);
                    frm.AddTemplate(app[4], 0, 0);
                }
            }
            PdfTemplate napp = new PdfTemplate(writer);
            napp.BoundingBox = rotated;
            writer.AddDirectTemplateSimple(napp, null);
            napp.AddTemplate(frm, 0, 0);
            return napp;
        }
Пример #21
0
        public virtual void NestedTableTest() {
            Document doc = new Document(PageSize.A4);
            String file = "nestedtabletest.pdf";
            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(OUTPUT_FOLDER + file, FileMode.Create));
            doc.Open();

            ColumnText col = new ColumnText(writer.DirectContent);
            col.SetSimpleColumn(
                Utilities.MillimetersToPoints(25),
                Utilities.MillimetersToPoints(25),
                PageSize.A4.Right - Utilities.MillimetersToPoints(25),
                PageSize.A4.Top - Utilities.MillimetersToPoints(25));

            PdfPTable table = new PdfPTable(3);
            table.HeaderRows = 1;
            table.AddCell("H1");
            table.AddCell("H2");
            table.AddCell("H3");

            for (int i = 0; i < 15; i++) {
                PdfPCell cell = new PdfPCell(createNestedTable());
                cell.Rowspan = 3;
                cell.Colspan = 3;
                table.AddCell(cell);
            }
            col.AddElement(table);

            while (ColumnText.HasMoreText(col.Go())) {
                doc.NewPage();
                col.YLine = PageSize.A4.Top - Utilities.MillimetersToPoints(25);
            }

            doc.Close();

            // compare
            CompareTool compareTool = new CompareTool();
            String errorMessage = compareTool.CompareByContent(OUTPUT_FOLDER + file, CMP_FOLDER + file, OUTPUT_FOLDER, "diff");
            if (errorMessage != null) {
                Assert.Fail(errorMessage);
            }
        }
Пример #22
0
        private int FloatingLayout(List <IElement> floatingElements, bool simulate)
        {
            int   status     = ColumnText.NO_MORE_TEXT;
            float minYLine   = yLine;
            float leftWidth  = 0;
            float rightWidth = 0;

            ColumnText currentCompositeColumn = compositeColumn;

            if (simulate)
            {
                currentCompositeColumn = ColumnText.Duplicate(compositeColumn);
            }

            bool ignoreSpacingBefore = maxY == yLine;

            while (floatingElements.Count > 0)
            {
                IElement nextElement = floatingElements[0];
                floatingElements.RemoveAt(0);
                if (nextElement is PdfDiv)
                {
                    PdfDiv floatingElement = (PdfDiv)nextElement;
                    status = floatingElement.Layout(compositeColumn.Canvas, useAscender, true, floatLeftX, minY, floatRightX, yLine);
                    if ((status & ColumnText.NO_MORE_TEXT) == 0)
                    {
                        yLine       = minYLine;
                        floatLeftX  = leftX;
                        floatRightX = rightX;
                        status      = floatingElement.Layout(compositeColumn.Canvas, useAscender, true, floatLeftX, minY, floatRightX, yLine);
                        if ((status & ColumnText.NO_MORE_TEXT) == 0)
                        {
                            floatingElements.Insert(0, floatingElement);
                            break;
                        }
                    }
                    if (floatingElement.Float == PdfDiv.FloatType.LEFT)
                    {
                        status      = floatingElement.Layout(compositeColumn.Canvas, useAscender, simulate, floatLeftX, minY, floatRightX, yLine);
                        floatLeftX += floatingElement.getActualWidth();
                        leftWidth  += floatingElement.getActualWidth();
                    }
                    else if (floatingElement.Float == PdfDiv.FloatType.RIGHT)
                    {
                        status       = floatingElement.Layout(compositeColumn.Canvas, useAscender, simulate, floatRightX - floatingElement.getActualWidth() - 0.01f, minY, floatRightX, yLine);
                        floatRightX -= floatingElement.getActualWidth();
                        rightWidth  += floatingElement.getActualWidth();
                    }
                    minYLine = Math.Min(minYLine, yLine - floatingElement.getActualHeight());
                }
                else
                {
                    if (minY > minYLine)
                    {
                        status = ColumnText.NO_MORE_COLUMN;
                        floatingElements.Insert(0, nextElement);
                        if (currentCompositeColumn != null)
                        {
                            currentCompositeColumn.SetText(null);
                        }
                        break;
                    }
                    else
                    {
                        if (nextElement is ISpaceable && (!ignoreSpacingBefore || !currentCompositeColumn.IgnoreSpacingBefore || ((ISpaceable)nextElement).PaddingTop != 0))
                        {
                            yLine -= ((ISpaceable)nextElement).SpacingBefore;
                        }
                        if (simulate)
                        {
                            if (nextElement is PdfPTable)
                            {
                                currentCompositeColumn.AddElement(new PdfPTable((PdfPTable)nextElement));
                            }
                            else
                            {
                                currentCompositeColumn.AddElement(nextElement);
                            }
                        }
                        else
                        {
                            currentCompositeColumn.AddElement(nextElement);
                        }

                        if (yLine > minYLine)
                        {
                            currentCompositeColumn.SetSimpleColumn(floatLeftX, yLine, floatRightX, minYLine);
                        }
                        else
                        {
                            currentCompositeColumn.SetSimpleColumn(floatLeftX, yLine, floatRightX, minY);
                        }

                        currentCompositeColumn.FilledWidth = 0;

                        status = currentCompositeColumn.Go(simulate);
                        if (yLine > minYLine && (floatLeftX > leftX || floatRightX < rightX) &&
                            (status & ColumnText.NO_MORE_TEXT) == 0)
                        {
                            yLine       = minYLine;
                            floatLeftX  = leftX;
                            floatRightX = rightX;
                            if (leftWidth != 0 && rightWidth != 0)
                            {
                                filledWidth = rightX - leftX;
                            }
                            else
                            {
                                if (leftWidth > filledWidth)
                                {
                                    filledWidth = leftWidth;
                                }
                                if (rightWidth > filledWidth)
                                {
                                    filledWidth = rightWidth;
                                }
                            }

                            leftWidth  = 0;
                            rightWidth = 0;
                            if (simulate && nextElement is PdfPTable)
                            {
                                currentCompositeColumn.AddElement(new PdfPTable((PdfPTable)nextElement));
                            }

                            currentCompositeColumn.SetSimpleColumn(floatLeftX, yLine, floatRightX, minY);
                            status   = currentCompositeColumn.Go(simulate);
                            minYLine = currentCompositeColumn.YLine + currentCompositeColumn.Descender;
                            yLine    = minYLine;
                            if (currentCompositeColumn.FilledWidth > filledWidth)
                            {
                                filledWidth = currentCompositeColumn.FilledWidth;
                            }
                        }
                        else
                        {
                            if (rightWidth > 0)
                            {
                                rightWidth += currentCompositeColumn.FilledWidth;
                            }
                            else if (leftWidth > 0)
                            {
                                leftWidth += currentCompositeColumn.FilledWidth;
                            }
                            else if (currentCompositeColumn.FilledWidth > filledWidth)
                            {
                                filledWidth = currentCompositeColumn.FilledWidth;
                            }
                            minYLine = Math.Min(currentCompositeColumn.YLine + currentCompositeColumn.Descender, minYLine);
                            yLine    = currentCompositeColumn.YLine + currentCompositeColumn.Descender;
                        }

                        if ((status & ColumnText.NO_MORE_TEXT) == 0)
                        {
                            if (!simulate)
                            {
                                floatingElements.InsertRange(0, currentCompositeColumn.CompositeElements);
                                currentCompositeColumn.CompositeElements.Clear();
                            }
                            else
                            {
                                floatingElements.Insert(0, nextElement);
                                currentCompositeColumn.SetText(null);
                            }
                            break;
                        }
                        else
                        {
                            currentCompositeColumn.SetText(null);
                        }
                    }
                }
                if (nextElement is Paragraph)
                {
                    Paragraph p = (Paragraph)nextElement;
                    foreach (IElement e in p)
                    {
                        if (e is WritableDirectElement)
                        {
                            WritableDirectElement writableElement = (WritableDirectElement)e;
                            if (writableElement.DirectElemenType == WritableDirectElement.DIRECT_ELEMENT_TYPE_HEADER && !simulate)
                            {
                                PdfWriter   writer = compositeColumn.Canvas.PdfWriter;
                                PdfDocument doc    = compositeColumn.Canvas.PdfDocument;

                                // here is used a little hack:
                                // writableElement.write() method implementation uses PdfWriter.getVerticalPosition() to create PdfDestination (see com.itextpdf.tool.xml.html.Header),
                                // so here we are adjusting document's currentHeight in order to make getVerticalPosition() return value corresponding to real current position
                                float savedHeight = doc.currentHeight;
                                doc.currentHeight = doc.Top - yLine - doc.indentation.indentTop;
                                writableElement.Write(writer, doc);
                                doc.currentHeight = savedHeight;
                            }
                        }
                    }
                }
                if (ignoreSpacingBefore && nextElement.Chunks.Count == 0)
                {
                    if (nextElement is Paragraph)
                    {
                        Paragraph p = (Paragraph)nextElement;
                        IElement  e = p[0];
                        if (e is WritableDirectElement)
                        {
                            WritableDirectElement writableDirectElement = (WritableDirectElement)e;
                            if (writableDirectElement.DirectElemenType != WritableDirectElement.DIRECT_ELEMENT_TYPE_HEADER)
                            {
                                ignoreSpacingBefore = false;
                            }
                        }
                    }
                    else if (nextElement is ISpaceable)
                    {
                        ignoreSpacingBefore = false;
                    }
                }
                else
                {
                    ignoreSpacingBefore = false;
                }
            }

            if (leftWidth != 0 && rightWidth != 0)
            {
                filledWidth = rightX - leftX;
            }
            else
            {
                if (leftWidth > filledWidth)
                {
                    filledWidth = leftWidth;
                }
                if (rightWidth > filledWidth)
                {
                    filledWidth = rightWidth;
                }
            }

            yLine       = minYLine;
            floatLeftX  = leftX;
            floatRightX = rightX;

            return(status);
        }
Пример #23
0
 public void TabStopOutOfPageBoundColumnTextTest() {
     Font f = FontFactory.GetFont(FontFactory.COURIER, 11);
     Document doc = new Document();
     Paragraph p;
     FileStream fs = new FileStream(TARGET + "/tabStopOutColumnText.pdf", FileMode.Create);
     PdfWriter writer = PdfWriter.GetInstance(doc, fs);
     writer.CompressionLevel = 0;
     doc.Open();
     ColumnText ct = new ColumnText(writer.DirectContent);
     ct.SetSimpleColumn(36, 0, 436, 836);
     f.Size = 16;
     p = new Paragraph(Chunk.TABBING);
     p.Add(new Chunk("Hello world", f));
     List<TabStop> tabStopsList = new List<TabStop>();
     tabStopsList.Add(new TabStop(1000, new DottedLineSeparator()));
     tabStopsList.Add(new TabStop(1050, new LineSeparator(), TabStop.Alignment.ANCHOR, ','));
     tabStopsList.Add(new TabStop(1100, new DottedLineSeparator(), TabStop.Alignment.ANCHOR));
     p.TabSettings = new TabSettings(tabStopsList, 50);
     AddTabs(p, f, 15, "l.aal");
     AddTabs(p, f, 13, "laa,l");
     AddTabs(p, f, 13, "laa.l");
     AddTabs(p, f, 13, "l,aal");
     ct.AddElement(p);
     ct.Go();
     doc.Close();
     writer.Close();
     Assert.IsTrue(CompareInnerText(SOURCE17, TARGET + "/tabStopOutColumnText.pdf"));
 }
Пример #24
0
        public void CreateTaggedPdf14() {
            InitializeDocument("14");
            Paragraph paragraph = new Paragraph("Document MUST contain 1 page only!");
            document.NewPage();
            ColumnText columnText = new ColumnText(writer.DirectContent);
            columnText.SetSimpleColumn(36, 36, 250, 800);
            columnText.AddElement(paragraph);
            columnText.Go();
            document.Close();

            int[] nums = new int[] {3};
            CheckNums(nums);

            PdfReader reader = new PdfReader(OUT + "14.pdf");
            Assert.AreEqual(1, reader.NumberOfPages);
        }
Пример #25
0
        virtual public void TabspaceColumnTextTest() {
            Font f = FontFactory.GetFont(FontFactory.COURIER, 11);
            Document doc = new Document();
            Paragraph p;
            FileStream fs = new FileStream(OUTABSPACEC, FileMode.Create);
            PdfWriter writer = PdfWriter.GetInstance(doc, fs);
            writer.CompressionLevel = 0;
            doc.Open();
            ColumnText ct = new ColumnText(writer.DirectContent);
            ct.SetSimpleColumn(36, 36, 436, 800);
            p = new Paragraph(new Chunk("Hello world", f));
            AddTabspaces(p, f, 0);
            ct.AddElement(p);

            p = new Paragraph(new Chunk("Hello World!!!"));
            AddTabspaces(p, f, 0);
            ct.AddElement(p);

            f.Size = 16;
            p = new Paragraph(new Chunk("Hello world", f));
            AddTabspaces(p, f, 0);
            ct.AddElement(p);

            f = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12);
            p = new Paragraph(new Chunk("Hello world", f));
            AddTabspaces(p, f, 0);
            ct.AddElement(p);

            f.Size = 20;
            p = new Paragraph(new Chunk("Hello world", f));
            AddTabspaces(p, f, 0);
            ct.AddElement(p);
            ct.Go();
            doc.Close();
            fs.Close();
            Assert.IsTrue(CompareInnerText(SOURCE12, OUTABSPACEC));
        }
Пример #26
0
        public void CreateTaggedPdf20() {
            InitializeDocument("20");

            Paragraph paragraph = new Paragraph();
            paragraph.Font.Color = BaseColor.RED;
            Chunk c = new Chunk("Hello ");
            paragraph.Add(c);
            c = new Chunk("  world\n\n");
            paragraph.Add(c);

            ColumnText columnText = new ColumnText(writer.DirectContent);
            columnText.SetSimpleColumn(36, 36, 250, 800);
            columnText.AddElement(paragraph);
            columnText.Go();

            PdfTemplate template = writer.DirectContent.CreateTemplate(PageSize.A4.Width, PageSize.A4.Height);
            writer.DirectContent.AddTemplate(template, 0, 0, true);

            columnText = new ColumnText(template);
            columnText.SetSimpleColumn(36, 36, 250, 750);
            columnText.AddText(new Phrase(new Chunk("Hello word \n")));
            columnText.Go();

            document.NewPage();

            paragraph = new Paragraph();
            paragraph.Font.Color = BaseColor.RED;
            c = new Chunk("Hello ");
            paragraph.Add(c);
            c = new Chunk("  world\n");
            paragraph.Add(c);

            columnText = new ColumnText(template);
            columnText.SetSimpleColumn(36, 36, 250, 700);
            columnText.AddElement(paragraph);
            columnText.Go();

            template = writer.DirectContent.CreateTemplate(PageSize.A4.Width, PageSize.A4.Height);
            writer.DirectContent.AddTemplate(template, 0, 0, true);

            paragraph = new Paragraph();
            paragraph.Font.Color = BaseColor.GREEN;
            c = new Chunk("Hello ");
            paragraph.Add(c);
            c = new Chunk("  world\n");
            paragraph.Add(c);

            columnText = new ColumnText(template);
            columnText.SetSimpleColumn(36, 36, 250, 800);
            columnText.AddElement(paragraph);
            columnText.Go();

            paragraph = new Paragraph();
            paragraph.Font.Color = BaseColor.BLUE;
            c = new Chunk("Hello ");
            paragraph.Add(c);
            c = new Chunk("  world\n");
            paragraph.Add(c);

            template = writer.DirectContent.CreateTemplate(PageSize.A4.Width, PageSize.A4.Height);

            columnText = new ColumnText(template);
            columnText.SetSimpleColumn(36, 36, 250, 650);
            columnText.AddElement(paragraph);
            columnText.Go();

            writer.DirectContent.AddTemplate(template, 0, 100);

            writer.DirectContent.AddTemplate(template, 0, 50);

            writer.DirectContent.AddTemplate(template, 0, 0);

            document.Close();
            CompareResults("20");
        }
Пример #27
0
        public override void ExecuteResult(ControllerContext context)
        {
            var Response = context.HttpContext.Response;

            CmsData.Meeting meeting = null;
            if (meetingid.HasValue)
            {
                meeting = DbUtil.Db.Meetings.Single(mt => mt.MeetingId == meetingid);
                dt = meeting.MeetingDate;
                orgid = meeting.OrganizationId;
            }

            var list1 = bygroup == true ? ReportList2().ToList() : ReportList().ToList();

            if (!list1.Any())
            {
                Response.Write("no data found");
                return;
            }
            if (!dt.HasValue)
            {
                Response.Write("bad date");
                return;
            }
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "filename=foo.pdf");

            doc = new Document(PageSize.LETTER.Rotate(), 36, 36, 64, 64);
            var w = PdfWriter.GetInstance(doc, Response.OutputStream);
            w.PageEvent = pageEvents;
            doc.Open();
            dc = w.DirectContent;

            box = new PdfPCell();
            box.Border = PdfPCell.NO_BORDER;
            box.CellEvent = new CellEvent();
            PdfPTable table = null;

            OrgInfo lasto = null;
            foreach (var o in list1)
            {
                lasto = o;
                table = new PdfPTable(1);
                table.DefaultCell.Border = PdfPCell.NO_BORDER;
                table.DefaultCell.Padding = 0;
                table.WidthPercentage = 100;
                if (meeting != null)
                {
                    var Groups = o.Groups;
                    if (Groups[0] == 0)
                    {
                        var q = from at in meeting.Attends
                                where at.AttendanceFlag == true || at.Commitment == AttendCommitmentCode.Attending || at.Commitment == AttendCommitmentCode.Substitute
                                orderby at.Person.LastName, at.Person.FamilyId, at.Person.Name2
                                select new
                                           {
                                               at.MemberType.Code,
                                               Name2 = (altnames == true && at.Person.AltName != null && at.Person.AltName.Length > 0) ? at.Person.AltName : at.Person.Name2,
                                               at.PeopleId,
                                               at.Person.DOB,
                                           };
                        if (q.Any())
                            StartPageSet(o);
                        foreach (var a in q)
                            table.AddCell(AddRow(a.Code, a.Name2, a.PeopleId, a.DOB, "", font));
                    }
                    else
                    {
                        var q = from at in meeting.Attends
                                let om =
                                    at.Organization.OrganizationMembers.SingleOrDefault(mm => mm.PeopleId == at.PeopleId)
                                let gc = om.OrgMemMemTags.Count(mt => Groups.Contains(mt.MemberTagId))
                                where gc == Groups.Length || Groups[0] <= 0
                                where gc > 0
                                where !Groups.Contains(-1) || (Groups.Contains(-1) && om.OrgMemMemTags.Count() == 0)
                                where
                                    at.AttendanceFlag == true || at.Commitment == AttendCommitmentCode.Attending ||
                                    at.Commitment == AttendCommitmentCode.Substitute
                                orderby at.Person.LastName, at.Person.FamilyId, at.Person.Name2
                                select new
                                           {
                                               at.MemberType.Code,
                                               Name2 = (altnames == true && at.Person.AltName != null && at.Person.AltName.Length > 0) ? at.Person.AltName : at.Person.Name2,
                                               at.PeopleId,
                                               at.Person.DOB,
                                           };
                        if (q.Any())
                            StartPageSet(o);
                        foreach (var a in q)
                            table.AddCell(AddRow(a.Code, a.Name2, a.PeopleId, a.DOB, "", font));
                    }
                }
                else
                {
                    var Groups = o.Groups;
                    if (Groups == null)
                        Groups = new int[] { 0 };
                    var q = from om in DbUtil.Db.OrganizationMembers
                            where om.OrganizationId == o.OrgId
                            let gc = om.OrgMemMemTags.Count(mt => Groups.Contains(mt.MemberTagId))
                            where gc == Groups.Length || Groups[0] <= 0
                            where !Groups.Contains(-1) || (Groups.Contains(-1) && om.OrgMemMemTags.Count() == 0)
                            where (om.Pending ?? false) == false
                            where om.MemberTypeId != MemberTypeCode.InActive
                            where om.MemberTypeId != MemberTypeCode.Prospect
                            where om.EnrollmentDate <= Util.Now
                            orderby om.Person.LastName, om.Person.FamilyId, om.Person.Name2
                            let p = om.Person
                            let ch = altnames == true && p.AltName != null && p.AltName.Length > 0
                            select new
                            {
                                PeopleId = p.PeopleId,
                                Name2 = ch ? p.AltName : p.Name2,
                                BirthDate = Util.FormatBirthday(
                                    p.BirthYear,
                                    p.BirthMonth,
                                    p.BirthDay),
                                MemberTypeCode = om.MemberType.Code,
                                ch,
                                highlight = om.OrgMemMemTags.Any(mm => mm.MemberTag.Name == highlightsg) ? highlightsg : ""
                            };
                    if (q.Any())
                        StartPageSet(o);
                    foreach (var m in q)
                        table.AddCell(AddRow(m.MemberTypeCode, m.Name2, m.PeopleId, m.BirthDate, m.highlight, m.ch ? china : font));
                }

                if (bygroup == false && groups[0] == 0 && meeting == null)
                {
                    foreach ( var m in RollsheetModel.FetchVisitors(o.OrgId, dt.Value, NoCurrentMembers: true, UseAltNames: altnames == true))
                    {
                        if(table.Rows.Count == 0)
                            StartPageSet(o);
                        table.AddCell(AddRow(m.VisitorType, m.Name2, m.PeopleId, m.BirthDate, "", boldfont));
                    }
                }
                if (!pageSetStarted)
                    continue;

                var col = 0;
                float gutter = 20f;
                float colwidth = (doc.Right - doc.Left - gutter) / 2;
                var ct = new ColumnText(w.DirectContent);
                ct.AddElement(table);

                int status = 0;

                while (ColumnText.HasMoreText(status))
                {
                    if(col == 0)
                        ct.SetSimpleColumn(doc.Left, doc.Bottom, doc.Left + colwidth, doc.Top);
                    else
                        ct.SetSimpleColumn(doc.Right - colwidth, doc.Bottom, doc.Right, doc.Top);
                    status = ct.Go();
                    ++col;
                    if (col > 1)
                    {
                        col = 0;
                        doc.NewPage();
                    }
                }

            //                foreach (var li in list)
            //                {
            //                    y = ct.YLine;
            //                    ct.AddElement(li);
            //                    status = ct.Go(true);
            //                    if (ColumnText.HasMoreText(status))
            //                    {
            //                        ++col;
            //                        if (col > 1)
            //                        {
            //                            col = 0;
            //                            doc.NewPage();
            //                        }
            //                        ct.SetSimpleColumn(cols[col]);
            //                        y = doc.Top;
            //                    }
            //                    ct.YLine = y;
            //                    ct.SetText(null);
            //                    ct.AddElement(li);
            //                    status = ct.Go();
            //                }
            }
            if (!hasRows)
            {
                if (!pageSetStarted)
                    StartPageSet(lasto);
                doc.Add(new Paragraph("no members as of this meeting date and time to show on rollsheet"));
            }
            doc.Close();
        }
Пример #28
0
        /// <summary>
        /// Adds in the project name, and clien information
        /// </summary>
        /// <param name="cb"></param>
        /// <param name="doc"></param>
        /// <param name="project"></param>
        private void AddProjectInformation(PdfContentByte cb, Document doc, Project project)
        {
            var x = doc.LeftMargin;
            var y = doc.BottomMargin + 185;

            var projName = new Paragraph(project.Name, _coverProjNameFont);

            var client = new Paragraph(string.Format("[Client: {0}]", project.Unit), _coverSmallFont);
            var contact = new Paragraph(string.Format("[Contact: {0}]", project.Contact), _coverSmallFont);

            var ct = new ColumnText(cb);
            ct.SetSimpleColumn(x, y, x + _pageWidth, y + 285);
            ct.Alignment = Element.ALIGN_LEFT | Element.ALIGN_TOP;

            ct.AddElement(projName);
            ct.AddElement(client);
            ct.AddElement(contact);

            ct.Go();
        }
Пример #29
0
// ---------------------------------------------------------------------------
    public bool AddParagraph(Paragraph p, PdfContentByte canvas, 
        AcroFields.FieldPosition f, bool simulate) 
    {
      ColumnText ct = new ColumnText(canvas);
      ct.SetSimpleColumn(
        f.position.Left, f.position.GetBottom(2),
        f.position.GetRight(2), f.position.Top
      );
      ct.AddElement(p);
      return ColumnText.HasMoreText(ct.Go(simulate));
    }
Пример #30
0
        public byte[] ToPDF()
        {
            try
            {
                byte[] pdfBytes;

                using (MemoryStream ms = new MemoryStream())
                {
                    iTextSharp.text.Document doc = new iTextSharp.text.Document();
                    PdfWriter writer = PdfWriter.GetInstance(doc, ms);
                    iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("~/Content/Images/InvoiceSheet/blank_invoice.jpg"));
                    doc.SetPageSize(iTextSharp.text.PageSize.A4);
                    
                    jpg.ScaleToFit(iTextSharp.text.PageSize.A4.Width, iTextSharp.text.PageSize.A4.Height);
                    jpg.Alignment = iTextSharp.text.Image.UNDERLYING;
                    jpg.SetAbsolutePosition(10, -5);

                    doc.Open();
                    doc.Add(jpg);

                    Font defaultFont = new Font(Font.FontFamily.HELVETICA, 7);

                    var cb = writer.DirectContent;

                    ColumnText desc_col = new ColumnText(cb);
                    ColumnText item_col = new ColumnText(cb);
                    ColumnText item_price_col = new ColumnText(cb);
                    ColumnText purchase_col = new ColumnText(cb);
                    ColumnText invoice_col = new ColumnText(cb);
                    ColumnText invoice_date_col = new ColumnText(cb);
                    ColumnText total_sub_price_col = new ColumnText(cb);
                    ColumnText vat_col = new ColumnText(cb);
                    ColumnText total_price_col = new ColumnText(cb);
                    ColumnText job_title_col = new ColumnText(cb);

                    job_title_col.SetSimpleColumn(165, doc.Top - 200, 500, 200, 15, Element.ALIGN_TOP);


                    invoice_col.SetSimpleColumn(doc.Right - 110, doc.Top - 154.2f, 500, 100, 15, Element.ALIGN_TOP);
                    invoice_date_col.SetSimpleColumn(doc.Right - 110, doc.Top - 166.3f, 500, 100, 15, Element.ALIGN_TOP);

                    purchase_col.SetSimpleColumn(200, doc.Top - 270, 500, 100, 15, Element.ALIGN_TOP);
                    desc_col.SetSimpleColumn(165, doc.Top - 320, 415, 200, 15, Element.ALIGN_TOP);
                    item_col.SetSimpleColumn(165, doc.Top - 340, 415, 200, 15, Element.ALIGN_TOP);

                    item_price_col.SetSimpleColumn(doc.Right - 110, doc.Top - 340, 500, 100, 15, Element.ALIGN_TOP);
                    total_sub_price_col.SetSimpleColumn(doc.Right - 110, doc.Bottom - 100, 500, 145, 15, Element.ALIGN_TOP);
                    vat_col.SetSimpleColumn(doc.Right - 110, doc.Bottom - 100, 500, 125, 15, Element.ALIGN_TOP);
                    total_price_col.SetSimpleColumn(doc.Right - 110, doc.Bottom, 500, 105, 15, Element.ALIGN_TOP);

                    job_title_col.AddElement(CreateInfo(this.Title));
                    invoice_col.AddElement(CreateInfo(this.InvoiceNumber.ToString()));
                    invoice_date_col.AddElement(CreateInfo(this.CreatedDate.ToString("dd MMM yyyy")));
                    purchase_col.AddElement(CreateInfo(this.PurchaseOrder));
                    desc_col.AddElement(CreateInfoLight(this.Description));
                    vat_col.AddElement(CreateInfoLight("20%"));

                    // add invoice items to page
                    var items = this.Items;
                    foreach (var item in items)
                    {
                        item_col.AddElement(CreateInfoLight("item title"));
                        item_price_col.AddElement(CreateInfoLight(item.Value.ToString()));
                    }

                    //totals
                    total_sub_price_col.AddElement(CreateInfo(this.SubValue.ToString("C")));
                    total_price_col.AddElement(CreateInfo(this.TotalValue.ToString("C")));


                    job_title_col.Go();
                    purchase_col.Go();
                    invoice_col.Go();
                    invoice_date_col.Go();
                    desc_col.Go();
                    item_col.Go();
                    item_price_col.Go();
                    total_sub_price_col.Go();
                    total_price_col.Go();
                    vat_col.Go();
                 //   column9.Go();
                //    column10.Go();
                  //  column11.Go();

                    doc.Close();

                    pdfBytes = ms.ToArray();
                }

                return pdfBytes;
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #31
0
 public void CreateTaggedPdf1() {
     InitializeDocument("1");
     Paragraph paragraph = new Paragraph(text);
     paragraph.Font = new Font(Font.FontFamily.HELVETICA, 8, Font.NORMAL, BaseColor.RED);
     ColumnText columnText = new ColumnText(writer.DirectContent);
     columnText.SetSimpleColumn(36, 36, 250, 800);
     columnText.AddElement(h1);
     columnText.AddElement(paragraph);
     columnText.Go();
     columnText.SetSimpleColumn(300, 36, 500, 800);
     columnText.Go();
     document.Close();
     int[] nums = new int[] {77};
     CheckNums(nums);
     CompareResults("1");
 }
Пример #32
0
        public void Run(Stream stream, CMSDataContext Db, IEnumerable<ContributorInfo> q, int set = 0)
        {
            pageEvents.set = set;
            pageEvents.PeopleId = 0;
            var contributors = q;

            PdfContentByte dc;
            var font = FontFactory.GetFont(FontFactory.HELVETICA, 11);
            var boldfont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 11);

            var doc = new Document(PageSize.LETTER);
            doc.SetMargins(36f, 30f, 24f, 36f);
            var w = PdfWriter.GetInstance(doc, stream);
            w.PageEvent = pageEvents;
            doc.Open();
            dc = w.DirectContent;

            var prevfid = 0;
            var runningtotals = Db.ContributionsRuns.OrderByDescending(mm => mm.Id).FirstOrDefault();
            runningtotals.Processed = 0;
            Db.SubmitChanges();
            var count = 0;
            foreach (var ci in contributors)
            {

                if (set > 0 && pageEvents.FamilySet[ci.PeopleId] != set)
                    continue;

                var contributions = APIContribution.contributions(Db, ci, FromDate, ToDate).ToList();
                var pledges = APIContribution.pledges(Db, ci, ToDate).ToList();
                var giftsinkind = APIContribution.GiftsInKind(Db, ci, FromDate, ToDate).ToList();
                var nontaxitems = Db.Setting("DisplayNonTaxOnStatement", "false").ToBool()
                    ? APIContribution.NonTaxItems(Db, ci, FromDate, ToDate).ToList()
                    : new List<ContributionInfo>();

                if ((contributions.Count + pledges.Count + giftsinkind.Count + nontaxitems.Count) == 0)
                {
                    runningtotals.Processed += 1;
                    runningtotals.CurrSet = set;
                    Db.SubmitChanges();
                    if (set == 0)
                        pageEvents.FamilySet[ci.PeopleId] = 0;
                    continue;
                }

                pageEvents.NextPeopleId = ci.PeopleId;
                doc.NewPage();
                if (prevfid != ci.FamilyId)
                {
                    prevfid = ci.FamilyId;
                    pageEvents.EndPageSet();
                    pageEvents.PeopleId = ci.PeopleId;
                }
                if (set == 0)
                    pageEvents.FamilySet[ci.PeopleId] = 0;
                count++;

                var css = @"
            <style>
            h1 { font-size: 24px; font-weight:normal; margin-bottom:0; }
            h2 { font-size: 11px; font-weight:normal; margin-top: 0; }
            p { font-size: 11px; }
            </style>
            ";
                //----Church Name

                var t1 = new PdfPTable(1);
                t1.TotalWidth = 72f*5f;
                t1.DefaultCell.Border = Rectangle.NO_BORDER;
                var html1 = Db.ContentHtml("StatementHeader", Resource1.ContributionStatementHeader);
                var html2 = Db.ContentHtml("StatementNotice", Resource1.ContributionStatementNotice);

                var mh = new MyHandler();
                using (var sr = new StringReader(css + html1))
                    XMLWorkerHelper.GetInstance().ParseXHtml(mh, sr);

                var cell = new PdfPCell(t1.DefaultCell);
                foreach (var e in mh.elements)
                    if (e.Chunks.Count > 0)
                        cell.AddElement(e);
                //cell.FixedHeight = 72f * 1.25f;
                t1.AddCell(cell);
                t1.AddCell("\n");

                var t1a = new PdfPTable(1);
                t1a.TotalWidth = 72f*5f;
                t1a.DefaultCell.Border = Rectangle.NO_BORDER;

                var ae = new PdfPTable(1);
                ae.DefaultCell.Border = Rectangle.NO_BORDER;
                ae.WidthPercentage = 100;

                var a = new PdfPTable(1);
                a.DefaultCell.Indent = 25f;
                a.DefaultCell.Border = Rectangle.NO_BORDER;
                a.AddCell(new Phrase(ci.Name, font));
                foreach (var line in ci.MailingAddress.SplitLines())
                    a.AddCell(new Phrase(line, font));
                cell = new PdfPCell(a) {Border = Rectangle.NO_BORDER};
                //cell.FixedHeight = 72f * 1.0625f;
                ae.AddCell(cell);

                cell = new PdfPCell(t1a.DefaultCell);
                cell.AddElement(ae);
                t1a.AddCell(ae);

                //-----Notice

                var t2 = new PdfPTable(1);
                t2.TotalWidth = 72f*3f;
                t2.DefaultCell.Border = Rectangle.NO_BORDER;

                var envno = "";
                if (Db.Setting("PrintEnvelopeNumberOnStatement"))
                {
                    var ev = Person.GetExtraValue(Db, ci.PeopleId, "EnvelopeNumber");
                    var s = Util.PickFirst(ev.Data, ev.IntValue.ToString(), ev.StrValue);
                    if(s.HasValue())
                        envno = $" env: {Util.PickFirst(ev.Data, ev.IntValue.ToString(), ev.StrValue)}";
                }
                t2.AddCell(Db.Setting("NoPrintDateOnStatement")
                    ? new Phrase($"\nid:{ci.PeopleId}{envno} {ci.CampusId}", font)
                    : new Phrase($"\nprinted: {DateTime.Now:d} id:{ci.PeopleId}{envno} {ci.CampusId}", font));

                t2.AddCell("");
                var mh2 = new MyHandler();
                using (var sr = new StringReader(css + html2))
                    XMLWorkerHelper.GetInstance().ParseXHtml(mh2, sr);
                cell = new PdfPCell(t1.DefaultCell);
                foreach (var e in mh2.elements)
                    if (e.Chunks.Count > 0)
                        cell.AddElement(e);
                t2.AddCell(cell);

                // POSITIONING OF ADDRESSES
                //----Header

                var yp = doc.BottomMargin +
                         Db.Setting("StatementRetAddrPos", "10.125").ToFloat()*72f;
                t1.WriteSelectedRows(0, -1,
                    doc.LeftMargin - 0.1875f*72f, yp, dc);

                yp = doc.BottomMargin +
                     Db.Setting("StatementAddrPos", "8.3375").ToFloat()*72f;
                t1a.WriteSelectedRows(0, -1, doc.LeftMargin, yp, dc);

                yp = doc.BottomMargin + 10.125f*72f;
                t2.WriteSelectedRows(0, -1, doc.LeftMargin + 72f*4.4f, yp, dc);

                //----Contributions

                doc.Add(new Paragraph(" "));
                doc.Add(new Paragraph(" ") {SpacingBefore = 72f*2.125f});

                doc.Add(new Phrase($"\n  Period: {FromDate:d} - {ToDate:d}", boldfont));

                var pos = w.GetVerticalPosition(true);

                var ct = new ColumnText(dc);
                var colwidth = (doc.Right - doc.Left);

                var t = new PdfPTable(new[] {15f, 25f, 15f, 15f, 30f});
                t.WidthPercentage = 100;
                t.DefaultCell.Border = Rectangle.NO_BORDER;
                t.HeaderRows = 2;

                cell = new PdfPCell(t.DefaultCell);
                cell.Colspan = 5;
                cell.Phrase = new Phrase("Contributions\n", boldfont);
                t.AddCell(cell);

                t.DefaultCell.Border = Rectangle.BOTTOM_BORDER;
                t.AddCell(new Phrase("Date", boldfont));
                t.AddCell(new Phrase("Description", boldfont));

                cell = new PdfPCell(t.DefaultCell);
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                cell.Phrase = new Phrase("Amount", boldfont);
                t.AddCell(cell);

                cell = new PdfPCell(t.DefaultCell);
                cell.HorizontalAlignment = Element.ALIGN_CENTER;

                if (ShowCheckNo)
                    cell.Phrase = new Phrase("Check No", boldfont);
                else
                    cell.Phrase = new Phrase("", boldfont);

                t.AddCell(cell);

                if (ShowNotes)
                    t.AddCell(new Phrase("Notes", boldfont));
                else
                    t.AddCell(new Phrase("", boldfont));

                t.DefaultCell.Border = Rectangle.NO_BORDER;

                var total = 0m;
                foreach (var c in contributions)
                {
                    t.AddCell(new Phrase(c.ContributionDate.ToShortDateString(), font));
                    t.AddCell(new Phrase(c.Fund, font));

                    cell = new PdfPCell(t.DefaultCell);
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    cell.Phrase = new Phrase(c.ContributionAmount.ToString("N2"), font);
                    t.AddCell(cell);

                    cell = new PdfPCell(t.DefaultCell);
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;

                    if (ShowCheckNo)
                        cell.Phrase = new Phrase(c.CheckNo, font);
                    else
                        cell.Phrase = new Phrase("", font);

                    t.AddCell(cell);

                    if (ShowNotes)
                        t.AddCell(new Phrase(c.Description.trim(), font));
                    else
                        t.AddCell(new Phrase("", font));

                    total += (c.ContributionAmount);
                }

                t.DefaultCell.Border = Rectangle.TOP_BORDER;

                cell = new PdfPCell(t.DefaultCell);
                cell.Colspan = 2;
                cell.Phrase = new Phrase("Total Contributions for period", boldfont);
                t.AddCell(cell);

                cell = new PdfPCell(t.DefaultCell);
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                cell.Phrase = new Phrase(total.ToString("N2"), font);
                t.AddCell(cell);

                cell = new PdfPCell(t.DefaultCell);
                cell.Colspan = 2;
                cell.Phrase = new Phrase("");
                t.AddCell(cell);

                ct.AddElement(t);

                //------Pledges

                if (pledges.Count > 0)
                {
                    t = new PdfPTable(new[] {25f, 15f, 15f, 15f, 30f});
                    t.WidthPercentage = 100;
                    t.DefaultCell.Border = Rectangle.NO_BORDER;
                    t.HeaderRows = 2;

                    cell = new PdfPCell(t.DefaultCell);
                    cell.Colspan = 5;
                    cell.Phrase = new Phrase("\n\nPledges\n", boldfont);
                    t.AddCell(cell);

                    t.DefaultCell.Border = Rectangle.BOTTOM_BORDER;
                    t.AddCell(new Phrase("Fund", boldfont));
                    cell = new PdfPCell(t.DefaultCell);
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    cell.Phrase = new Phrase("Pledge", boldfont);
                    t.AddCell(cell);
                    cell = new PdfPCell(t.DefaultCell);
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    cell.Phrase = new Phrase("Given", boldfont);
                    t.AddCell(cell);

                    t.DefaultCell.Border = Rectangle.NO_BORDER;
                    t.AddCell(new Phrase("", boldfont));
                    t.AddCell(new Phrase("", boldfont));

                    foreach (var c in pledges)
                    {
                        t.AddCell(new Phrase(c.Fund, font));

                        cell = new PdfPCell(t.DefaultCell);
                        cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        cell.Phrase = new Phrase(c.PledgeAmount.ToString2("N2"), font);
                        t.AddCell(cell);

                        cell = new PdfPCell(t.DefaultCell);
                        cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        cell.Phrase = new Phrase(c.ContributionAmount.ToString2("N2"), font);
                        t.AddCell(cell);

                        t.AddCell(new Phrase("", boldfont));
                        t.AddCell(new Phrase("", boldfont));
                    }
                    ct.AddElement(t);
                }

                //------Gifts In Kind

                if (giftsinkind.Count > 0)
                {
                    t = new PdfPTable(new[] {15f, 25f, 15f, 15f, 30f});
                    t.WidthPercentage = 100;
                    t.DefaultCell.Border = Rectangle.NO_BORDER;
                    t.HeaderRows = 2;

                    // Headers
                    cell = new PdfPCell(t.DefaultCell);
                    cell.Colspan = 5;
                    cell.Phrase = new Phrase("\n\nGifts in Kind\n", boldfont);
                    t.AddCell(cell);

                    t.DefaultCell.Border = Rectangle.BOTTOM_BORDER;
                    t.AddCell(new Phrase("Date", boldfont));
                    cell = new PdfPCell(t.DefaultCell);
                    cell.Phrase = new Phrase("Fund", boldfont);
                    t.AddCell(cell);
                    cell = new PdfPCell(t.DefaultCell);
                    cell.Phrase = new Phrase("Description", boldfont);
                    t.AddCell(cell);

                    t.AddCell(new Phrase("", boldfont));
                    t.AddCell(new Phrase("", boldfont));

                    t.DefaultCell.Border = Rectangle.NO_BORDER;

                    foreach (var c in giftsinkind)
                    {
                        t.AddCell(new Phrase(c.ContributionDate.ToShortDateString(), font));
                        cell = new PdfPCell(t.DefaultCell);

                        cell.Phrase = new Phrase(c.Fund, font);
                        t.AddCell(cell);

                        cell = new PdfPCell(t.DefaultCell);
                        cell.Colspan = 3;
                        cell.Phrase = new Phrase(c.Description, font);
                        t.AddCell(cell);
                    }
                    ct.AddElement(t);
                }

                //-----Summary

                t = new PdfPTable(new[] {40f, 15f, 45f});
                t.WidthPercentage = 100;
                t.DefaultCell.Border = Rectangle.NO_BORDER;
                t.HeaderRows = 2;

                cell = new PdfPCell(t.DefaultCell);
                cell.Colspan = 3;
                cell.Phrase = new Phrase("\n\nPeriod Summary\n", boldfont);
                t.AddCell(cell);

                t.DefaultCell.Border = Rectangle.BOTTOM_BORDER;
                t.AddCell(new Phrase("Fund", boldfont));

                cell = new PdfPCell(t.DefaultCell);
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                cell.Phrase = new Phrase("Amount", boldfont);
                t.AddCell(cell);

                t.DefaultCell.Border = Rectangle.NO_BORDER;
                t.AddCell(new Phrase("", boldfont));

                foreach (var c in APIContribution.quarterlySummary(Db, ci, FromDate, ToDate))
                {
                    t.AddCell(new Phrase(c.Fund, font));

                    cell = new PdfPCell(t.DefaultCell);
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    cell.Phrase = new Phrase(c.ContributionAmount.ToString("N2"), font);
                    t.AddCell(cell);

                    t.AddCell(new Phrase("", boldfont));
                }

                t.DefaultCell.Border = Rectangle.NO_BORDER;

                cell = new PdfPCell(t.DefaultCell);
                cell.Border = Rectangle.TOP_BORDER;
                cell.Colspan = 1;
                cell.Phrase = new Phrase("Total Contributions for period", boldfont);
                t.AddCell(cell);

                cell = new PdfPCell(t.DefaultCell);
                cell.Border = Rectangle.TOP_BORDER;
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                cell.Phrase = new Phrase(total.ToString("N2"), font);
                t.AddCell(cell);

                cell = new PdfPCell(t.DefaultCell);
                cell.Phrase = new Phrase("");
                t.AddCell(cell);

                ct.AddElement(t);

                //------NonTax

                if (nontaxitems.Count > 0)
                {
                    t = new PdfPTable(new[] {15f, 25f, 15f, 15f, 30f});
                    t.WidthPercentage = 100;
                    t.DefaultCell.Border = Rectangle.NO_BORDER;
                    t.HeaderRows = 2;

                    cell = new PdfPCell(t.DefaultCell);
                    cell.Colspan = 5;
                    cell.Phrase = new Phrase("\n\nNon Tax-Deductible Items\n", boldfont);
                    t.AddCell(cell);

                    t.DefaultCell.Border = Rectangle.BOTTOM_BORDER;
                    t.AddCell(new Phrase("Date", boldfont));
                    t.AddCell(new Phrase("Description", boldfont));
                    cell = new PdfPCell(t.DefaultCell);
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    cell.Phrase = new Phrase("Amount", boldfont);
                    t.AddCell(cell);
                    t.AddCell(new Phrase("", boldfont));
                    t.AddCell(new Phrase("", boldfont));

                    t.DefaultCell.Border = Rectangle.NO_BORDER;

                    var ntotal = 0m;
                    foreach (var c in nontaxitems)
                    {
                        t.AddCell(new Phrase(c.ContributionDate.ToShortDateString(), font));
                        t.AddCell(new Phrase(c.Fund, font));
                        cell = new PdfPCell(t.DefaultCell);
                        cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        cell.Phrase = new Phrase(c.ContributionAmount.ToString("N2"), font);
                        t.AddCell(cell);
                        t.AddCell(new Phrase("", boldfont));
                        if (ShowNotes)
                            t.AddCell(new Phrase(c.Description, font));
                        else
                            t.AddCell(new Phrase("", font));

                        ntotal += (c.ContributionAmount);
                    }
                    t.DefaultCell.Border = Rectangle.TOP_BORDER;
                    cell = new PdfPCell(t.DefaultCell);
                    cell.Colspan = 2;
                    cell.Phrase = new Phrase("Total Non Tax-Deductible Items for period", boldfont);
                    t.AddCell(cell);
                    cell = new PdfPCell(t.DefaultCell);
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    cell.Phrase = new Phrase(ntotal.ToString("N2"), font);
                    t.AddCell(cell);
                    t.AddCell(new Phrase("", boldfont));
                    t.AddCell(new Phrase("", boldfont));

                    ct.AddElement(t);
                }

                var status = 0;
                while (ColumnText.HasMoreText(status))
                {
                    ct.SetSimpleColumn(doc.Left, doc.Bottom, doc.Left + colwidth, pos);

                    status = ct.Go();
                    pos = doc.Top;
                    doc.NewPage();
                }

                runningtotals.Processed += 1;
                runningtotals.CurrSet = set;
                Db.SubmitChanges();
            }

            if (count == 0)
            {
                doc.NewPage();
                doc.Add(new Phrase("no data"));
            }
            doc.Close();

            if (set == LastSet())
                runningtotals.Completed = DateTime.Now;
            Db.SubmitChanges();
        }
Пример #33
0
        public void CreateTaggedPdf8() {
            InitializeDocument("8");

            ColumnText columnText = new ColumnText(writer.DirectContent);

            List list = new List(true);
            try {
                list = new List(true);
                ListItem listItem =
                    new ListItem(
                        new Chunk(
                            "Quick brown fox jumped over a lazy dog. A very long line appears here because we need new line."));
                list.Add(listItem);
                Image i = Image.GetInstance(RESOURCES + "img\\fox.bmp");
                Chunk c = new Chunk(i, 0, 0);
                c.SetAccessibleAttribute(PdfName.ALT, new PdfString("Fox image"));
                listItem = new ListItem(c);
                list.Add(listItem);
                listItem = new ListItem(new Chunk("jumped over a lazy"));
                list.Add(listItem);
                i = Image.GetInstance(RESOURCES + "img\\dog.bmp");
                c = new Chunk(i, 0, 0);
                c.SetAccessibleAttribute(PdfName.ALT, new PdfString("Dog image"));
                listItem = new ListItem(c);
                list.Add(listItem);
                listItem = new ListItem(new Paragraph(text));
                list.Add(listItem);
            }
            catch (Exception) {
            }
            columnText.SetSimpleColumn(36, 36, 400, 800);
            columnText.AddElement(h1);
            columnText.AddElement(list);
            columnText.Go();
            document.NewPage();
            columnText.SetSimpleColumn(36, 36, 400, 800);
            columnText.Go();
            document.Close();

            int[] nums = new int[] {64, 35};
            CheckNums(nums);
            CompareResults("8");
        }
Пример #34
0
        private int floatingLayout(ColumnText compositeColumn, List<IElement> floatingElements, bool simulate) {
            int status = ColumnText.NO_MORE_TEXT;
            float minYLine = yLine;
            float leftWidth = 0;
            float rightWidth = 0;

            while (floatingElements.Count > 0) {
                if (floatingElements[0] is PdfDiv) {
                    PdfDiv floatingElement = (PdfDiv)floatingElements[0];
                    floatingElements.RemoveAt(0);
                    status = floatingElement.layout(compositeColumn, true, floatLeftX, minY, floatRightX, yLine);
                    if ((status & ColumnText.NO_MORE_TEXT) == 0) {
                        yLine = minYLine;
                        floatLeftX = leftX;
                        floatRightX = rightX;
                        status = floatingElement.layout(compositeColumn, true, floatLeftX, minY, floatRightX, yLine);
                        if ((status & ColumnText.NO_MORE_TEXT) == 0) {
                            floatingElements.Insert(0, floatingElement);
                            break;
                        }
                    }
                    if (floatingElement.Float == PdfDiv.FloatType.LEFT) {
                        status = floatingElement.layout(compositeColumn, simulate, floatLeftX, minY, floatRightX, yLine);
                        floatLeftX += floatingElement.getActualWidth();
                        leftWidth += floatingElement.getActualWidth();
                    } else if (floatingElement.Float == PdfDiv.FloatType.RIGHT) {
                        status = floatingElement.layout(compositeColumn, simulate, floatRightX - floatingElement.getActualWidth() - 0.01f, minY, floatRightX, yLine);
                        floatRightX -= floatingElement.getActualWidth();
                        rightWidth += floatingElement.getActualWidth();
                    }
                    minYLine = Math.Min(minYLine, yLine - floatingElement.getActualHeight());
                } else {
                    IElement firstElement = floatingElements[0];
                    if (firstElement is ISpaceable) {
                        yLine -= ((ISpaceable)firstElement).SpacingBefore;
                    }
                    compositeColumn.AddElement(firstElement);
                    floatingElements.RemoveAt(0);
                    if (yLine > minYLine)
                        compositeColumn.SetSimpleColumn(floatLeftX, yLine, floatRightX, minYLine);
                    else
                        compositeColumn.SetSimpleColumn(floatLeftX, yLine, floatRightX, minY);

                    compositeColumn.FilledWidth = 0;

                    status = compositeColumn.Go(simulate);
                    if (yLine > minYLine && (floatLeftX > leftX || floatRightX < rightX) && (status & ColumnText.NO_MORE_TEXT) == 0) {
                        yLine = minYLine;
                        floatLeftX = leftX;
                        floatRightX = rightX;
                        if (leftWidth != 0 && rightWidth != 0) {
                            filledWidth = rightX - leftX;
                        } else {
                            if (leftWidth > filledWidth) {
                                filledWidth = leftWidth;
                            }
                            if (rightWidth > filledWidth) {
                                filledWidth = rightWidth;
                            }
                        }

                        leftWidth = 0;
                        rightWidth = 0;
                        compositeColumn.SetSimpleColumn(floatLeftX, yLine, floatRightX, minY);
                        status = compositeColumn.Go(simulate);
                        minYLine = compositeColumn.YLine + compositeColumn.Descender;
                        yLine = minYLine;
                        if (compositeColumn.FilledWidth > filledWidth) {
                            filledWidth = compositeColumn.FilledWidth;
                        }
                    } else {
                        if (rightWidth > 0) {
                            rightWidth += compositeColumn.FilledWidth;
                        } else if (leftWidth > 0) {
                            leftWidth += compositeColumn.FilledWidth;
                        } else if (compositeColumn.FilledWidth > filledWidth) {
                            filledWidth = compositeColumn.FilledWidth;
                        }
                        minYLine = Math.Min(compositeColumn.YLine + compositeColumn.Descender, minYLine);
                        yLine = compositeColumn.YLine + compositeColumn.Descender;
                    }

                    if ((status & ColumnText.NO_MORE_TEXT) == 0) {
                        foreach (IElement element in compositeColumn.CompositeElements) {
                            floatingElements.Insert(0, element);
                        }
                        compositeColumn.CompositeElements.Clear();
                        break;
                    } else {
                        compositeColumn.CompositeElements.Clear();
                    }
                }
            }


            if (leftWidth != 0 && rightWidth != 0) {
                filledWidth = rightX - leftX;
            } else {
                if (leftWidth > filledWidth) {
                    filledWidth = leftWidth;
                }
                if (rightWidth > filledWidth) {
                    filledWidth = rightWidth;
                }
            }

            yLine = minYLine;
            floatLeftX = leftX;
            floatRightX = rightX;

            return status;
        }
Пример #35
0
        public void CreateTaggedPdf0() {
            InitializeDocument("0");
            Paragraph paragraph = new Paragraph();
            Chunk c = new Chunk(" Hello ");
            paragraph.Add(c);
            c = new Chunk("  world\n\n");
            paragraph.Add(c);
            ColumnText columnText = new ColumnText(writer.DirectContent);
            columnText.SetSimpleColumn(36, 36, 250, 800);
            columnText.AddElement(paragraph);
            columnText.Go();
            document.Close();

            InitializeDocument("0");
            paragraph = new Paragraph();
            c = new Chunk("  ");
            paragraph.Add(c);
            columnText = new ColumnText(writer.DirectContent);
            columnText.SetSimpleColumn(36, 36, 250, 800);
            columnText.AddElement(paragraph);
            columnText.Go();
            document.Close();

            InitializeDocument("0");
            paragraph = new Paragraph();
            c = new Chunk("Hello World");
            paragraph.Add(c);
            columnText = new ColumnText(writer.DirectContent);
            columnText.SetSimpleColumn(36, 36, 250, 800);
            columnText.AddElement(paragraph);
            columnText.Go();
            document.Close();

            InitializeDocument("0");
            paragraph = new Paragraph();
            c = new Chunk("Hello World");
            paragraph.Add(c);
            document.Add(paragraph);
            document.Close();

            InitializeDocument("0");
            paragraph = new Paragraph();
            c = new Chunk(" Hello ");
            paragraph.Add(c);
            c = new Chunk("  world\n");
            paragraph.Add(c);
            paragraph.Font = new Font(Font.FontFamily.HELVETICA, 8, Font.NORMAL, BaseColor.RED);
            document.Add(paragraph);
            document.Close();
        }
Пример #36
0
        /// <summary>
        /// Add text at the X Y position; multiple lines handled
        /// </summary>
        private void addText(float x, float y, float width, float height, string[] textLines,
            StyleInfo styleInfo, float[] textWidths, bool wrap, string url, bool noClip, string tooltip)
        {
            RenderFont renderFont = RenderUtility.GetRenderFont(styleInfo);
            BaseFont baseFont = null;

            //convert the render font type to iTextSharp type
            int fontType = 0;
            switch (renderFont.Style)
            {
                case RenderFont.FontStyle.Bold:
                    fontType = iTextSharp.text.Font.BOLD;
                    break;
                case RenderFont.FontStyle.Italic:
                    fontType = iTextSharp.text.Font.ITALIC;
                    break;
                case RenderFont.FontStyle.BoldItalic:
                    fontType = iTextSharp.text.Font.BOLDITALIC;
                    break;
                default:
                    fontType = iTextSharp.text.Font.NORMAL;
                    break;
            }

            //get the index of the font name in the list font name
            int indexBaseFont = BaseFontNames.FindIndex(delegate(string _fontname) { return _fontname == renderFont.FaceName + "_" + fontType; });

            //if not found then add the new BaseFont
            if (indexBaseFont == -1)
            {
                //create a new font or a with a new type
                baseFont = FontFactory.GetFont(renderFont.FaceName, BaseFont.IDENTITY_H, 0, fontType).BaseFont;

                //add the font face name and font to the lists
                BaseFontNames.Add(renderFont.FaceName + "_" + fontType);
                BaseFonts.Add(baseFont);
            }
            else
                baseFont = BaseFonts[indexBaseFont];

            //text alignment
            int align = 0;

            //first position x and y and the leading (usefull for all kind of justified text)
            float firstStartX = -1;
            float firstStartY = -1;
            float leading = -1;

            //chunks of text
            List<Chunk> chunks = new List<Chunk>();

            //loop thru the lines of text
            for (int i = 0; i < textLines.Length; i++)
            {
                string text = textLines[i];
                float textwidth = textWidths[i];

                float startX = x + styleInfo.PaddingLeft;						    // TODO: handle tb_rl
                float startY = y + styleInfo.PaddingTop + (i * styleInfo.FontSize);	// TODO: handle tb_rl

                if (styleInfo.WritingMode == WritingModeEnum.lr_tb)
                {
                    //calculate the x position
                    switch (styleInfo.TextAlign)
                    {
                        case TextAlignEnum.Center:
                            if (width > 0)
                            {
                                startX = x + styleInfo.PaddingLeft + (width - styleInfo.PaddingLeft - styleInfo.PaddingRight) / 2 - textwidth / 2;
                                align = Element.ALIGN_CENTER;
                            }
                            break;

                        case TextAlignEnum.Right:
                            if (width > 0)
                            {
                                startX = x + width - textwidth - styleInfo.PaddingRight - 2;
                                align = Element.ALIGN_RIGHT;
                            }
                            break;

                        case TextAlignEnum.Justified:
                        case TextAlignEnum.JustifiedLine:
                        case TextAlignEnum.JustifiedDottedLine:
                            if (width > 0)
                            {
                                startX += 2;
                                align = Element.ALIGN_JUSTIFIED;
                            }
                            break;

                        case TextAlignEnum.Left:
                        default:
                            if (width > 0)
                                startX += 2;
                            align = Element.ALIGN_LEFT;
                            break;
                    }

                    //calculate the y position
                    switch (styleInfo.VerticalAlign)
                    {
                        case VerticalAlignEnum.Middle:
                            if (height <= 0)
                                break;

                            //calculate the middle of the region
                            startY = y + styleInfo.PaddingTop + (height - styleInfo.PaddingTop - styleInfo.PaddingBottom) / 2 - styleInfo.FontSize / 2;

                            //now go up or down depending on which line
                            if (textLines.Length == 1)
                                break;

                            //even number
                            if (textLines.Length % 2 == 0)
                                startY = startY - ((textLines.Length / 2 - i) * styleInfo.FontSize) + styleInfo.FontSize / 2;
                            else
                                startY = startY - ((textLines.Length / 2 - i) * styleInfo.FontSize);
                            break;

                        case VerticalAlignEnum.Bottom:
                            if (height <= 0)
                                break;

                            startY = y + height - styleInfo.PaddingBottom - (styleInfo.FontSize * (textLines.Length - i));
                            break;

                        case VerticalAlignEnum.Top:
                        default:
                            break;
                    }
                }
                else
                {
                    //move x in a little - it draws to close to the edge of the rectangle (25% of the font size seems to work!) and Center or right align vertical text
                    startX += styleInfo.FontSize / 4;

                    switch (styleInfo.TextAlign)
                    {
                        case TextAlignEnum.Center:
                            if (height > 0)
                                startY = y + styleInfo.PaddingLeft + (height - styleInfo.PaddingLeft - styleInfo.PaddingRight) / 2 - textwidth / 2;
                            break;

                        case TextAlignEnum.Right:
                            if (width > 0)
                                startY = y + height - textwidth - styleInfo.PaddingRight;
                            break;

                        case TextAlignEnum.Left:
                        default:
                            break;
                    }
                }

                //mark the first x position for justify text
                if (firstStartX == -1)
                    firstStartX = startX;

                //mark the first y position for justify text
                if (firstStartY == -1)
                    firstStartY = startY;

                //mark the first leading height for justify text
                else if (leading == -1)
                    leading = startY - firstStartY;

                //draw background rectangle if needed (only put out on the first line, since we do whole rectangle)
                if (!styleInfo.BackgroundColor.IsEmpty && height > 0 && width > 0 && i == 0)
                    addFillRectangle(x, y, width, height, styleInfo.BackgroundColor);

                //set the clipping path, (Itext have no clip)
                if (height > 0 && width > 0)
                {
                    pdfContent.SetRGBColorFill(styleInfo.Color.R, styleInfo.Color.G, styleInfo.Color.B);

                    if (align == Element.ALIGN_JUSTIFIED)
                        chunks.Add(new Chunk(text));
                    else
                    {
                        if (styleInfo.WritingMode == WritingModeEnum.lr_tb)
                        {
                            //if textline after measure with word break can fit just simple show Text
                            if (width >= textwidth)
                            {
                                pdfContent.SaveState();
                                pdfContent.BeginText();
                                pdfContent.SetFontAndSize(baseFont, styleInfo.FontSize);
                                //same fonts dont have nativelly bold so we could simulate that
                                if (renderFont.SimulateBold)
                                {
                                    pdfContent.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
                                    pdfContent.SetLineWidth(0.2f);
                                }
                                pdfContent.SetTextMatrix(startX, pageHeight - startY - styleInfo.FontSize);
                                pdfContent.ShowText(text);
                                pdfContent.EndText();
                                pdfContent.RestoreState();
                            }
                            else
                            {
                                //else use Column text to wrap or clip (wrap: for example a text like an URL so word break is not working here
                                //itextsharp ColumnText do the work for us)
                                ColumnText columnText = new ColumnText(pdfContent);
                                columnText.SetSimpleColumn(new Phrase(text, new iTextSharp.text.Font(baseFont, styleInfo.FontSize)),
                                    x + styleInfo.PaddingLeft, pageHeight - startY, x + width - styleInfo.PaddingRight,
                                    pageHeight - y - styleInfo.PaddingBottom - height, 10f, align);
                                columnText.Go();
                            }
                        }
                        else
                        {
                            //not checked
                            double rads = -283.0 / 180.0;
                            double radsCos = Math.Cos(rads);
                            double radsSin = Math.Sin(rads);
                            pdfContent.BeginText();
                            pdfContent.SetFontAndSize(baseFont, styleInfo.FontSize);
                            pdfContent.SetTextMatrix((float)radsCos, (float)radsSin, (float)-radsSin, (float)radsCos, startX, pageHeight - startY);
                            pdfContent.ShowText(text);
                            pdfContent.EndText();
                        }
                    }

                    //add URL
                    if (url != null)
                        document.Add(new Annotation(x, pageHeight - y, height, width, url));

                    //add tooltip
                    if (tooltip != null)
                        document.Add(new Annotation(x, pageHeight - y, height, width, tooltip));
                }

                //handle underlining etc ...
                float maxX;
                switch (styleInfo.TextDecoration)
                {
                    case TextDecorationEnum.Underline:
                        maxX = width > 0 ? Math.Min(x + width, startX + textwidth) : startX + textwidth;
                        addLine(startX, startY + styleInfo.FontSize + 1, maxX, startY + styleInfo.FontSize + 1, 1, styleInfo.Color, BorderStyleEnum.Solid);
                        break;

                    case TextDecorationEnum.LineThrough:
                        maxX = width > 0 ? Math.Min(x + width, startX + textwidth) : startX + textwidth;
                        addLine(startX, startY + (styleInfo.FontSize / 2) + 1, maxX, startY + (styleInfo.FontSize / 2) + 1, 1, styleInfo.Color, BorderStyleEnum.Solid);
                        break;

                    case TextDecorationEnum.Overline:
                        maxX = width > 0 ? Math.Min(x + width, startX + textwidth) : startX + textwidth;
                        addLine(startX, startY + 1, maxX, startY + 1, 1, styleInfo.Color, BorderStyleEnum.Solid);
                        break;

                    case TextDecorationEnum.None:
                    default:
                        break;
                }
            }

            //add text to justify
            if (chunks.Count > 0)
            {
                Paragraph paragraph = new Paragraph();
                paragraph.Alignment = align;
                paragraph.Leading = leading;
                paragraph.Font = new iTextSharp.text.Font(baseFont, styleInfo.FontSize);

                //join all text (is necessary to justify alignment)
                foreach (Chunk chunk in chunks)
                    paragraph.Add(chunk);

                //add separator for kind of justified alignments
                if (styleInfo.TextAlign == TextAlignEnum.JustifiedLine)
                {
                    iTextSharp.text.pdf.draw.LineSeparator lineSeparator = new iTextSharp.text.pdf.draw.LineSeparator();
                    lineSeparator.Offset = 3f;
                    lineSeparator.LineColor = new BaseColor(styleInfo.Color);
                    paragraph.Add(new Chunk(lineSeparator));
                }
                else if (styleInfo.TextAlign == TextAlignEnum.JustifiedDottedLine)
                {
                    iTextSharp.text.pdf.draw.DottedLineSeparator dottedLineSeparator = new iTextSharp.text.pdf.draw.DottedLineSeparator();
                    dottedLineSeparator.Offset = 3f;
                    dottedLineSeparator.LineColor = new BaseColor(styleInfo.Color);
                    paragraph.Add(new Chunk(dottedLineSeparator));
                }

                ColumnText columnText = new ColumnText(pdfContent);
                //start from the top of the column
                columnText.UseAscender = true;
                //width, y position from the bottom page (compensate 2 units), x position, 0
                columnText.SetSimpleColumn(firstStartX, pageHeight - firstStartY - 2, firstStartX + width - styleInfo.PaddingRight, 0);
                columnText.AddElement(paragraph);
                columnText.Go();
            }

            //add any required border
            addBorder(styleInfo, x, y, width, height);
        }
    //	[M4] Adding a PdfPTable

        /** Adds a <CODE>PdfPTable</CODE> to the document.
        * @param ptable the <CODE>PdfPTable</CODE> to be added to the document.
        * @throws DocumentException on error
        */
        internal void AddPTable(PdfPTable ptable) {
            ColumnText ct = new ColumnText(writer.DirectContent);
            // if the table prefers to be on a single page, and it wouldn't
            //fit on the current page, start a new page.
            if (ptable.KeepTogether && !FitsPage(ptable, 0f) && currentHeight > 0)  {
                NewPage();
            }
            if (currentHeight == 0) {
                ct.AdjustFirstLine = false;
            }
            ct.AddElement(ptable);
            bool he = ptable.HeadersInEvent;
            ptable.HeadersInEvent = true;
            int loop = 0;
            while (true) {
                ct.SetSimpleColumn(IndentLeft, IndentBottom, IndentRight, IndentTop - currentHeight);
                int status = ct.Go();
                if ((status & ColumnText.NO_MORE_TEXT) != 0) {
                    if (IsTagged(writer))
                        text.SetTextMatrix(IndentLeft, ct.YLine);
                    else
                        text.MoveText(0, ct.YLine - IndentTop + currentHeight);

                    currentHeight = IndentTop - ct.YLine;
                    break;
                }
                if (IndentTop - currentHeight == ct.YLine)
                    ++loop;
                else
                    loop = 0;
                if (loop == 3) {
                    throw new DocumentException(MessageLocalization.GetComposedMessage("infinite.table.loop"));
                }
                NewPage();
                if (IsTagged(writer))
                    ct.Canvas = text;
            }
            ptable.HeadersInEvent = he;
        }
Пример #38
0
        private int FloatingLayout(List <IElement> floatingElements, bool simulate)
        {
            int   status     = ColumnText.NO_MORE_TEXT;
            float minYLine   = yLine;
            float leftWidth  = 0;
            float rightWidth = 0;

            ColumnText currentCompositeColumn = compositeColumn;

            if (simulate)
            {
                currentCompositeColumn = ColumnText.Duplicate(compositeColumn);
            }

            bool ignoreSpacingBefore = maxY == yLine;

            while (floatingElements.Count > 0)
            {
                IElement nextElement = floatingElements[0];
                floatingElements.RemoveAt(0);
                if (nextElement is PdfDiv)
                {
                    PdfDiv floatingElement = (PdfDiv)nextElement;
                    status = floatingElement.Layout(compositeColumn.Canvas, useAscender, true, floatLeftX, minY, floatRightX, yLine);
                    if ((status & ColumnText.NO_MORE_TEXT) == 0)
                    {
                        yLine       = minYLine;
                        floatLeftX  = leftX;
                        floatRightX = rightX;
                        status      = floatingElement.Layout(compositeColumn.Canvas, useAscender, true, floatLeftX, minY, floatRightX, yLine);
                        if ((status & ColumnText.NO_MORE_TEXT) == 0)
                        {
                            floatingElements.Insert(0, floatingElement);
                            break;
                        }
                    }
                    if (floatingElement.Float == PdfDiv.FloatType.LEFT)
                    {
                        status      = floatingElement.Layout(compositeColumn.Canvas, useAscender, simulate, floatLeftX, minY, floatRightX, yLine);
                        floatLeftX += floatingElement.getActualWidth();
                        leftWidth  += floatingElement.getActualWidth();
                    }
                    else if (floatingElement.Float == PdfDiv.FloatType.RIGHT)
                    {
                        status       = floatingElement.Layout(compositeColumn.Canvas, useAscender, simulate, floatRightX - floatingElement.getActualWidth() - 0.01f, minY, floatRightX, yLine);
                        floatRightX -= floatingElement.getActualWidth();
                        rightWidth  += floatingElement.getActualWidth();
                    }
                    minYLine = Math.Min(minYLine, yLine - floatingElement.getActualHeight());
                }
                else
                {
                    if (minY > minYLine)
                    {
                        status = ColumnText.NO_MORE_COLUMN;
                        floatingElements.Insert(0, nextElement);
                        if (currentCompositeColumn != null)
                        {
                            currentCompositeColumn.SetText(null);
                        }
                        break;
                    }
                    else
                    {
                        if (nextElement is ISpaceable && (!ignoreSpacingBefore || !currentCompositeColumn.IgnoreSpacingBefore || ((ISpaceable)nextElement).PaddingTop != 0))
                        {
                            yLine -= ((ISpaceable)nextElement).SpacingBefore;
                        }
                        if (simulate)
                        {
                            if (nextElement is PdfPTable)
                            {
                                currentCompositeColumn.AddElement(new PdfPTable((PdfPTable)nextElement));
                            }
                            else
                            {
                                currentCompositeColumn.AddElement(nextElement);
                            }
                        }
                        else
                        {
                            currentCompositeColumn.AddElement(nextElement);
                        }

                        if (yLine > minYLine)
                        {
                            currentCompositeColumn.SetSimpleColumn(floatLeftX, yLine, floatRightX, minYLine);
                        }
                        else
                        {
                            currentCompositeColumn.SetSimpleColumn(floatLeftX, yLine, floatRightX, minY);
                        }

                        currentCompositeColumn.FilledWidth = 0;

                        status = currentCompositeColumn.Go(simulate);
                        if (yLine > minYLine && (floatLeftX > leftX || floatRightX < rightX) &&
                            (status & ColumnText.NO_MORE_TEXT) == 0)
                        {
                            yLine       = minYLine;
                            floatLeftX  = leftX;
                            floatRightX = rightX;
                            if (leftWidth != 0 && rightWidth != 0)
                            {
                                filledWidth = rightX - leftX;
                            }
                            else
                            {
                                if (leftWidth > filledWidth)
                                {
                                    filledWidth = leftWidth;
                                }
                                if (rightWidth > filledWidth)
                                {
                                    filledWidth = rightWidth;
                                }
                            }

                            leftWidth  = 0;
                            rightWidth = 0;
                            if (simulate && nextElement is PdfPTable)
                            {
                                currentCompositeColumn.AddElement(new PdfPTable((PdfPTable)nextElement));
                            }

                            currentCompositeColumn.SetSimpleColumn(floatLeftX, yLine, floatRightX, minY);
                            status   = currentCompositeColumn.Go(simulate);
                            minYLine = currentCompositeColumn.YLine + currentCompositeColumn.Descender;
                            yLine    = minYLine;
                            if (currentCompositeColumn.FilledWidth > filledWidth)
                            {
                                filledWidth = currentCompositeColumn.FilledWidth;
                            }
                        }
                        else
                        {
                            if (rightWidth > 0)
                            {
                                rightWidth += currentCompositeColumn.FilledWidth;
                            }
                            else if (leftWidth > 0)
                            {
                                leftWidth += currentCompositeColumn.FilledWidth;
                            }
                            else if (currentCompositeColumn.FilledWidth > filledWidth)
                            {
                                filledWidth = currentCompositeColumn.FilledWidth;
                            }
                            minYLine = Math.Min(currentCompositeColumn.YLine + currentCompositeColumn.Descender, minYLine);
                            yLine    = currentCompositeColumn.YLine + currentCompositeColumn.Descender;
                        }

                        if ((status & ColumnText.NO_MORE_TEXT) == 0)
                        {
                            if (!simulate)
                            {
                                floatingElements.InsertRange(0, currentCompositeColumn.CompositeElements);
                                currentCompositeColumn.CompositeElements.Clear();
                            }
                            else
                            {
                                floatingElements.Insert(0, nextElement);
                                currentCompositeColumn.SetText(null);
                            }
                            break;
                        }
                        else
                        {
                            currentCompositeColumn.SetText(null);
                        }
                    }
                }
                if (ignoreSpacingBefore && nextElement.Chunks.Count == 0)
                {
                    if (nextElement is Paragraph)
                    {
                        Paragraph p = (Paragraph)nextElement;
                        IElement  e = p[0];
                        if (e is WritableDirectElement)
                        {
                            WritableDirectElement writableDirectElement = (WritableDirectElement)e;
                            if (writableDirectElement.DirectElemenType != WritableDirectElement.DIRECT_ELEMENT_TYPE_HEADER)
                            {
                                ignoreSpacingBefore = false;
                            }
                        }
                    }
                    else if (nextElement is ISpaceable)
                    {
                        ignoreSpacingBefore = false;
                    }
                }
                else
                {
                    ignoreSpacingBefore = false;
                }
            }

            if (leftWidth != 0 && rightWidth != 0)
            {
                filledWidth = rightX - leftX;
            }
            else
            {
                if (leftWidth > filledWidth)
                {
                    filledWidth = leftWidth;
                }
                if (rightWidth > filledWidth)
                {
                    filledWidth = rightWidth;
                }
            }

            yLine       = minYLine;
            floatLeftX  = leftX;
            floatRightX = rightX;

            return(status);
        }