From 427a0f90f23282a4bcd1f71f7c7a54060d54187d Mon Sep 17 00:00:00 2001
From: Dan Allen <dan.j.allen@gmail.com>
Date: Tue, 25 Aug 2020 01:10:12 -0600
Subject: [PATCH] read padding from correct box when creating new page

resolves #1121
---
 CHANGELOG.md          |  8 ++++++++
 lib/prawn/document.rb | 12 +++++++-----
 2 files changed, 15 insertions(+), 5 deletions(-)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index bd9a78586..d8f7ba3f2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,13 @@
 ## PrawnPDF master branch
 
+## Unreleased
+
+### Apply correct margin box when creating or switching pages
+
+When creating a new page or returning to a page previously created, compute the margin box correctly.
+
+(Dan Allen, [#1122](https://github.com/prawnpdf/prawn/pull/1022))
+
 ## PrawnPDF 2.3.0
 
 ### Added OpenType Font Support
diff --git a/lib/prawn/document.rb b/lib/prawn/document.rb
index eb2247550..88b1165b6 100644
--- a/lib/prawn/document.rb
+++ b/lib/prawn/document.rb
@@ -720,15 +720,17 @@ def generate_margin_box
           (page.margins[:top] + page.margins[:bottom])
       )
 
-      # This check maintains indentation settings across page breaks
+      # update bounding box if not flowing from the previous page
+      unless @bounding_box&.parent
+        old_margin_box = @bounding_box
+        @bounding_box = @margin_box
+      end
+
+      # maintains indentation settings across page breaks
       if old_margin_box
         @margin_box.add_left_padding(old_margin_box.total_left_padding)
         @margin_box.add_right_padding(old_margin_box.total_right_padding)
       end
-
-      # we must update bounding box if not flowing from the previous page
-      #
-      @bounding_box = @margin_box unless @bounding_box&.parent
     end
 
     def apply_margin_options(options)