Skip to content

Commit ae63b2b

Browse files
authored
Add option to treat empty paragraphs as new line (#61)
1 parent a3e8677 commit ae63b2b

File tree

3 files changed

+17
-6
lines changed

3 files changed

+17
-6
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ Beside these options handled by Prawn / prawn-table, the following values may be
7878
- `:text`
7979
- `:preprocessor`: A proc/callable that is called each time before a chunk of text is rendered.
8080
- `:margin_bottom`: Margin after each `<p>`, `<ol>`, `<ul>` or `<table>`. Defaults to about half a line.
81+
- `:treat_empty_paragraph_as_new_line`: Boolean flag to set a new line if paragraph is empty.
8182
- `:heading1-6`
8283
- `:margin_top`: Margin before a heading. Default is 0.
8384
- `:margin_bottom`: Margin after a heading. Default is 0.

lib/prawn/markup/processor/blocks.rb

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -63,11 +63,11 @@ def append_new_line
6363
def add_paragraph
6464
text = dump_text
6565
text.gsub!(/[^\n]/, '') if text.strip.empty?
66-
unless text.empty?
67-
add_bottom_margin
68-
add_formatted_text(text, text_options)
69-
put_bottom_margin(text_margin_bottom)
70-
end
66+
return if text.empty? && !treat_empty_paragraph_as_new_line?
67+
68+
add_bottom_margin
69+
add_formatted_text(text.empty? ? "\n" : text, text_options)
70+
put_bottom_margin(text_margin_bottom)
7171
end
7272

7373
def add_current_text(options = text_options)
@@ -151,6 +151,10 @@ def default_text_options
151151
inline_format: true
152152
}
153153
end
154+
155+
def treat_empty_paragraph_as_new_line?
156+
text_options[:treat_empty_paragraph_as_new_line] || false
157+
end
154158
end
155159
end
156160
end

spec/prawn/markup/processor/blocks_spec.rb

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,8 @@
8484
leading: leading,
8585
size: font_size,
8686
margin_bottom: 0,
87-
preprocessor: ->(text) { text.upcase }
87+
preprocessor: ->(text) { text.upcase },
88+
treat_empty_paragraph_as_new_line: true
8889
}
8990
}
9091
end
@@ -107,5 +108,10 @@
107108
expect(top_positions).to eq([top, top - line].map(&:round))
108109
end
109110

111+
it "treats empty paragraphs as new line if configured" do
112+
processor.parse("<p>hello</p><p></p><p>world</p>")
113+
expect(text.strings).to eq(%w[HELLO WORLD])
114+
expect(top_positions).to eq([top, top - 2 * line].map(&:round))
115+
end
110116
end
111117
end

0 commit comments

Comments
 (0)