diff --git a/weasyprint/pdf.py b/weasyprint/pdf.py
index 8bdfbd7b..262e4196 100644
--- a/weasyprint/pdf.py
+++ b/weasyprint/pdf.py
@@ -304,6 +304,11 @@ def process_bookmarks(raw_bookmarks):
root = {'Count': 0}
bookmark_list = []
+ # At one point in the document, for each "output" level (ie. depth in the
+ # PDF outline tree), how much to add to get the source level (CSS values
+ # of bookmark-level).
+ # Eg. with
then , level_shifts == [0, 1]
+ # 1 means that has depth 3 - 1 = 2 in the output.
level_shifts = []
last_by_level = [root]
indices_by_level = [0]
@@ -314,9 +319,12 @@ def process_bookmarks(raw_bookmarks):
if level > previous_level:
level_shifts.append(level - previous_level - 1)
else:
- k = 0
- while k < previous_level - level:
- k += 1 + level_shifts.pop()
+ temp_level = level
+ while temp_level < previous_level:
+ temp_level += 1 + level_shifts.pop()
+ if temp_level > previous_level:
+ # The last pop’d value was too big
+ level_shifts.append(temp_level - previous_level - 1)
# Resolve level inconsistencies
level -= sum(level_shifts)
diff --git a/weasyprint/tests/test_pdf.py b/weasyprint/tests/test_pdf.py
index 298521b5..a9937ccd 100644
--- a/weasyprint/tests/test_pdf.py
+++ b/weasyprint/tests/test_pdf.py
@@ -84,6 +84,23 @@ def test_bookmarks():
Warning: the PDF output of this structure is not tested.
"""
+ root, bookmarks = get_bookmarks('''
+ a
#
+ b
####
+ c
###
+ d
##
+ e
#
+ ''', structure_only=True)
+ assert root == dict(Count=5, First=1, Last=5)
+ import pprint
+ pprint.pprint(bookmarks, width=150)
+ assert bookmarks == [
+ dict(Count=3, First=2, Last=4, Next=5, Parent=0, Prev=None),
+ dict(Count=0, First=None, Last=None, Next=3, Parent=1, Prev=None),
+ dict(Count=0, First=None, Last=None, Next=4, Parent=1, Prev=2),
+ dict(Count=0, First=None, Last=None, Next=None, Parent=1, Prev=3),
+ dict(Count=0, First=None, Last=None, Next=None, Parent=0, Prev=1)]
+
root, bookmarks = get_bookmarks('')
assert root == dict(Count=0)
assert bookmarks == []