From 7934124221d1a436347fb98d60df59fc7b7f7335 Mon Sep 17 00:00:00 2001 From: ekkxl Date: Mon, 23 Jan 2023 16:03:54 -0500 Subject: [PATCH] Add line_widths to Prawn::Text::Formatted::Box --- lib/prawn/text/formatted/box.rb | 4 +++ lib/prawn/text/formatted/wrap.rb | 2 ++ spec/prawn/text/formatted/box_spec.rb | 48 +++++++++++++++++++++++++++ 3 files changed, 54 insertions(+) diff --git a/lib/prawn/text/formatted/box.rb b/lib/prawn/text/formatted/box.rb index 16b6b3a4f..1ee41fc87 100644 --- a/lib/prawn/text/formatted/box.rb +++ b/lib/prawn/text/formatted/box.rb @@ -130,6 +130,8 @@ def everything_printed? attr_reader :descender # The leading used during printing attr_reader :leading + # The width of each line + attr_reader :line_widths def line_gap line_height - (ascender + descender) @@ -194,6 +196,8 @@ def initialize(formatted_text, options = {}) style: options[:style] } + @line_widths = [] + super(formatted_text, options) end diff --git a/lib/prawn/text/formatted/wrap.rb b/lib/prawn/text/formatted/wrap.rb index 81b4fdac5..cf342f809 100644 --- a/lib/prawn/text/formatted/wrap.rb +++ b/lib/prawn/text/formatted/wrap.rb @@ -106,6 +106,8 @@ def print_line accumulated_width += fragment_this_line.width end + @line_widths.push(accumulated_width) + @printed_lines << printed_fragments.map do |s| s.dup.force_encoding(::Encoding::UTF_8) end.join diff --git a/spec/prawn/text/formatted/box_spec.rb b/spec/prawn/text/formatted/box_spec.rb index 327a788d0..7f32b39c4 100644 --- a/spec/prawn/text/formatted/box_spec.rb +++ b/spec/prawn/text/formatted/box_spec.rb @@ -906,4 +906,52 @@ def render_in_front(fragment); end ) end end + + describe 'Text::Formatted::box#line_widths' do + it 'handles newlines' do + accented_char = win1252_string("\xE9"); # é in win-1252 + array = [ + { + text: "Oh hai t#{accented_char}xt rect.\nOh hai text rect thats longer.", + font: 'Times-Roman', + size: 12 + } + ] + + options = { document: pdf } + text_box = described_class.new(array, options) + text_box.render + expect(text_box.line_widths).to eq( + [ + 77.136, + 135.804 + ] + ) + end + + it 'handles fallback fonts' do + file = "#{Prawn::DATADIR}/fonts/gkai00mp.ttf" + pdf.font_families['Kai'] = { + normal: { file: file, font: 'Kai' } + } + array = [ + { + text: "hello你好\n再见goodbye", + font: 'Times-Roman', + size: 12 + } + ] + + options = { document: pdf, fallback_fonts: ['Kai'] } + text_box = described_class.new(array, options) + text_box.render + + expect(text_box.line_widths).to eq( + [ + 48.000, + 65.328 + ] + ) + end + end end