Module: PdfExtract::Columns

Defined in:
lib/analysis/columns.rb

Class Method Summary collapse

Class Method Details

.columns_at(y, body_regions) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/analysis/columns.rb', line 16

def self.columns_at y, body_regions
  x_mask = MultiRange.new

  body_regions.each do |region|
    if region[:y] <= y && (region[:y] + region[:height]) >= y
      x_mask.append(region[:x] .. (region[:x] + region[:width]))
    end
  end

  x_mask
end

.include_in(pdf) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/analysis/columns.rb', line 28

def self.include_in pdf
  deps = [:regions, :bodies]
  pdf.spatials :columns, :paged => true, :depends_on => deps do |parser|

    body = nil
    body_regions = []

    parser.before do
      body_regions = []
    end

    parser.objects :bodies do |b|
      body = b
    end

    parser.objects :regions do |region|
      if Spatial.contains? body, region
        body_regions << region
      end
    end

    parser.after do
      column_sample_count = pdf.settings[:column_sample_count]

      step = 1.0 / (column_sample_count + 1)
      column_ranges = []

      (1 .. column_sample_count).each do |i|
        y = body[:y] + (body[:height] * i * step)
        column_ranges << columns_at(y, body_regions)
      end

      # Discard those with a coverage of 0.
      column_ranges.reject! { |r| r.covered.zero? }

      # Discard those with more than x columns. They've probably hit a table.
      column_ranges.reject! { |r| r.count > pdf.settings[:max_column_count] }

      # Discard ranges that comprise only of very narrow columns.
      # Likely tables or columns picking up on false tab stops.
      column_ranges.reject! { |r| r.widest < (0.25 * body[:width]) }

      if column_ranges.count.zero?
        []
      else
        # Find the highest column count.
        most = column_ranges.max_by { |r| r.count }.count
        column_ranges.reject! { |r| r.count != most }

        # Take the columns that are widest.
        widest = column_ranges.map { |r| r.avg }.max
        column_ranges.reject! { |r| r.avg < widest }

        column_ranges.first.ranges.map do |range|
          body.merge({:x => range.min, :width => range.max - range.min })
        end
      end
    end

  end
end