DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Ruby FPDF PDF_MC_Table Port

01.09.2006
| 3990 views |
  • submit to reddit
        My old direct port of FPDF MultiCell tables to Ruby from PHP.  I'm sure there are at least 30 better ways to do this :-) (PDF::Writer is more popular now anyway)

FPDF: http://fpdf.org/en/script/script3.php
Ruby FPDF: http://brian.imxcc.com/fpdf/

require 'fpdf'

class PDF_MC_Table < FPDF
  attr_reader :widths, :aligns

  def SetWidths (w)
    # Set the array of column widths
    @widths=w;
  end

  def SetAligns (a)
    # Set the array of column alignments
    @aligns=a;
  end

  def Row (data)
    # Calculate the height of the row
    nb = 0
    0.upto(data.length - 1) do |i|
      num_lines = NbLines(@widths[i],data[i])
      nb = num_lines if num_lines > nb
    end
    h = 5 * nb
    # Issue a page break first if needed
    CheckPageBreak(h)
    # Draw the cells of the row
    0.upto(data.length - 1) do |i|
        w = @widths[i]
        a = ( (@aligns && @aligns[i]) ? @aligns[i] : 'L' )
        # Save the current position
        x = GetX()
        y = GetY()
        # Draw the border
        Rect(x,y,w,h)
        # Print the text
        MultiCell(w,5,data[i],0,a)
        # Put the position to the right of the cell
        SetXY(x+w,y)
    end
    # Go to the next line
    Ln(h)
  end

  def CheckPageBreak(h)
    # If the height h would cause an overflow, add a new page immediately
    AddPage(@CurOrientation) if GetY()+h > @PageBreakTrigger
  end

  def NbLines(w,txt)
    # Computes the number of lines a MultiCell of width w will take
    cw = @CurrentFont['cw']
    w = w - @rMargin - @x if ( w==0 )
    wmax = ( w - 2 * @cMargin ) * 1000 / @FontSize
    s = txt ? txt.gsub(/\r/,'') : ''
    nb = s.length
    nb -= 1 if ( nb > 0 and s[nb-1]==10 ) # strip a trailing \n
    sep = -1
    i = 0
    j = 0
    l = 0
    nl = 1
    while(i < nb) do
      c=s[i] #go through the string character by character
      if(c==10) #if we find a newline just skip the rest
	i += 1
        sep = -1
        j = i
        l = 0
        nl += 1
        next
      end
      sep = i if (c==' ')
      l = l + cw[c]
      if(l>wmax)
        if(sep==-1)
          if(i==j)
	    i += 1
	  end
        else
	  i = sep+1
	end
        sep = -1
        j = i
        l = 0
        nl += 1
      else
	i += 1
      end
    end
    return nl
  end
end