Skip to content

Commit

Permalink
Fix character_spacing effect on text width calculation.
Browse files Browse the repository at this point in the history
The value of character_spacing should be added to the length of the
original string `(string.length - 1)` times instead of `string.length`
times, since character_spacing only increases the space between
characters.

This fixes text positioning when using character_spacing != 0 and
:center or :right text alignment option.
  • Loading branch information
mtyaka authored and pointlessone committed May 13, 2019
1 parent b3f04e1 commit c61c5d4
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 10 deletions.
9 changes: 6 additions & 3 deletions lib/prawn/font_metric_cache.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,12 @@ def width_of(string, options)

length = @cache[key]

length +
(@document.character_spacing *
@document.font.character_count(encoded_string))
character_count = @document.font.character_count(encoded_string)
if character_count.positive?
length += @document.character_spacing * (character_count - 1)
end

length
end
end
end
2 changes: 1 addition & 1 deletion spec/prawn/font_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
it 'takes character spacing into account' do
original_width = pdf.width_of('hello world')
pdf.character_spacing(7) do
expect(pdf.width_of('hello world')).to eq(original_width + 11 * 7)
expect(pdf.width_of('hello world')).to eq(original_width + 10 * 7)
end
end

Expand Down
4 changes: 2 additions & 2 deletions spec/prawn/text_spacing_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@
end

pdf.character_spacing(10) do
# the new width should include seven 10-pt character spaces.
expect(pdf.width_of(str)).to be_within(0.001).of(raw_width + (10 * 7))
# the new width should include six 10-pt character spaces.
expect(pdf.width_of(str)).to be_within(0.001).of(raw_width + (10 * 6))
end
end
end
Expand Down
8 changes: 4 additions & 4 deletions spec/prawn_manual_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
MANUAL_HASH =
case RUBY_ENGINE
when 'ruby'
'cfc8c0335d96952ec9e06e8509ba6e80af20e4ff5e8a75143f1e78ca36ddb56f'\
'f861dd285c65b5b823845ae2b4d7a4f9d538c5fbf376f50c89bb87b7dd3c6b51'
'0b6348280c2bd694d32e687bbe8e04d1659f09624ab9787186a933f4e1274382'\
'a7d8eda06dd168da955a39d34ebafbf5a1c20a62f2a2a34281e4732beaba47a0'
when 'jruby'
'30b10f71981d3dfbc087f18fe7aa98e67aaeaf5c0d97e30896b2edbda8de39e1'\
'1031f13905ec093cbc1afe4e6e00ef22d9dcf8a27b8febf76f02120c2ebf187a'
'1df4c83bc2dadb6368b755dfbed87f2730243023c8e7ceb8dc283eb9a485bf89'\
'644baf93e6e2f016f7c990a47dd001080904f0c60066025ef2204769b906d173'
end

RSpec.describe Prawn do
Expand Down

0 comments on commit c61c5d4

Please sign in to comment.