Go() public method

public Go ( ) : int
return int
Ejemplo n.º 1
2
 /** Shows a line of text. Only the first line is written.
  * @param canvas where the text is to be written to
  * @param alignment the alignment. It is not influenced by the run direction
  * @param phrase the <CODE>Phrase</CODE> with the text
  * @param x the x reference position
  * @param y the y reference position
  * @param rotation the rotation to be applied in degrees counterclockwise
  * @param runDirection the run direction
  * @param arabicOptions the options for the arabic shaping
  */    
 public static void ShowTextAligned(PdfContentByte canvas, int alignment, Phrase phrase, float x, float y, float rotation, int runDirection, int arabicOptions) {
     if (alignment != Element.ALIGN_LEFT && alignment != Element.ALIGN_CENTER
         && alignment != Element.ALIGN_RIGHT)
         alignment = Element.ALIGN_LEFT;
     canvas.SaveState();
     ColumnText ct = new ColumnText(canvas);
     float lly = -1;
     float ury = 2;
     float llx;
     float urx;
     switch (alignment) {
         case Element.ALIGN_LEFT:
             llx = 0;
             urx = 20000;
             break;
         case Element.ALIGN_RIGHT:
             llx = -20000;
             urx = 0;
             break;
         default:
             llx = -20000;
             urx = 20000;
             break;
     }
     if (rotation == 0) {
         llx += x;
         lly += y;
         urx += x;
         ury += y;
     }
     else {
         double alpha = rotation * Math.PI / 180.0;
         float cos = (float)Math.Cos(alpha);
         float sin = (float)Math.Sin(alpha);
         canvas.ConcatCTM(cos, sin, -sin, cos, x, y);
     }
     ct.SetSimpleColumn(phrase, llx, lly, urx, ury, 2, alignment);
     if (runDirection == PdfWriter.RUN_DIRECTION_RTL) {
         if (alignment == Element.ALIGN_LEFT)
             alignment = Element.ALIGN_RIGHT;
         else if (alignment == Element.ALIGN_RIGHT)
             alignment = Element.ALIGN_LEFT;
     }
     ct.Alignment = alignment;
     ct.ArabicOptions = arabicOptions;
     ct.RunDirection = runDirection;
     ct.Go();
     canvas.RestoreState();
 }
Ejemplo n.º 2
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 ct = new ColumnText(writer.DirectContent);
         int column = 0;
         ct.SetSimpleColumn(
           COLUMNS[column, 0], COLUMNS[column, 1],
           COLUMNS[column, 2], COLUMNS[column, 3]
         );
         // iText-ONLY, 'Initial value of the status' => 0
         // iTextSharp **DOES NOT** include this member variable
         // int status = ColumnText.START_COLUMN;
         int status = 0;
         float y;
         Image img;
         IEnumerable<Movie> movies = PojoFactory.GetMovies();
         foreach (Movie movie in movies)
         {
             y = ct.YLine;
             img = Image.GetInstance(
               Path.Combine(RESOURCE, movie.Imdb + ".jpg")
             );
             img.ScaleToFit(80, 1000);
             AddContent(ct, movie, img);
             status = ct.Go(true);
             if (ColumnText.HasMoreText(status))
             {
                 column = (column + 1) % 4;
                 if (column == 0)
                 {
                     document.NewPage();
                 }
                 ct.SetSimpleColumn(
                   COLUMNS[column, 0], COLUMNS[column, 1],
                   COLUMNS[column, 2], COLUMNS[column, 3]
                 );
                 y = COLUMNS[column, 3];
             }
             ct.YLine = y;
             ct.SetText(null);
             AddContent(ct, movie, img);
             status = ct.Go();
         }
     }
 }
Ejemplo n.º 3
0
 // ===========================================================================
 public override 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
         PdfContentByte canvas = writer.DirectContent;
         DrawRectangles(canvas);
         ColumnText ct = new ColumnText(canvas);
         ct.Alignment = Element.ALIGN_JUSTIFIED;
         ct.Leading = 14;
         int column = 0;
         ct.SetColumns(
           new float[] { 36, 806, 36, 670, 108, 670, 108, 596, 36, 596, 36, 36 },
           new float[] { 296, 806, 296, 484, 259, 484, 259, 410, 296, 410, 296, 36 }
         );
         ct.SetColumns(LEFT[column], RIGHT[column]);
         // ct.SetColumns(LEFT[column], RIGHT[column]);
         // iText-ONLY, 'Initial value of the status' => 0
         // iTextSharp **DOES NOT** include this member variable
         // int status = ColumnText.START_COLUMN;
         int status = 0;
         Phrase p;
         float y;
         IEnumerable<Movie> movies = PojoFactory.GetMovies();
         foreach (Movie movie in movies)
         {
             y = ct.YLine;
             p = CreateMovieInformation(movie);
             ct.AddText(p);
             status = ct.Go(true);
             if (ColumnText.HasMoreText(status))
             {
                 column = Math.Abs(column - 1);
                 if (column == 0)
                 {
                     document.NewPage();
                     DrawRectangles(canvas);
                 }
                 ct.SetColumns(LEFT[column], RIGHT[column]);
                 y = 806;
             }
             ct.YLine = y;
             ct.SetText(p);
             status = ct.Go();
         }
     }
 }
Ejemplo n.º 4
0
 // ===========================================================================
 public override 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
         ColumnText ct = new ColumnText(writer.DirectContent)
         {
             Alignment = Element.ALIGN_JUSTIFIED,
             ExtraParagraphSpace = 6,
             Leading = 14,
             Indent = 10,
             RightIndent = 3,
             SpaceCharRatio = PdfWriter.NO_SPACE_CHAR_RATIO
         };
         int column = 0;
         // iText-ONLY, 'Initial value of the status' => 0
         // iTextSharp **DOES NOT** include this member variable
         // int status = ColumnText.START_COLUMN;
         int status = 0;
         ct.SetSimpleColumn(
           COLUMNS[column][0], COLUMNS[column][1],
           COLUMNS[column][2], COLUMNS[column][3]
         );
         IEnumerable<Movie> movies = PojoFactory.GetMovies();
         foreach (Movie movie in movies)
         {
             ct.AddText(CreateMovieInformation(movie));
             status = ct.Go();
             if (ColumnText.HasMoreText(status))
             {
                 column = Math.Abs(column - 1);
                 if (column == 0)
                 {
                     document.NewPage();
                 }
                 ct.SetSimpleColumn(
                   COLUMNS[column][0], COLUMNS[column][1],
                   COLUMNS[column][2], COLUMNS[column][3]
                 );
                 ct.YLine = COLUMNS[column][3];
                 status = ct.Go();
             }
         }
     }
 }
Ejemplo n.º 5
0
 // ===========================================================================
 public override 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
         ColumnText ct = new ColumnText(writer.DirectContent);
         int column = 0;
         ct.SetSimpleColumn(
           COLUMNS[column][0], COLUMNS[column][1],
           COLUMNS[column][2], COLUMNS[column][3]
         );
         // iText-ONLY, 'Initial value of the status' => 0
         // iTextSharp **DOES NOT** include this member variable
         // int status = ColumnText.START_COLUMN;
         int status = 0;
         Phrase p;
         float y;
         IEnumerable<Movie> movies = PojoFactory.GetMovies();
         foreach (Movie movie in movies)
         {
             y = ct.YLine;
             p = CreateMovieInformation(movie);
             ct.AddText(p);
             status = ct.Go(true);
             if (ColumnText.HasMoreText(status))
             {
                 column = Math.Abs(column - 1);
                 if (column == 0)
                 {
                     document.NewPage();
                 }
                 ct.SetSimpleColumn(
                   COLUMNS[column][0], COLUMNS[column][1],
                   COLUMNS[column][2], COLUMNS[column][3]
                 );
                 y = COLUMNS[column][3];
             }
             ct.YLine = y;
             ct.SetText(p);
             status = ct.Go(false);
         }
     }
 }
Ejemplo n.º 6
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();
            }
        }
Ejemplo n.º 7
0
 public Unit CalculateTextHeight(string text, Unit width)
 {
     var ct = new ColumnText(null) { Leading = (float) leading };
     ct.AddText(new Phrase(text, Font));
     ct.SetSimpleColumn(0, 0, (float) width.Points, float.MaxValue);
     ct.Go(true);
     var test = ct.LinesWritten*ct.Leading.points();
     return test;
 }
Ejemplo n.º 8
0
        // ===========================================================================
        public virtual 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
                IEnumerable<Movie> movies = PojoFactory.GetMovies();
                ColumnText ct = new ColumnText(writer.DirectContent);
                foreach (Movie movie in movies)
                {
                    ct.AddText(CreateMovieInformation(movie));
                    ct.AddText(Chunk.NEWLINE);
                }
                ct.Alignment = Element.ALIGN_JUSTIFIED;
                ct.ExtraParagraphSpace = 6;
                ct.SetLeading(0, 1.2f);
                ct.FollowingIndent = 27;
                int linesWritten = 0;
                int column = 0;
                // iText-ONLY, 'Initial value of the status' => 0
                // iTextSharp **DOES NOT** include this member variable
                // int status = ColumnText.START_COLUMN;
                int status = 0;
                while (ColumnText.HasMoreText(status))
                {
                    ct.SetSimpleColumn(
                      COLUMNS[column][0], COLUMNS[column][1],
                      COLUMNS[column][2], COLUMNS[column][3]
                    );
                    ct.YLine = COLUMNS[column][3];
                    status = ct.Go();
                    linesWritten += ct.LinesWritten;
                    column = Math.Abs(column - 1);
                    if (column == 0) document.NewPage();
                }

                ct.AddText(new Phrase("Lines written: " + linesWritten));
                ct.Go();
            }
        }
Ejemplo n.º 9
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();
         }
     }
 }
Ejemplo n.º 10
0
		public override void DrawItem(PdfWriter pdfWriter,
		                              ICSharpCode.Reports.Core.Exporter.ExportRenderer.PdfUnitConverter converter)
		{
			if (pdfWriter == null) {
				throw new ArgumentNullException("pdfWriter");
			}
			if (converter == null) {
				throw new ArgumentNullException("converter");
			}
			base.DrawItem(pdfWriter,converter);
			
			iTextSharp.text.Font font = null;
			
			if (this.StyleDecorator.Font.Unit == GraphicsUnit.Point) {
				
				font = FontFactory.GetFont(this.StyleDecorator.Font.FontFamily.Name,
				                           BaseFont.IDENTITY_H,
				                           this.StyleDecorator.Font.Size,
				                           (int)this.StyleDecorator.Font.Style,
				                           this.StyleDecorator.PdfForeColor);
				
			} else {
				
				font = FontFactory.GetFont(this.StyleDecorator.Font.FontFamily.Name,
				                           BaseFont.IDENTITY_H,
				                           UnitConverter.FromPixel(this.StyleDecorator.Font.Size).Point,
				                           (int)this.StyleDecorator.Font.Style,
				                           this.StyleDecorator.PdfForeColor);
			}

			base.Decorate();
			
			PdfContentByte contentByte = base.PdfWriter.DirectContent;
		
			CalculatePdfFormat pdfFormat = new CalculatePdfFormat(this.StyleDecorator,font);
			
			ColumnText columnText = new ColumnText(contentByte);
			iTextSharp.text.Rectangle r = base.ConvertToPdfRectangle();
			columnText.SetSimpleColumn(r.Left, r.Top , r.Left + r.Width,r.Top - r.Height,pdfFormat.Leading,pdfFormat.Alignment);
		
			string formatedText = this.text;
			
			if (!String.IsNullOrEmpty(StyleDecorator.FormatString)) {
				formatedText = StandardFormatter.FormatOutput(this.text,this.StyleDecorator.FormatString,
				                                                 this.StyleDecorator.DataType,String.Empty);
			}
			
			Chunk chunk = new Chunk(formatedText,font);

			columnText.AddText(chunk);
			
			columnText.Go();
		}
Ejemplo n.º 11
0
// ===========================================================================
    /**
     * Draws the info about the movie.
     * @throws DocumentException 
     */
    protected override void DrawMovieInfo(
      Screening screening, PdfContentByte directcontent
    ) {
      base.DrawMovieInfo(screening, directcontent);
      Rectangle rect = GetPosition(screening);
      ColumnText column = new ColumnText(directcontent);
      column.SetSimpleColumn(
        new Phrase(screening.movie.Title),
        rect.Left, rect.Bottom,
        rect.Right, rect.Top, 18, Element.ALIGN_CENTER
      );
      column.Go();
    }
Ejemplo n.º 12
0
 /**
 * Returns the height of the cell.
 * @return  the height of the cell
 * @since   3.0.0
 */
 public float GetMaxHeight() {
     bool pivoted = (Rotation == 90 || Rotation == 270);
     Image img = this.Image;
     if (img != null) {
         img.ScalePercent(100);
         float refWidth = pivoted ? img.ScaledHeight : img.ScaledWidth;
         float scale = (Right - EffectivePaddingRight
                 - EffectivePaddingLeft - Left) / refWidth;
         img.ScalePercent(scale * 100);
         float refHeight = pivoted ? img.ScaledWidth : img.ScaledHeight;
         Bottom = Top - EffectivePaddingTop - EffectivePaddingBottom - refHeight;
     }
     else {
         if (pivoted && HasFixedHeight())
             Bottom = Top - FixedHeight;
         else {
             ColumnText ct = ColumnText.Duplicate(Column);
             float right, top, left, bottom;
             if (pivoted) {
                 right = PdfPRow.RIGHT_LIMIT;
                 top = Right - EffectivePaddingRight;
                 left = 0;
                 bottom = Left + EffectivePaddingLeft;
             }
             else {
                 right = NoWrap ? PdfPRow.RIGHT_LIMIT : Right - EffectivePaddingRight;
                 top = Top - EffectivePaddingTop;
                 left = Left + EffectivePaddingLeft;
                 bottom = HasFixedHeight() ? top + EffectivePaddingBottom - FixedHeight : PdfPRow.BOTTOM_LIMIT;
             }
             PdfPRow.SetColumn(ct, left, bottom, right, top);
             ct.Go(true);
             if (pivoted)
                 Bottom = Top - EffectivePaddingTop - EffectivePaddingBottom - ct.FilledWidth;
             else {
                 float yLine = ct.YLine;
                 if (UseDescender)
                     yLine += ct.Descender;
                 Bottom = yLine - EffectivePaddingBottom;
             }
         }
     }
     float height = Height;
     if (HasFixedHeight())
         height = FixedHeight;
     else if (HasMinimumHeight() && height < MinimumHeight)
         height = MinimumHeight;
     return height;
 }
Ejemplo n.º 13
0
 public void WriteTextWithWordSpacing()
 {
     Document document = new Document();
     FileStream output = new FileStream(TARGET + "textWithWorldSpacing.pdf", FileMode.Create);
     PdfWriter writer = PdfWriter.GetInstance(document, output);
     document.Open();
     document.SetPageSize(PageSize.A4);
     document.NewPage();
     writer.DirectContent.SetWordSpacing(10);
     ColumnText columnText = new ColumnText(writer.DirectContent);
     columnText.SetSimpleColumn(new Rectangle(30, 0, document.PageSize.Right, document.PageSize.Top - 30));
     columnText.UseAscender = true;
     columnText.AddText(new Chunk("H H H H H H H H H  !", new Font(fontWithToUnicode, 30)));
     columnText.Go();
     document.Close();
 }
Ejemplo n.º 14
0
        public void Go()
        {
            var outputFile = Helpers.IO.GetClassOutputPath(this);
            var imagePath = Helpers.IO.GetInputFilePath("100x100.jpg");
            var imageSpacerPath = Helpers.IO.GetInputFilePath("20x20.png");
            var testText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.";

            using (FileStream stream = new FileStream(
                outputFile,
                FileMode.Create,
                FileAccess.Write))
            {
                using (Document document = new Document())
                {
                    Image img = Image.GetInstance(imagePath);
                    PdfWriter writer = PdfWriter.GetInstance(document, stream);
                    // writer.InitialLeading = 108;
                    document.Open();

                    // document.Add(new Paragraph(img.Height.ToString()));
                    img.Alignment = Image.ALIGN_LEFT | Image.TEXTWRAP;
                    img.BorderWidth = 10;
                    img.ScaleToFit(1000, 72);
                    document.Add(img);
                    //img.BorderColor = BaseColor.RED;
                    var p = new Paragraph();
                    p.Add(testText);
                    document.Add(p);


                    PdfContentByte cb = writer.DirectContent;
                    ColumnText ct = new ColumnText(cb);
                    ct.SetSimpleColumn(new Phrase(new Chunk(testText, FontFactory.GetFont(FontFactory.HELVETICA, 18, Font.NORMAL))),
                                       46, 190, 530, 36, 25, Element.ALIGN_LEFT | Element.ALIGN_TOP);
                    ct.Go(); 

                    // document.Add(new Paragraph(testText));
                    // document.Add(new Chunk(testText));

                }
            }
        }
Ejemplo n.º 15
0
        /**
         * Consumes part of the content of the cell.
         * @param   height  the hight of the part that has to be consumed
         * @since   2.1.6
         */
        internal void ConsumeHeight(float height)
        {
            float rightLimit = Right - EffectivePaddingRight;
            float leftLimit  = Left + EffectivePaddingLeft;
            float bry        = height - EffectivePaddingTop - EffectivePaddingBottom;

            if (Rotation != 90 && Rotation != 270)
            {
                column.SetSimpleColumn(leftLimit, bry + 0.001f, rightLimit, 0);
            }
            else
            {
                column.SetSimpleColumn(0, leftLimit, bry + 0.001f, rightLimit);
            }
            try {
                column.Go(true);
            } catch (DocumentException) {
                // do nothing
            }
        }
Ejemplo n.º 16
0
// ---------------------------------------------------------------------------
    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();
      }
    }
Ejemplo n.º 17
0
		public override void DrawItem(PdfWriter pdfWriter,
		                              ICSharpCode.Reports.Core.Exporter.ExportRenderer.PdfUnitConverter converter)
		{
			if (pdfWriter == null) {
				throw new ArgumentNullException("pdfWriter");
			}
			if (converter == null) {
				throw new ArgumentNullException("converter");
			}
			base.DrawItem(pdfWriter,converter);

			base.Decorate();
	
			PdfContentByte contentByte = base.PdfWriter.DirectContent;
			
			iTextSharp.text.Font font = CreateFontFromFactory(this.StyleDecorator);
			CalculatePdfFormat pdfFormat = new CalculatePdfFormat(this.StyleDecorator,font);
			
			ColumnText columnText = new ColumnText(contentByte);

			if (StyleDecorator.RightToLeft.ToString() == "Yes") {
				columnText.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
			}
			
			iTextSharp.text.Rectangle r = base.ConvertToPdfRectangle();
			columnText.SetSimpleColumn(r.Left, r.Top , r.Left + r.Width,r.Top - r.Height,pdfFormat.Leading,pdfFormat.Alignment);
		
			string formatedText = this.Text;
			
			if (!String.IsNullOrEmpty(StyleDecorator.FormatString)) {
				formatedText = StandardFormatter.FormatOutput(this.Text,this.StyleDecorator.FormatString,
				                                                 this.StyleDecorator.DataType,String.Empty);
			}
			
			Chunk chunk = new Chunk(formatedText,font);

			columnText.AddText(chunk);
			
			columnText.Go();
		}
Ejemplo n.º 18
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);
        }
Ejemplo n.º 19
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();
      }
    }
Ejemplo n.º 20
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();
        }
Ejemplo n.º 21
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");
        }
Ejemplo n.º 22
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");
 }
Ejemplo n.º 23
0
        // try to balance out the content of the columns to have equal content length
        private float getBalanceDesiredHeight(PdfContentByte canvas, PdfDocument document, float documentY)
        {
            this.document = document;
            if (columnDefs.Count == 0)
            {
                throw new DocumentException("MultiColumnText has no columns");
            }

            float origintop     = top;
            float originnextY   = nextY;
            float originDesired = desiredHeight;

            desiredHeight = -1;
            float maxHeight = 0; // as much height that's left on the page

            top = document.GetVerticalPosition(true);
            foreach (ColumnDef cd in columnDefs)
            {
                float[] left  = cd.ResolvePositions(Rectangle.LEFT_BORDER);
                float[] right = cd.ResolvePositions(Rectangle.RIGHT_BORDER);
                maxHeight = Math.Max(maxHeight, GetHeight(left, right));
            }
            float measureHeight = maxHeight;
            float heightAdust   = maxHeight / 2.0f;

            float fitHeight = -1;
            bool  firstPass = true;

            while (heightAdust > 0.25)
            {
                ColumnText columnText = new ColumnText(canvas);
                columnText.Canvas = canvas;
                columnText.SetACopy(this.columnText);

                bool fitAll = false;
                desiredHeight = measureHeight;
                top           = origintop;
                nextY         = originnextY;

                float currentHeight = 0;
                bool  done          = false;
                while (!done)
                {
                    if (top == AUTOMATIC)
                    {
                        top = document.GetVerticalPosition(true);
                    }
                    else if (nextY == AUTOMATIC)
                    {
                        nextY = document.GetVerticalPosition(true); // RS - 07/07/2005 - - Get current doc writing position for top of columns on new page.
                    }

                    ColumnDef currentDef = (ColumnDef)columnDefs[CurrentColumn];
                    columnText.YLine = top;

                    float[] left  = currentDef.ResolvePositions(Rectangle.LEFT_BORDER);
                    float[] right = currentDef.ResolvePositions(Rectangle.RIGHT_BORDER);
                    if (document.IsMarginMirroring() && document.PageNumber % 2 == 0)
                    {
                        float delta = document.RightMargin - document.Left;
                        left  = (float[])left.Clone();
                        right = (float[])right.Clone();
                        for (int i = 0; i < left.Length; i += 2)
                        {
                            left[i] -= delta;
                        }
                        for (int i = 0; i < right.Length; i += 2)
                        {
                            right[i] -= delta;
                        }
                    }
                    currentHeight = Math.Max(currentHeight, GetHeight(left, right));
                    if (currentDef.IsSimple())
                    {
                        columnText.SetSimpleColumn(left[2], left[3], right[0], right[1]);
                    }
                    else
                    {
                        columnText.SetColumns(left, right);
                    }
                    int result = columnText.Go(true);
                    if ((result & ColumnText.NO_MORE_TEXT) != 0)
                    {
                        done   = true;
                        top    = columnText.YLine;
                        fitAll = true;
                    }
                    else if (ShiftCurrentColumn()) // NO_MORE_COLUMN, try to go to the next column
                    {
                        top = nextY;
                    }
                    else
                    {   // check if we are done because of height
                        fitAll = false;
                        done   = true;
                    }
                }
                ResetCurrentColumn();

                if (fitAll)
                {
                    fitHeight      = measureHeight;
                    measureHeight -= heightAdust;
                }
                else
                {
                    measureHeight += heightAdust;

                    // ok, so we've tried the full length! and it cannot fit.
                    // leave the current page as is, and we we'll try on the text page
                    if (firstPass)
                    {
                        break;
                    }
                }
                heightAdust /= 2.0f;
                firstPass    = false;
            }

            top           = origintop;
            nextY         = originnextY;
            desiredHeight = originDesired;

            return(fitHeight);
        }
Ejemplo n.º 24
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;
        }
Ejemplo n.º 25
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);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Write out the columns.  After writing, use
        /// {@link #isOverflow()} to see if all text was written.
        /// @throws DocumentException on error
        /// </summary>
        /// <param name="canvas">PdfContentByte to write with</param>
        /// <param name="document">document to write to (only used to get page limit info)</param>
        /// <param name="documentY">starting y position to begin writing at</param>
        /// <returns>the current height (y position) after writing the columns</returns>
        public float Write(PdfContentByte canvas, PdfDocument document, float documentY)
        {
            _document          = document;
            _columnText.Canvas = canvas;
            if (_columnDefs.Count == 0)
            {
                throw new DocumentException("MultiColumnText has no columns");
            }
            _overflow = false;
            float currentHeight = 0;
            var   done          = false;

            while (!done)
            {
                if (_top.ApproxEquals(AUTOMATIC))
                {
                    _top = document.GetVerticalPosition(true);
                }
                else if (_nextY.ApproxEquals(AUTOMATIC))
                {
                    _nextY = document.GetVerticalPosition(true); // RS - 07/07/2005 - - Get current doc writing position for top of columns on new page.
                }

                var currentDef = (ColumnDef)_columnDefs[CurrentColumn];
                _columnText.YLine = _top;

                var left  = currentDef.ResolvePositions(Rectangle.LEFT_BORDER);
                var right = currentDef.ResolvePositions(Rectangle.RIGHT_BORDER);
                if (document.IsMarginMirroring() && document.PageNumber % 2 == 0)
                {
                    var delta = document.RightMargin - document.Left;
                    left  = (float[])left.Clone();
                    right = (float[])right.Clone();
                    for (var i = 0; i < left.Length; i += 2)
                    {
                        left[i] -= delta;
                    }
                    for (var i = 0; i < right.Length; i += 2)
                    {
                        right[i] -= delta;
                    }
                }
                currentHeight = Math.Max(currentHeight, getHeight(left, right));

                if (currentDef.IsSimple())
                {
                    _columnText.SetSimpleColumn(left[2], left[3], right[0], right[1]);
                }
                else
                {
                    _columnText.SetColumns(left, right);
                }

                var result = _columnText.Go();
                if ((result & ColumnText.NO_MORE_TEXT) != 0)
                {
                    done = true;
                    _top = _columnText.YLine;
                }
                else if (ShiftCurrentColumn())
                {
                    _top = _nextY;
                }
                else
                {  // check if we are done because of height
                    _totalHeight += currentHeight;

                    if ((_desiredHeight.ApproxNotEqual(AUTOMATIC)) && (_totalHeight >= _desiredHeight))
                    {
                        _overflow = true;
                        break;
                    }
                    else
                    {  // need to start new page and reset the columns
                        documentY = _nextY;
                        newPage();
                        currentHeight = 0;
                    }
                }
            }
            if (_desiredHeight.ApproxEquals(AUTOMATIC) && _columnDefs.Count == 1)
            {
                currentHeight = documentY - _columnText.YLine;
            }
            return(currentHeight);
        }
Ejemplo n.º 27
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);
        }
Ejemplo n.º 28
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"));
 }
Ejemplo n.º 29
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));
        }
Ejemplo n.º 30
0
        public void CreateTaggedPdf21() {
            try {
                InitializeDocument("21");

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

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

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

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

                document.Close();
            }
            catch (Exception conformExc) {
                Assert.AreEqual("Template with tagged content could not be used more than once.", conformExc.Message);
                return;
            }
            finally {
                document.Close();
            }
            Assert.Fail("Expected error: 'Template with tagged content could not be used more than once.");
        }
Ejemplo n.º 31
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();
        }
Ejemplo n.º 32
0
        /**
         * Splits a row to newHeight. The returned row is the remainder. It will
         * return null if the newHeight was so small that only an empty row would
         * result.
         *
         * @param newHeight
         *            the new height
         * @return the remainder row or null if the newHeight was so small that only
         *         an empty row would result
         */
        public PdfPRow SplitRow(float newHeight)
        {
            PdfPCell[] newCells = new PdfPCell[cells.Length];
            float[]    fh       = new float[cells.Length * 2];
            bool       allEmpty = true;

            for (int k = 0; k < cells.Length; ++k)
            {
                PdfPCell cell = cells[k];
                if (cell == null)
                {
                    continue;
                }
                fh[k * 2]     = cell.FixedHeight;
                fh[k * 2 + 1] = cell.MinimumHeight;
                Image    img = cell.Image;
                PdfPCell c2  = new PdfPCell(cell);
                if (img != null)
                {
                    if (newHeight > cell.EffectivePaddingBottom
                        + cell.EffectivePaddingTop + 2)
                    {
                        c2.Phrase = null;
                        allEmpty  = false;
                    }
                }
                else
                {
                    int        status;
                    float      y;
                    ColumnText ct = ColumnText.Duplicate(cell.Column);
                    if (cell.Rotation == 90 || cell.Rotation == 270)
                    {
                        y = SetColumn(ct,
                                      cell.Top - newHeight + cell.EffectivePaddingBottom,
                                      cell.Left + cell.EffectivePaddingLeft,
                                      cell.Top - cell.EffectivePaddingTop,
                                      cell.Right - cell.EffectivePaddingRight);
                    }
                    else
                    {
                        float rightLimit = cell.NoWrap ? 20000 : cell.Right
                                           - cell.EffectivePaddingRight;
                        float y1 = cell.Top - newHeight
                                   + cell.EffectivePaddingBottom;
                        float y2 = cell.Top - cell.EffectivePaddingTop;
                        y = Math.Max(y1, y2);
                        y = SetColumn(ct,
                                      cell.Left + cell.EffectivePaddingLeft, y1,
                                      rightLimit, y2);
                    }
                    status = ct.Go(true);
                    bool thisEmpty = (ct.YLine == y);
                    if (thisEmpty)
                    {
                        ct = ColumnText.Duplicate(cell.Column);
                    }
                    allEmpty = (allEmpty && thisEmpty);
                    if ((status & ColumnText.NO_MORE_TEXT) == 0 || thisEmpty)
                    {
                        c2.Column      = ct;
                        ct.FilledWidth = 0;
                    }
                    else
                    {
                        c2.Phrase = null;
                    }
                }
                newCells[k]      = c2;
                cell.FixedHeight = newHeight;
            }
            if (allEmpty)
            {
                for (int k = 0; k < cells.Length; ++k)
                {
                    PdfPCell cell = cells[k];
                    if (cell == null)
                    {
                        continue;
                    }
                    float f = fh[k * 2];
                    float m = fh[k * 2 + 1];
                    if (f <= 0)
                    {
                        cell.MinimumHeight = m;
                    }
                    else
                    {
                        cell.FixedHeight = f;
                    }
                }
                return(null);
            }
            CalculateHeights();
            PdfPRow split = new PdfPRow(newCells);

            split.widths = (float[])widths.Clone();
            split.CalculateHeights();
            return(split);
        }
Ejemplo n.º 33
0
    /**
     * Fits the text to some rectangle adjusting the font size as needed.
     * @param font the font to use
     * @param text the text
     * @param rect the rectangle where the text must fit
     * @param maxFontSize the maximum font size
     * @param runDirection the run direction
     * @return the calculated font size that makes the text fit
     */
    public static float FitText(Font font, String text, Rectangle rect, float maxFontSize, int runDirection) {
        ColumnText ct = null;
        int status = 0;
        if (maxFontSize <= 0) {
            int cr = 0;
            int lf = 0;
            char[] t = text.ToCharArray();
            for (int k = 0; k < t.Length; ++k) {
                if (t[k] == '\n')
                    ++lf;
                else if (t[k] == '\r')
                    ++cr;
            }
            int minLines = Math.Max(cr, lf) + 1;
            maxFontSize = Math.Abs(rect.Height) / minLines - 0.001f;
        }
        font.Size = maxFontSize;
        Phrase ph = new Phrase(text, font);
        ct = new ColumnText(null);
        ct.SetSimpleColumn(ph, rect.Left, rect.Bottom, rect.Right, rect.Top, maxFontSize, Element.ALIGN_LEFT);
        ct.RunDirection = runDirection;
        status = ct.Go(true);
        if ((status & NO_MORE_TEXT) != 0)
            return maxFontSize;
        float precision = 0.1f;
        float min = 0;
        float max = maxFontSize;
        float size = maxFontSize;
        for (int k = 0; k < 50; ++k) { //just in case it doesn't converge
            size = (min + max) / 2;
            ct = new ColumnText(null);
            font.Size = size;
            ct.SetSimpleColumn(new Phrase(text, font), rect.Left, rect.Bottom, rect.Right, rect.Top, size, Element.ALIGN_LEFT);
            ct.RunDirection = runDirection;
            status = ct.Go(true);
            if ((status & NO_MORE_TEXT) != 0) {
                if (max - min < size * precision)
                    return size;
                min = size;
            }
            else
                max = size;
        }
        return size;
	}
Ejemplo n.º 34
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);
        }
Ejemplo n.º 35
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);
        }
Ejemplo n.º 36
0
        /**
         * Writes a number of cells (not necessarily all cells).
         *
         * @param    colStart The first column to be written.
         * Remember that the column index starts with 0.
         * @param    colEnd The last column to be written.
         * Remember that the column index starts with 0.
         * If -1, all the columns to the end are written.
         * @param    xPos The x-coordinate where the table starts on the canvas
         * @param    yPos The y-coordinate where the table starts on the canvas
         * @param   reusable if set to false, the content in the cells is "consumed";
         * if true, you can reuse the cells, the row, the parent table as many times you want.
         * @since 5.1.0 added the reusable parameter
         */
        public void WriteCells(int colStart, int colEnd, float xPos, float yPos, PdfContentByte[] canvases, bool reusable)
        {
            if (!calculated)
            {
                CalculateHeights();
            }
            if (colEnd < 0)
            {
                colEnd = cells.Length;
            }
            else
            {
                colEnd = Math.Min(colEnd, cells.Length);
            }
            if (colStart < 0)
            {
                colStart = 0;
            }
            if (colStart >= colEnd)
            {
                return;
            }

            int newStart;

            for (newStart = colStart; newStart >= 0; --newStart)
            {
                if (cells[newStart] != null)
                {
                    break;
                }
                if (newStart > 0)
                {
                    xPos -= widths[newStart - 1];
                }
            }

            if (newStart < 0)
            {
                newStart = 0;
            }
            if (cells[newStart] != null)
            {
                xPos -= cells[newStart].Left;
            }

            for (int k = newStart; k < colEnd; ++k)
            {
                PdfPCell cell = cells[k];
                if (cell == null)
                {
                    continue;
                }
                float currentMaxHeight = maxHeight + extraHeights[k];

                WriteBorderAndBackground(xPos, yPos, currentMaxHeight, cell, canvases);

                Image img = cell.Image;

                float tly = cell.Top + yPos - cell.EffectivePaddingTop;
                if (cell.Height <= currentMaxHeight)
                {
                    switch (cell.VerticalAlignment)
                    {
                    case Element.ALIGN_BOTTOM:
                        tly = cell.Top + yPos - currentMaxHeight + cell.Height
                              - cell.EffectivePaddingTop;
                        break;

                    case Element.ALIGN_MIDDLE:
                        tly = cell.Top + yPos + (cell.Height - currentMaxHeight) / 2
                              - cell.EffectivePaddingTop;
                        break;

                    default:
                        break;
                    }
                }
                if (img != null)
                {
                    if (cell.Rotation != 0)
                    {
                        img          = Image.GetInstance(img);
                        img.Rotation = img.GetImageRotation() + (float)(cell.Rotation * Math.PI / 180.0);
                    }
                    bool vf = false;
                    if (cell.Height > currentMaxHeight)
                    {
                        img.ScalePercent(100);
                        float scale = (currentMaxHeight - cell.EffectivePaddingTop - cell
                                       .EffectivePaddingBottom)
                                      / img.ScaledHeight;
                        img.ScalePercent(scale * 100);
                        vf = true;
                    }
                    float left = cell.Left + xPos
                                 + cell.EffectivePaddingLeft;
                    if (vf)
                    {
                        switch (cell.HorizontalAlignment)
                        {
                        case Element.ALIGN_CENTER:
                            left = xPos
                                   + (cell.Left + cell.EffectivePaddingLeft
                                      + cell.Right
                                      - cell.EffectivePaddingRight - img
                                      .ScaledWidth) / 2;
                            break;

                        case Element.ALIGN_RIGHT:
                            left = xPos + cell.Right
                                   - cell.EffectivePaddingRight
                                   - img.ScaledWidth;
                            break;

                        default:
                            break;
                        }
                        tly = cell.Top + yPos - cell.EffectivePaddingTop;
                    }
                    img.SetAbsolutePosition(left, tly - img.ScaledHeight);
                    canvases[PdfPTable.TEXTCANVAS].AddImage(img);
                }
                else
                {
                    // rotation sponsored by Connection GmbH
                    if (cell.Rotation == 90 || cell.Rotation == 270)
                    {
                        float      netWidth  = currentMaxHeight - cell.EffectivePaddingTop - cell.EffectivePaddingBottom;
                        float      netHeight = cell.Width - cell.EffectivePaddingLeft - cell.EffectivePaddingRight;
                        ColumnText ct        = ColumnText.Duplicate(cell.Column);
                        ct.Canvases = canvases;
                        ct.SetSimpleColumn(0, 0, netWidth + 0.001f, -netHeight);
                        ct.Go(true);
                        float calcHeight = -ct.YLine;
                        if (netWidth <= 0 || netHeight <= 0)
                        {
                            calcHeight = 0;
                        }
                        if (calcHeight > 0)
                        {
                            if (cell.UseDescender)
                            {
                                calcHeight -= ct.Descender;
                            }
                            ct          = ColumnText.Duplicate(cell.Column);
                            ct.Canvases = canvases;
                            ct.SetSimpleColumn(-0.003f, -0.001f, netWidth + 0.003f, calcHeight);
                            float pivotX;
                            float pivotY;
                            if (cell.Rotation == 90)
                            {
                                pivotY = cell.Top + yPos - currentMaxHeight + cell.EffectivePaddingBottom;
                                switch (cell.VerticalAlignment)
                                {
                                case Element.ALIGN_BOTTOM:
                                    pivotX = cell.Left + xPos + cell.Width - cell.EffectivePaddingRight;
                                    break;

                                case Element.ALIGN_MIDDLE:
                                    pivotX = cell.Left + xPos + (cell.Width + cell.EffectivePaddingLeft - cell.EffectivePaddingRight + calcHeight) / 2;
                                    break;

                                default: //top
                                    pivotX = cell.Left + xPos + cell.EffectivePaddingLeft + calcHeight;
                                    break;
                                }
                                SaveAndRotateCanvases(canvases, 0, 1, -1, 0, pivotX, pivotY);
                            }
                            else
                            {
                                pivotY = cell.Top + yPos - cell.EffectivePaddingTop;
                                switch (cell.VerticalAlignment)
                                {
                                case Element.ALIGN_BOTTOM:
                                    pivotX = cell.Left + xPos + cell.EffectivePaddingLeft;
                                    break;

                                case Element.ALIGN_MIDDLE:
                                    pivotX = cell.Left + xPos + (cell.Width + cell.EffectivePaddingLeft - cell.EffectivePaddingRight - calcHeight) / 2;
                                    break;

                                default: //top
                                    pivotX = cell.Left + xPos + cell.Width - cell.EffectivePaddingRight - calcHeight;
                                    break;
                                }
                                SaveAndRotateCanvases(canvases, 0, -1, 1, 0, pivotX, pivotY);
                            }
                            try {
                                ct.Go();
                            } finally {
                                RestoreCanvases(canvases);
                            }
                        }
                    }
                    else
                    {
                        float fixedHeight = cell.FixedHeight;
                        float rightLimit  = cell.Right + xPos
                                            - cell.EffectivePaddingRight;
                        float leftLimit = cell.Left + xPos
                                          + cell.EffectivePaddingLeft;
                        if (cell.NoWrap)
                        {
                            switch (cell.HorizontalAlignment)
                            {
                            case Element.ALIGN_CENTER:
                                rightLimit += 10000;
                                leftLimit  -= 10000;
                                break;

                            case Element.ALIGN_RIGHT:
                                if (cell.Rotation == 180)
                                {
                                    rightLimit += RIGHT_LIMIT;
                                }
                                else
                                {
                                    leftLimit -= RIGHT_LIMIT;
                                }
                                break;

                            default:
                                if (cell.Rotation == 180)
                                {
                                    leftLimit -= RIGHT_LIMIT;
                                }
                                else
                                {
                                    rightLimit += RIGHT_LIMIT;
                                }
                                break;
                            }
                        }
                        ColumnText ct;
                        if (reusable)
                        {
                            ct = ColumnText.Duplicate(cell.Column);
                        }
                        else
                        {
                            ct = cell.Column;
                        }
                        ct.Canvases = canvases;
                        float bry = tly
                                    - (currentMaxHeight
                                       - cell.EffectivePaddingTop - cell.EffectivePaddingBottom);
                        if (fixedHeight > 0)
                        {
                            if (cell.Height > currentMaxHeight)
                            {
                                tly = cell.Top + yPos - cell.EffectivePaddingTop;
                                bry = cell.Top + yPos - currentMaxHeight + cell.EffectivePaddingBottom;
                            }
                        }
                        if ((tly > bry || ct.ZeroHeightElement()) && leftLimit < rightLimit)
                        {
                            ct.SetSimpleColumn(leftLimit, bry - 0.001f, rightLimit, tly);
                            if (cell.Rotation == 180)
                            {
                                float shx = leftLimit + rightLimit;
                                float shy = yPos + yPos - currentMaxHeight + cell.EffectivePaddingBottom - cell.EffectivePaddingTop;
                                SaveAndRotateCanvases(canvases, -1, 0, 0, -1, shx, shy);
                            }
                            try {
                                ct.Go();
                            } finally {
                                if (cell.Rotation == 180)
                                {
                                    RestoreCanvases(canvases);
                                }
                            }
                        }
                    }
                }
                IPdfPCellEvent evt = cell.CellEvent;
                if (evt != null)
                {
                    Rectangle rect = new Rectangle(cell.Left + xPos, cell.Top
                                                   + yPos - currentMaxHeight, cell.Right + xPos, cell.Top
                                                   + yPos);
                    evt.CellLayout(cell, rect, canvases);
                }
            }
        }
Ejemplo n.º 37
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");
        }
Ejemplo n.º 38
0
        /**
         * Splits a row to newHeight.
         * The returned row is the remainder. It will return null if the newHeight
         * was so small that only an empty row would result.
         *
         * @param new_height the new height
         * @return the remainder row or null if the newHeight was so small that only
         * an empty row would result
         */
        public PdfPRow SplitRow(PdfPTable table, int rowIndex, float new_height)
        {
            // second part of the row
            PdfPCell[] newCells = new PdfPCell[cells.Length];
            float[]    fixHs    = new float[cells.Length];
            float[]    minHs    = new float[cells.Length];
            bool       allEmpty = true;

            // loop over all the cells
            for (int k = 0; k < cells.Length; ++k)
            {
                float    newHeight = new_height;
                PdfPCell cell      = cells[k];
                if (cell == null)
                {
                    int index = rowIndex;
                    if (table.RowSpanAbove(index, k))
                    {
                        while (table.RowSpanAbove(--index, k))
                        {
                            newHeight += table.GetRow(index).MaxHeights;
                        }
                        PdfPRow row = table.GetRow(index);
                        if (row != null && row.GetCells()[k] != null)
                        {
                            newCells[k]         = new PdfPCell(row.GetCells()[k]);
                            newCells[k].Column  = null;
                            newCells[k].Rowspan = row.GetCells()[k].Rowspan - rowIndex + index;
                            allEmpty            = false;
                        }
                    }
                    continue;
                }
                fixHs[k] = cell.FixedHeight;
                minHs[k] = cell.MinimumHeight;
                Image    img     = cell.Image;
                PdfPCell newCell = new PdfPCell(cell);
                if (img != null)
                {
                    if (newHeight > cell.EffectivePaddingBottom + cell.EffectivePaddingTop + 2)
                    {
                        newCell.Phrase = null;
                        allEmpty       = false;
                    }
                }
                else
                {
                    float      y;
                    ColumnText ct     = ColumnText.Duplicate(cell.Column);
                    float      left   = cell.Left + cell.EffectivePaddingLeft;
                    float      bottom = cell.Top + cell.EffectivePaddingBottom - newHeight;
                    float      right  = cell.Right - cell.EffectivePaddingRight;
                    float      top    = cell.Top - cell.EffectivePaddingTop;
                    switch (cell.Rotation)
                    {
                    case 90:
                    case 270:
                        y = SetColumn(ct, bottom, left, top, right);
                        break;

                    default:
                        y = SetColumn(ct, left, bottom + 0.00001f, cell.NoWrap ? RIGHT_LIMIT : right, top);
                        break;
                    }
                    int status;
                    status = ct.Go(true);
                    bool thisEmpty = (ct.YLine == y);
                    if (thisEmpty)
                    {
                        newCell.Column = ColumnText.Duplicate(cell.Column);
                        ct.FilledWidth = 0;
                    }
                    else if ((status & ColumnText.NO_MORE_TEXT) == 0)
                    {
                        newCell.Column = ct;
                        ct.FilledWidth = 0;
                    }
                    else
                    {
                        newCell.Phrase = null;
                    }
                    allEmpty = (allEmpty && thisEmpty);
                }
                newCells[k]      = newCell;
                cell.FixedHeight = newHeight;
            }
            if (allEmpty)
            {
                for (int k = 0; k < cells.Length; ++k)
                {
                    PdfPCell cell = cells[k];
                    if (cell == null)
                    {
                        continue;
                    }
                    if (fixHs[k] > 0)
                    {
                        cell.FixedHeight = fixHs[k];
                    }
                    else
                    {
                        cell.MinimumHeight = minHs[k];
                    }
                }
                return(null);
            }
            CalculateHeights();
            PdfPRow split = new PdfPRow(newCells);

            split.widths = (float[])widths.Clone();
            return(split);
        }
Ejemplo n.º 39
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);
        }
Ejemplo n.º 40
0
        /**
         * Get the <code>PdfAppearance</code> of a text or combo field
         * @throws IOException on error
         * @throws DocumentException on error
         * @return A <code>PdfAppearance</code>
         */
        public PdfAppearance GetAppearance()
        {
            PdfAppearance app = GetBorderAppearance();

            app.BeginVariableText();
            if (text == null || text.Length == 0)
            {
                app.EndVariableText();
                return(app);
            }
            bool  borderExtra = borderStyle == PdfBorderDictionary.STYLE_BEVELED || borderStyle == PdfBorderDictionary.STYLE_INSET;
            float h           = box.Height - borderWidth * 2 - extraMarginTop;
            float bw2         = borderWidth;

            if (borderExtra)
            {
                h   -= borderWidth * 2;
                bw2 *= 2;
            }
            float offsetX = Math.Max(bw2, 1);
            float offX    = Math.Min(bw2, offsetX);

            app.SaveState();
            app.Rectangle(offX, offX, box.Width - 2 * offX, box.Height - 2 * offX);
            app.Clip();
            app.NewPath();
            String ptext;

            if ((options & PASSWORD) != 0)
            {
                ptext = ObfuscatePassword(text);
            }
            else if ((options & MULTILINE) == 0)
            {
                ptext = RemoveCRLF(text);
            }
            else
            {
                ptext = text; //fixed by Kazuya Ujihara (ujihara.jp)
            }
            BaseFont  ufont  = RealFont;
            BaseColor fcolor = (textColor == null) ? GrayColor.GRAYBLACK : textColor;
            int       rtl    = CheckRTL(ptext) ? PdfWriter.RUN_DIRECTION_LTR : PdfWriter.RUN_DIRECTION_NO_BIDI;
            float     usize  = fontSize;
            Phrase    phrase = ComposePhrase(ptext, ufont, fcolor, usize);

            if ((options & MULTILINE) != 0)
            {
                float      width  = box.Width - 4 * offsetX - extraMarginLeft;
                float      factor = ufont.GetFontDescriptor(BaseFont.BBOXURY, 1) - ufont.GetFontDescriptor(BaseFont.BBOXLLY, 1);
                ColumnText ct     = new ColumnText(null);
                if (usize == 0)
                {
                    usize = h / factor;
                    if (usize > 4)
                    {
                        if (usize > 12)
                        {
                            usize = 12;
                        }
                        float step = Math.Max((usize - 4) / 10, 0.2f);
                        ct.SetSimpleColumn(0, -h, width, 0);
                        ct.Alignment    = alignment;
                        ct.RunDirection = rtl;
                        for (; usize > 4; usize -= step)
                        {
                            ct.YLine = 0;
                            ChangeFontSize(phrase, usize);
                            ct.SetText(phrase);
                            ct.Leading = factor * usize;
                            int status = ct.Go(true);
                            if ((status & ColumnText.NO_MORE_COLUMN) == 0)
                            {
                                break;
                            }
                        }
                    }
                    if (usize < 4)
                    {
                        usize = 4;
                    }
                }
                ChangeFontSize(phrase, usize);
                ct.Canvas = app;
                float leading = usize * factor;
                float offsetY = offsetX + h - ufont.GetFontDescriptor(BaseFont.BBOXURY, usize);
                ct.SetSimpleColumn(extraMarginLeft + 2 * offsetX, -20000, box.Width - 2 * offsetX, offsetY + leading);
                ct.Leading      = leading;
                ct.Alignment    = alignment;
                ct.RunDirection = rtl;
                ct.SetText(phrase);
                ct.Go();
            }
            else
            {
                if (usize == 0)
                {
                    float maxCalculatedSize = h / (ufont.GetFontDescriptor(BaseFont.BBOXURX, 1) - ufont.GetFontDescriptor(BaseFont.BBOXLLY, 1));
                    ChangeFontSize(phrase, 1);
                    float wd = ColumnText.GetWidth(phrase, rtl, 0);
                    if (wd == 0)
                    {
                        usize = maxCalculatedSize;
                    }
                    else
                    {
                        usize = Math.Min(maxCalculatedSize, (box.Width - extraMarginLeft - 4 * offsetX) / wd);
                    }
                    if (usize < 4)
                    {
                        usize = 4;
                    }
                }
                ChangeFontSize(phrase, usize);
                float offsetY = offX + ((box.Height - 2 * offX) - ufont.GetFontDescriptor(BaseFont.ASCENT, usize)) / 2;
                if (offsetY < offX)
                {
                    offsetY = offX;
                }
                if (offsetY - offX < -ufont.GetFontDescriptor(BaseFont.DESCENT, usize))
                {
                    float ny = -ufont.GetFontDescriptor(BaseFont.DESCENT, usize) + offX;
                    float dy = box.Height - offX - ufont.GetFontDescriptor(BaseFont.ASCENT, usize);
                    offsetY = Math.Min(ny, Math.Max(offsetY, dy));
                }
                if ((options & COMB) != 0 && maxCharacterLength > 0)
                {
                    int textLen  = Math.Min(maxCharacterLength, ptext.Length);
                    int position = 0;
                    if (alignment == Element.ALIGN_RIGHT)
                    {
                        position = maxCharacterLength - textLen;
                    }
                    else if (alignment == Element.ALIGN_CENTER)
                    {
                        position = (maxCharacterLength - textLen) / 2;
                    }
                    float step  = (box.Width - extraMarginLeft) / maxCharacterLength;
                    float start = step / 2 + position * step;
                    if (textColor == null)
                    {
                        app.SetGrayFill(0);
                    }
                    else
                    {
                        app.SetColorFill(textColor);
                    }
                    app.BeginText();
                    foreach (Chunk ck in phrase)
                    {
                        BaseFont bf = ck.Font.BaseFont;
                        app.SetFontAndSize(bf, usize);
                        StringBuilder sb = ck.Append("");
                        for (int j = 0; j < sb.Length; ++j)
                        {
                            String c  = sb.ToString(j, 1);
                            float  wd = bf.GetWidthPoint(c, usize);
                            app.SetTextMatrix(extraMarginLeft + start - wd / 2, offsetY - extraMarginTop);
                            app.ShowText(c);
                            start += step;
                        }
                    }
                    app.EndText();
                }
                else
                {
                    float x;
                    switch (alignment)
                    {
                    case Element.ALIGN_RIGHT:
                        x = extraMarginLeft + box.Width - (2 * offsetX);
                        break;

                    case Element.ALIGN_CENTER:
                        x = extraMarginLeft + (box.Width / 2);
                        break;

                    default:
                        x = extraMarginLeft + (2 * offsetX);
                        break;
                    }
                    ColumnText.ShowTextAligned(app, alignment, phrase, x, offsetY - extraMarginTop, 0, rtl, 0);
                }
            }
            app.RestoreState();
            app.EndVariableText();
            return(app);
        }
Ejemplo n.º 41
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");
        }
Ejemplo n.º 42
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));
        }
    //	[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;
        }
Ejemplo n.º 44
0
 /**
  * Calculates the heights of each cell in the row.
  * @return the maximum height of the row.
  */
 public float CalculateHeights()
 {
     maxHeight = 0;
     for (int k = 0; k < cells.Length; ++k)
     {
         PdfPCell cell = cells[k];
         if (cell == null)
         {
             continue;
         }
         Image img = cell.Image;
         if (img != null)
         {
             img.ScalePercent(100);
             float refWidth = img.ScaledWidth;
             if (cell.Rotation == 90 || cell.Rotation == 270)
             {
                 refWidth = img.ScaledHeight;
             }
             float scale = (cell.Right - cell.EffectivePaddingRight
                            - cell.EffectivePaddingLeft - cell.Left)
                           / refWidth;
             img.ScalePercent(scale * 100);
             float refHeight = img.ScaledHeight;
             if (cell.Rotation == 90 || cell.Rotation == 270)
             {
                 refHeight = img.ScaledWidth;
             }
             cell.Bottom = cell.Top - cell.EffectivePaddingTop
                           - cell.EffectivePaddingBottom
                           - refHeight;
         }
         else
         {
             if (cell.Rotation == 0 || cell.Rotation == 180)
             {
                 float rightLimit = cell.NoWrap ? 20000 : cell.Right
                                    - cell.EffectivePaddingRight;
                 float bry = (cell.FixedHeight > 0) ? cell.Top
                             - cell.EffectivePaddingTop
                             + cell.EffectivePaddingBottom
                             - cell.FixedHeight : BOTTOM_LIMIT;
                 ColumnText ct = ColumnText.Duplicate(cell.Column);
                 SetColumn(ct,
                           cell.Left + cell.EffectivePaddingLeft, bry,
                           rightLimit, cell.Top - cell.EffectivePaddingTop);
                 ct.Go(true);
                 float yLine = ct.YLine;
                 if (cell.UseDescender)
                 {
                     yLine += ct.Descender;
                 }
                 cell.Bottom = yLine - cell.EffectivePaddingBottom;
             }
             else
             {
                 if (cell.FixedHeight > 0)
                 {
                     cell.Bottom = cell.Top - cell.FixedHeight;
                 }
                 else
                 {
                     ColumnText ct = ColumnText.Duplicate(cell.Column);
                     SetColumn(ct, 0, cell.Left + cell.EffectivePaddingLeft,
                               20000, cell.Right - cell.EffectivePaddingRight);
                     ct.Go(true);
                     cell.Bottom = cell.Top - cell.EffectivePaddingTop
                                   - cell.EffectivePaddingBottom - ct.FilledWidth;
                 }
             }
         }
         float height = cell.FixedHeight;
         if (height <= 0)
         {
             height = cell.Height;
         }
         if (height < cell.FixedHeight)
         {
             height = cell.FixedHeight;
         }
         else if (height < cell.MinimumHeight)
         {
             height = cell.MinimumHeight;
         }
         if (height > maxHeight)
         {
             maxHeight = height;
         }
     }
     calculated = true;
     return(maxHeight);
 }