xhtml2pdf 0.2.26__tar.gz → 0.2.27__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. {xhtml2pdf-0.2.26/xhtml2pdf.egg-info → xhtml2pdf-0.2.27}/PKG-INFO +1 -1
  2. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_document.py +33 -0
  3. xhtml2pdf-0.2.27/tests/test_generated_content.py +211 -0
  4. xhtml2pdf-0.2.27/tests/test_insert_pdf.py +160 -0
  5. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_reportlab_api.py +11 -0
  6. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_special_css.py +66 -0
  7. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_tables.py +71 -0
  8. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_tags.py +77 -1
  9. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/__init__.py +1 -1
  10. xhtml2pdf-0.2.27/xhtml2pdf/builders/inserts.py +156 -0
  11. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/builders/watermarks.py +13 -1
  12. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/context.py +11 -0
  13. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/default.py +1 -0
  14. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/document.py +5 -0
  15. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/parser.py +90 -5
  16. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/properties.py +29 -0
  17. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/reportlab_paragraph.py +108 -0
  18. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/tables.py +16 -6
  19. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/tags.py +29 -35
  20. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/util.py +16 -0
  21. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/w3c/css.py +73 -5
  22. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/w3c/cssDOMElementInterface.py +4 -0
  23. xhtml2pdf-0.2.27/xhtml2pdf/w3c/generated_content.py +284 -0
  24. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/xhtml2pdf_reportlab.py +97 -14
  25. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27/xhtml2pdf.egg-info}/PKG-INFO +1 -1
  26. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf.egg-info/SOURCES.txt +5 -1
  27. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/LICENSE.txt +0 -0
  28. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/MANIFEST.in +0 -0
  29. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/README.rst +0 -0
  30. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/pyproject.toml +0 -0
  31. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/setup.cfg +0 -0
  32. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_asian_font_support.py +0 -0
  33. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_bidi.py +0 -0
  34. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_block_box.py +0 -0
  35. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_block_margins.py +0 -0
  36. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_block_width.py +0 -0
  37. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_cli.py +0 -0
  38. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_css_media_rule.py +0 -0
  39. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_css_parser.py +0 -0
  40. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_css_variables.py +0 -0
  41. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_files.py +0 -0
  42. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_flex.py +0 -0
  43. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_flex_flowable.py +0 -0
  44. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_flex_layout.py +0 -0
  45. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_font_isolation.py +0 -0
  46. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_fonts.py +0 -0
  47. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_frame_align.py +0 -0
  48. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_frame_pages.py +0 -0
  49. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_http.py +0 -0
  50. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_inline_block.py +0 -0
  51. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_inline_box.py +0 -0
  52. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_optional_dependencies.py +0 -0
  53. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_page_numbering.py +0 -0
  54. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_page_padding.py +0 -0
  55. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_paragraph.py +0 -0
  56. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_paragraph_height.py +0 -0
  57. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_parser.py +0 -0
  58. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_pdf.py +0 -0
  59. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_position.py +0 -0
  60. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_reportlab.py +0 -0
  61. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_reportlab_paragraph.py +0 -0
  62. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_resource_policy.py +0 -0
  63. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_right_to_left_font_support.py +0 -0
  64. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_security_limits.py +0 -0
  65. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_selectors.py +0 -0
  66. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_signatures.py +0 -0
  67. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_table_border_radius.py +0 -0
  68. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_table_css.py +0 -0
  69. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_update_face_name.py +0 -0
  70. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_utils.py +0 -0
  71. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_watermarks.py +0 -0
  72. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_word_breaking.py +0 -0
  73. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/tests/test_wsgi.py +0 -0
  74. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/__main__.py +0 -0
  75. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/_bidi_data.py +0 -0
  76. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/bidi.py +0 -0
  77. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/builders/__init__.py +0 -0
  78. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/builders/block.py +0 -0
  79. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/builders/flex.py +0 -0
  80. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/builders/flex_layout.py +0 -0
  81. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/builders/position.py +0 -0
  82. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/builders/signs.py +0 -0
  83. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/charts.py +0 -0
  84. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/config/__init__.py +0 -0
  85. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/config/httpconfig.py +0 -0
  86. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/config/resources.py +0 -0
  87. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/files.py +0 -0
  88. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/paragraph.py +0 -0
  89. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/pdf.py +0 -0
  90. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/pisa.py +0 -0
  91. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/w3c/__init__.py +0 -0
  92. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/w3c/cssParser.py +0 -0
  93. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/w3c/cssSpecial.py +0 -0
  94. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/w3c/css_variables.py +0 -0
  95. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf/wsgi.py +0 -0
  96. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf.egg-info/dependency_links.txt +0 -0
  97. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf.egg-info/entry_points.txt +0 -0
  98. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf.egg-info/requires.txt +0 -0
  99. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.27}/xhtml2pdf.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: xhtml2pdf
3
- Version: 0.2.26
3
+ Version: 0.2.27
4
4
  Summary: PDF generator using HTML and CSS
5
5
  Author-email: Dirk Holtwick <dirk.holtwick@gmail.com>
6
6
  Maintainer-email: Luis Zarate <luisza14@gmail.com>, Timo Brembeck <opensource@timo.brembeck.email>
@@ -468,6 +468,39 @@ class EncryptAndSignTest(TestCase):
468
468
 
469
469
  self.assertIn("cannot be merged", str(raised.exception))
470
470
 
471
+ def test_a_background_drops_an_owner_password_and_says_so(self) -> None:
472
+ """
473
+ With an owner password only the document can be read back, and the
474
+ background is merged in; but it is written again unencrypted.
475
+ """
476
+ from reportlab.lib.pdfencrypt import StandardEncryption
477
+
478
+ html = (
479
+ "<html><head><style>@page { background-image:"
480
+ ' url("tests/samples/img/tree.jpg"); }</style></head>'
481
+ "<body><p>x</p></body></html>"
482
+ )
483
+ dest = io.BytesIO()
484
+ encrypt = StandardEncryption("", ownerPassword="owner", canPrint=0)
485
+
486
+ with self.assertLogs("xhtml2pdf", level="WARNING") as logs:
487
+ pisaDocument(io.StringIO(html), dest, encrypt=encrypt, path=".")
488
+
489
+ self.assertFalse(PdfReader(io.BytesIO(dest.getvalue())).is_encrypted)
490
+ self.assertTrue(
491
+ any("WITHOUT encryption" in line for line in logs.output), logs.output
492
+ )
493
+
494
+ def test_no_warning_without_a_background(self) -> None:
495
+ from reportlab.lib.pdfencrypt import StandardEncryption
496
+
497
+ dest = io.BytesIO()
498
+ encrypt = StandardEncryption("", ownerPassword="owner")
499
+ with self.assertNoLogs("xhtml2pdf", level="WARNING"):
500
+ pisaDocument(io.StringIO(self.HTML), dest, encrypt=encrypt)
501
+
502
+ self.assertTrue(PdfReader(io.BytesIO(dest.getvalue())).is_encrypted)
503
+
471
504
 
472
505
  class ArgumentsThatDoSomethingTest(TestCase):
473
506
  """
@@ -0,0 +1,211 @@
1
+ """CSS counters and ::before / ::after content (#112)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ from unittest import TestCase
7
+
8
+ from pypdf import PdfReader
9
+
10
+ from xhtml2pdf import pisa
11
+ from xhtml2pdf.w3c.css import CSSString, CSSTerminalFunction
12
+ from xhtml2pdf.w3c.generated_content import (
13
+ AttrItem,
14
+ CounterItem,
15
+ Counters,
16
+ format_counter,
17
+ parse_content,
18
+ parse_counter_list,
19
+ )
20
+
21
+ HEADINGS = """
22
+ body { counter-reset: h2 }
23
+ h2 { counter-increment: h2; counter-reset: h3 }
24
+ h3 { counter-increment: h3 }
25
+ h2::before { content: counter(h2) ". " }
26
+ h3::before { content: counter(h2) "." counter(h3) " " }
27
+ """
28
+
29
+
30
+ def render(body: str, css: str = HEADINGS) -> PdfReader:
31
+ html = f"<html><head><style>{css}</style></head><body>{body}</body></html>"
32
+ output = io.BytesIO()
33
+ pisa.CreatePDF(html, dest=output, raise_exception=True)
34
+ return PdfReader(output)
35
+
36
+
37
+ def lines(body: str, css: str = HEADINGS) -> list[str]:
38
+ text = "".join(page.extract_text() for page in render(body, css).pages)
39
+ return [line.strip() for line in text.split("\n") if line.strip()]
40
+
41
+
42
+ def outline_titles(items) -> list[str]:
43
+ titles: list[str] = []
44
+ for item in items:
45
+ if isinstance(item, list):
46
+ titles += outline_titles(item)
47
+ else:
48
+ titles.append(item["/Title"])
49
+ return titles
50
+
51
+
52
+ class NumberedHeadingsTest(TestCase):
53
+ BODY = "<h2>Intro</h2><h3>Scope</h3><h3>Terms</h3><h2>Design</h2><h3>Parts</h3>"
54
+
55
+ def test_the_headings_are_numbered(self) -> None:
56
+ self.assertEqual(
57
+ ["1. Intro", "1.1 Scope", "1.2 Terms", "2. Design", "2.1 Parts"],
58
+ lines(self.BODY),
59
+ )
60
+
61
+ def test_the_table_of_contents_shows_the_numbers(self) -> None:
62
+ text = lines("<pdf:toc/>" + self.BODY)
63
+
64
+ # Once in the table of contents and once as the heading itself.
65
+ for heading in ("1. Intro", "1.1 Scope", "2.1 Parts"):
66
+ self.assertEqual(2, text.count(heading), (heading, text))
67
+
68
+ def test_the_outline_shows_the_numbers(self) -> None:
69
+ titles = outline_titles(render(self.BODY).outline)
70
+
71
+ self.assertIn("1.2 Terms", titles)
72
+ self.assertIn("2. Design", titles)
73
+
74
+ def test_a_hidden_heading_is_not_counted(self) -> None:
75
+ body = '<h2>A</h2><h2 style="display: none">Hidden</h2><h2>B</h2>'
76
+
77
+ self.assertEqual(["1. A", "2. B"], lines(body))
78
+
79
+ def test_without_a_before_rule_nothing_changes(self) -> None:
80
+ self.assertEqual(["Intro"], lines("<h2>Intro</h2>", css="h2 { color: red }"))
81
+
82
+
83
+ class ContentTest(TestCase):
84
+ def test_after_and_attr(self) -> None:
85
+ css = 'p::after { content: " [" attr(data-ref) "]" }'
86
+
87
+ self.assertEqual(["Text [r1]"], lines('<p data-ref="r1">Text</p>', css))
88
+
89
+ def test_a_counter_style(self) -> None:
90
+ css = (
91
+ "ol { counter-reset: item; list-style: none }"
92
+ " li { counter-increment: item }"
93
+ ' li::before { content: counter(item, upper-roman) ") " }'
94
+ )
95
+
96
+ self.assertEqual(
97
+ ["I) a", "II) b", "III) c"],
98
+ lines("<ol><li>a</li><li>b</li><li>c</li></ol>", css),
99
+ )
100
+
101
+ def test_counters_joins_the_nested_instances(self) -> None:
102
+ css = (
103
+ "ol { counter-reset: item; list-style: none } li { counter-increment: item }"
104
+ ' li::before { content: counters(item, ".") " " }'
105
+ )
106
+ body = "<ol><li>a<ol><li>b</li><li>c</li></ol></li><li>d</li></ol>"
107
+
108
+ self.assertEqual(["1 a", "1.1 b", "1.2 c", "2 d"], lines(body, css))
109
+
110
+ def test_the_css2_single_colon_form(self) -> None:
111
+ css = 'h2:before { content: "> " }'
112
+
113
+ self.assertEqual(["> Intro"], lines("<h2>Intro</h2>", css))
114
+
115
+ def test_a_before_rule_does_not_style_the_element_itself(self) -> None:
116
+ css = 'h2::before { content: "x "; color: red }'
117
+ reader = render("<h2>Intro</h2>", css)
118
+ content = reader.pages[0].get_contents().get_data().decode("latin-1")
119
+
120
+ # The number is red, the heading after it is not.
121
+ self.assertIn("1 0 0 rg", content)
122
+ self.assertIn("0 0 0 rg", content)
123
+
124
+ def test_the_more_specific_rule_wins(self) -> None:
125
+ css = 'h2::before { content: "a " } h2.x::before { content: "b " }'
126
+
127
+ self.assertEqual(["b Intro"], lines('<h2 class="x">Intro</h2>', css))
128
+
129
+ def test_none_and_an_empty_string_generate_nothing(self) -> None:
130
+ for content in ("none", '""'):
131
+ with self.subTest(content=content):
132
+ css = f"h2::before {{ content: {content} }}"
133
+ self.assertEqual(["Intro"], lines("<h2>Intro</h2>", css))
134
+
135
+
136
+ class FormatCounterTest(TestCase):
137
+ def test_styles(self) -> None:
138
+ cases = {
139
+ "decimal": "4",
140
+ "decimal-leading-zero": "04",
141
+ "lower-roman": "iv",
142
+ "upper-roman": "IV",
143
+ "lower-alpha": "d",
144
+ "upper-latin": "D",
145
+ "lower-greek": "δ",
146
+ "none": "",
147
+ "unknown": "4",
148
+ }
149
+ for style, expected in cases.items():
150
+ with self.subTest(style=style):
151
+ self.assertEqual(expected, format_counter(4, style))
152
+
153
+ def test_letters_go_on_past_z(self) -> None:
154
+ self.assertEqual(
155
+ ["z", "aa", "ab"], [format_counter(n, "lower-alpha") for n in (26, 27, 28)]
156
+ )
157
+
158
+ def test_out_of_range_falls_back_to_decimal(self) -> None:
159
+ self.assertEqual("0", format_counter(0, "upper-roman"))
160
+ self.assertEqual("-1", format_counter(-1, "lower-alpha"))
161
+
162
+
163
+ class ParseTest(TestCase):
164
+ def test_content_items(self) -> None:
165
+ value = [
166
+ CSSTerminalFunction("counter", ["h2", "upper-roman"]),
167
+ CSSString(". "),
168
+ CSSTerminalFunction("counters", ["item", CSSString(".")]),
169
+ CSSTerminalFunction("attr", ["title"]),
170
+ ]
171
+
172
+ self.assertEqual(
173
+ [
174
+ CounterItem("h2", "upper-roman"),
175
+ ". ",
176
+ CounterItem("item", "decimal", "."),
177
+ AttrItem("title"),
178
+ ],
179
+ parse_content(value),
180
+ )
181
+
182
+ def test_a_css_escape_in_a_string(self) -> None:
183
+ self.assertEqual(["—"], parse_content(CSSString("\\2014")))
184
+
185
+ def test_none_is_nothing_and_the_string_none_is_text(self) -> None:
186
+ self.assertIsNone(parse_content("none"))
187
+ self.assertEqual(["none"], parse_content(CSSString("none")))
188
+
189
+ def test_counter_lists(self) -> None:
190
+ self.assertEqual(
191
+ [("h2", 0), ("h3", 5)], parse_counter_list(["h2", "h3", "5"], 0)
192
+ )
193
+ self.assertEqual([], parse_counter_list("none", 1))
194
+
195
+
196
+ class CountersTest(TestCase):
197
+ def test_a_sibling_reset_takes_over_and_leaving_the_parent_ends_it(self) -> None:
198
+ from xml.dom.minidom import parseString
199
+
200
+ root = parseString("<r><a/><b/></r>").documentElement
201
+ assert root is not None
202
+ a, b = root.childNodes
203
+ assert a.parentNode is not None and b.parentNode is not None
204
+ counters = Counters()
205
+ counters.reset(root, "n", 1)
206
+ counters.reset(a.parentNode, "n", 5)
207
+ counters.increment(b.parentNode, "n", 1)
208
+
209
+ self.assertEqual([6], counters.values("n"))
210
+ counters.leave(root)
211
+ self.assertEqual([], counters.values("n"))
@@ -0,0 +1,160 @@
1
+ """<pdf:insertpdf>: the pages of another PDF inside the document (#551)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import io
7
+ import tempfile
8
+ from pathlib import Path
9
+ from unittest import TestCase
10
+
11
+ from pypdf import PdfReader
12
+ from reportlab.lib.pagesizes import A5, landscape
13
+ from reportlab.pdfgen.canvas import Canvas
14
+
15
+ from xhtml2pdf import pisa
16
+ from xhtml2pdf.builders.inserts import parse_pages
17
+ from xhtml2pdf.config.resources import ResourceAccessPolicy
18
+
19
+
20
+ def source_pdf(path: Path) -> None:
21
+ """Three pages saying "Source page N", the third one A5 landscape."""
22
+ canvas = Canvas(str(path))
23
+ for number in range(1, 4):
24
+ if number == 3:
25
+ canvas.setPageSize(landscape(A5))
26
+ canvas.drawString(72, 300, f"Source page {number}")
27
+ canvas.showPage()
28
+ canvas.save()
29
+
30
+
31
+ class InsertPdfTest(TestCase):
32
+ directory: tempfile.TemporaryDirectory
33
+ base: Path
34
+ policy: ResourceAccessPolicy
35
+
36
+ @classmethod
37
+ def setUpClass(cls) -> None:
38
+ cls.directory = tempfile.TemporaryDirectory()
39
+ cls.base = Path(cls.directory.name)
40
+ source_pdf(cls.base / "source.pdf")
41
+ cls.policy = ResourceAccessPolicy(base_dir=cls.base)
42
+
43
+ @classmethod
44
+ def tearDownClass(cls) -> None:
45
+ cls.directory.cleanup()
46
+
47
+ def render(self, body: str, head: str = "", policy=None) -> PdfReader:
48
+ html = f"<html><head>{head}</head><body>{body}</body></html>"
49
+ output = io.BytesIO()
50
+ pisa.CreatePDF(
51
+ html,
52
+ dest=output,
53
+ path=str(self.base / "doc.html"),
54
+ resource_policy=policy or self.policy,
55
+ raise_exception=True,
56
+ )
57
+ return PdfReader(output)
58
+
59
+ @staticmethod
60
+ def texts(reader: PdfReader) -> list[str]:
61
+ return [page.extract_text().strip() for page in reader.pages]
62
+
63
+ def test_the_pages_go_where_the_tag_is(self) -> None:
64
+ reader = self.render(
65
+ '<p>before</p><pdf:insertpdf src="source.pdf"/><p>after</p>'
66
+ )
67
+
68
+ self.assertEqual(
69
+ ["before", "Source page 1", "Source page 2", "Source page 3", "after"],
70
+ self.texts(reader),
71
+ )
72
+
73
+ def test_pages_picks_and_orders_them(self) -> None:
74
+ reader = self.render('<p>a</p><pdf:insertpdf src="source.pdf" pages="3,1"/>')
75
+
76
+ self.assertEqual(["a", "Source page 3", "Source page 1"], self.texts(reader))
77
+
78
+ def test_no_empty_page_at_either_end(self) -> None:
79
+ reader = self.render('<pdf:insertpdf src="source.pdf" pages="2"/>')
80
+
81
+ self.assertEqual(["Source page 2"], self.texts(reader))
82
+
83
+ def test_inserted_pages_are_numbered_and_counted(self) -> None:
84
+ reader = self.render(
85
+ '<p>first of <pdf:pagecount/></p><pdf:insertpdf src="source.pdf"/>'
86
+ "<p>page <pdf:pagenumber/></p>"
87
+ )
88
+
89
+ self.assertEqual("first of 5", self.texts(reader)[0])
90
+ self.assertEqual("page 5", self.texts(reader)[-1])
91
+
92
+ def test_a_page_keeps_its_own_size(self) -> None:
93
+ reader = self.render('<p>a</p><pdf:insertpdf src="source.pdf" pages="3"/>')
94
+ box = reader.pages[1].mediabox
95
+
96
+ self.assertEqual(
97
+ [round(v) for v in landscape(A5)], [round(box.width), round(box.height)]
98
+ )
99
+
100
+ def test_nothing_of_the_document_is_drawn_on_it(self) -> None:
101
+ head = (
102
+ "<style>@page { background-image: url(source.pdf);"
103
+ " @frame footer { -pdf-frame-content: foot; bottom: 1cm;"
104
+ " height: 1cm; left: 2cm; width: 10cm } }</style>"
105
+ )
106
+ reader = self.render(
107
+ '<div id="foot">footer</div><p>a</p>'
108
+ '<pdf:insertpdf src="source.pdf" pages="2"/>',
109
+ head,
110
+ )
111
+
112
+ self.assertIn("footer", self.texts(reader)[0])
113
+ self.assertEqual("Source page 2", self.texts(reader)[1])
114
+
115
+ def test_a_missing_file_inserts_nothing(self) -> None:
116
+ with self.assertLogs("xhtml2pdf", level="WARNING"):
117
+ reader = self.render('<p>a</p><pdf:insertpdf src="missing.pdf"/>')
118
+
119
+ self.assertEqual(["a"], self.texts(reader))
120
+
121
+ def test_an_inline_pdf_follows_the_pdf_background_policy(self) -> None:
122
+ data = base64.b64encode((self.base / "source.pdf").read_bytes()).decode()
123
+ body = f'<p>a</p><pdf:insertpdf src="data:application/pdf;base64,{data}"/>'
124
+ strict = ResourceAccessPolicy(
125
+ base_dir=self.base, allow_remote_pdf_backgrounds=False
126
+ )
127
+
128
+ self.assertEqual(4, len(self.render(body).pages))
129
+ with self.assertLogs("xhtml2pdf", level="WARNING") as logs:
130
+ self.assertEqual(1, len(self.render(body, policy=strict).pages))
131
+ self.assertTrue(any("PDF to insert" in line for line in logs.output))
132
+
133
+ def test_it_cannot_be_used_with_encryption(self) -> None:
134
+ """An owner password alone would be silently lost on the way."""
135
+ from reportlab.lib.pdfencrypt import StandardEncryption
136
+
137
+ for encrypt in ("user", StandardEncryption("", ownerPassword="owner")):
138
+ with self.subTest(encrypt=encrypt), self.assertRaises(ValueError):
139
+ pisa.CreatePDF(
140
+ '<p>a</p><pdf:insertpdf src="source.pdf"/>',
141
+ dest=io.BytesIO(),
142
+ path=str(self.base / "doc.html"),
143
+ resource_policy=self.policy,
144
+ encrypt=encrypt,
145
+ )
146
+
147
+
148
+ class ParsePagesTest(TestCase):
149
+ def test_every_page_by_default(self) -> None:
150
+ self.assertEqual([0, 1, 2], parse_pages("", 3))
151
+
152
+ def test_pages_and_ranges(self) -> None:
153
+ self.assertEqual([0, 2, 3, 4], parse_pages("1, 3-5", 5))
154
+
155
+ def test_open_ranges(self) -> None:
156
+ self.assertEqual([0, 1, 3, 4], parse_pages("-2,4-", 5))
157
+
158
+ def test_a_page_it_does_not_have_is_left_out(self) -> None:
159
+ with self.assertLogs("xhtml2pdf", level="WARNING"):
160
+ self.assertEqual([1], parse_pages("2, 7, x", 3))
@@ -74,6 +74,7 @@ REQUIRED_SYMBOLS: dict[str, tuple[str, ...]] = {
74
74
  "reportlab.pdfbase": ("pdfform", "pdfmetrics"),
75
75
  "reportlab.pdfgen.canvas": ("Canvas", "FILL_EVEN_ODD"),
76
76
  "reportlab.platypus.doctemplate": (
77
+ "ActionFlowable",
77
78
  "BaseDocTemplate",
78
79
  "FrameBreak",
79
80
  "IndexingFlowable",
@@ -88,6 +89,7 @@ REQUIRED_SYMBOLS: dict[str, tuple[str, ...]] = {
88
89
  "KeepInFrame",
89
90
  "KeepTogether",
90
91
  "PageBreak",
92
+ "PageBreakIfNotEmpty",
91
93
  "ParagraphAndImage",
92
94
  "Spacer",
93
95
  ),
@@ -528,6 +530,15 @@ class DocTemplateStateTest(TestCase):
528
530
 
529
531
  self.assertEqual("B", record[0]["template"])
530
532
 
533
+ def test_a_page_break_if_not_empty_on_a_fresh_page_is_dropped(self) -> None:
534
+ """<pdf:insertpdf> starts with one; at the top of a page it does nothing."""
535
+ from reportlab.platypus.flowables import PageBreakIfNotEmpty
536
+
537
+ record: list[dict] = []
538
+ doc = _build([PageBreakIfNotEmpty(), _Probe.make(record)])
539
+
540
+ self.assertEqual(1, doc.page)
541
+
531
542
  def test_PmlBaseDoc_cycles_left_and_right_templates(self) -> None:
532
543
  """
533
544
  The whole contract at once: PmlBaseDoc's copy of
@@ -705,6 +705,72 @@ class WhiteSpaceTest(TestCase):
705
705
  self.assertEqual("two spaces and a newline", self._text("nowrap").strip())
706
706
 
707
707
 
708
+ class TextOverflowTest(TestCase):
709
+ """
710
+ A line wider than a block whose overflow is not visible is cut at the
711
+ block's edge, and text-overflow: ellipsis ends it with one (#698).
712
+ """
713
+
714
+ LONG = "The quick brown fox jumps over the lazy dog and keeps on running"
715
+ WIDTH = 113.39 # 4cm in points
716
+
717
+ @classmethod
718
+ def _lines(cls, style: str, tag: str = "div", content: str = LONG) -> list[str]:
719
+ font = "font-family: Helvetica; font-size: 10pt"
720
+ block = f'<{tag} style="width: 4cm; {font}; {style}">{content}</{tag}>'
721
+ if tag == "td":
722
+ block = f'<table style="width: 12cm"><tr>{block}<td>next</td></tr></table>'
723
+ out = io.BytesIO()
724
+ pisa.pisaDocument(io.StringIO(f"<html><body>{block}</body></html>"), out)
725
+ text = PdfReader(out).pages[0].extract_text()
726
+ return [line for line in text.replace("\xa0", " ").split("\n") if line]
727
+
728
+ def assertFits(self, line: str) -> None:
729
+ from reportlab.pdfbase.pdfmetrics import stringWidth
730
+
731
+ self.assertLessEqual(stringWidth(line, "Helvetica", 10), self.WIDTH)
732
+
733
+ def test_ellipsis_ends_the_cut_line_with_one(self) -> None:
734
+ nowrap = "white-space: nowrap; overflow: hidden; text-overflow: ellipsis"
735
+ [line] = self._lines(nowrap)
736
+
737
+ self.assertTrue(line.endswith("\u2026"), line)
738
+ self.assertTrue(self.LONG.startswith(line[:-1]), line)
739
+ self.assertFits(line)
740
+
741
+ def test_clip_cuts_it_without_a_mark(self) -> None:
742
+ [line] = self._lines("white-space: nowrap; overflow: hidden")
743
+
744
+ self.assertTrue(self.LONG.startswith(line), line)
745
+ self.assertLess(len(line), len(self.LONG))
746
+ self.assertFits(line)
747
+
748
+ def test_a_table_cell_is_cut_at_its_width(self) -> None:
749
+ nowrap = "white-space: nowrap; overflow: hidden; text-overflow: ellipsis"
750
+ line, after = self._lines(nowrap, tag="td")
751
+
752
+ self.assertTrue(line.endswith("\u2026"), line)
753
+ self.assertFits(line)
754
+ self.assertEqual("next", after)
755
+
756
+ def test_the_mark_comes_where_the_line_is_cut_across_elements(self) -> None:
757
+ nowrap = "white-space: nowrap; overflow: hidden; text-overflow: ellipsis"
758
+ [line] = self._lines(nowrap, content=f"<b>{self.LONG}</b> and more")
759
+
760
+ self.assertTrue(line.endswith("\u2026"), line)
761
+ self.assertNotIn("more", line)
762
+
763
+ def test_visible_overflow_leaves_the_line_whole(self) -> None:
764
+ [line] = self._lines("white-space: nowrap; text-overflow: ellipsis")
765
+
766
+ self.assertEqual(self.LONG, line)
767
+
768
+ def test_lines_that_fit_are_left_alone(self) -> None:
769
+ lines = self._lines("overflow: hidden; text-overflow: ellipsis")
770
+
771
+ self.assertEqual(self.LONG, " ".join(lines))
772
+
773
+
708
774
  class BackgroundShorthandTest(TestCase):
709
775
  """
710
776
  Every part of the shorthand but one used to be thrown away: the first was
@@ -1205,6 +1205,77 @@ class RowCutAcrossPagesTestCase(TestCase):
1205
1205
  self.assertEqual(0, table.splitInRow)
1206
1206
 
1207
1207
 
1208
+ class NestedTableAcrossPagesTestCase(TestCase):
1209
+ """
1210
+ A table in a cell goes on from page to page in print of its own size,
1211
+ starting where the row holding it starts, as in a browser (#402).
1212
+ """
1213
+
1214
+ PAGE = RowCutAcrossPagesTestCase.PAGE
1215
+
1216
+ @staticmethod
1217
+ def rows(count: int) -> str:
1218
+ return "".join(f"<tr><td>row{i:03d}</td></tr>" for i in range(count))
1219
+
1220
+ def html(self, count: int, cell_style: str = "") -> str:
1221
+ return (
1222
+ f"<html><head>{self.PAGE}</head><body><table>"
1223
+ "<tr><td>outer</td></tr>"
1224
+ f'<tr><td style="{cell_style}"><table>{self.rows(count)}</table></td></tr>'
1225
+ "</table></body></html>"
1226
+ )
1227
+
1228
+ @staticmethod
1229
+ def pages(html: str) -> list[str]:
1230
+ from io import BytesIO
1231
+
1232
+ from pypdf import PdfReader
1233
+
1234
+ from xhtml2pdf import pisa
1235
+
1236
+ output = BytesIO()
1237
+ pisa.CreatePDF(html, dest=output, raise_exception=True)
1238
+ return [page.extract_text() for page in PdfReader(output).pages]
1239
+
1240
+ def test_the_nested_table_starts_under_the_row_before_it(self) -> None:
1241
+ pages = self.pages(self.html(40))
1242
+
1243
+ self.assertIn("outer", pages[0])
1244
+ self.assertIn("row000", pages[0])
1245
+
1246
+ def test_every_row_is_there_in_order(self) -> None:
1247
+ text = "".join(self.pages(self.html(40)))
1248
+ found = [text.index(f"row{i:03d}") for i in range(40)]
1249
+
1250
+ self.assertEqual(sorted(found), found)
1251
+
1252
+ @staticmethod
1253
+ def row_heights(html: str) -> set[float]:
1254
+ """The row heights of the nested table's parts, the outer one left out."""
1255
+ return {
1256
+ round(height, 2)
1257
+ for part in drawn_tables(html)
1258
+ if len(part.rows) > 2
1259
+ for height in part.rows
1260
+ }
1261
+
1262
+ def test_its_rows_keep_their_height(self) -> None:
1263
+ unshrunk = self.row_heights(self.html(5))
1264
+
1265
+ self.assertEqual(1, len(unshrunk))
1266
+ self.assertEqual(unshrunk, self.row_heights(self.html(40)))
1267
+ self.assertEqual(3, len(self.pages(self.html(40))))
1268
+
1269
+ def test_a_short_nested_table_is_not_cut(self) -> None:
1270
+ self.assertEqual(1, len(self.pages(self.html(5))))
1271
+
1272
+ def test_an_explicit_shrink_still_shrinks_it_onto_one_page(self) -> None:
1273
+ pages = self.pages(self.html(40, "-pdf-keep-in-frame-mode: shrink"))
1274
+
1275
+ self.assertEqual(2, len(pages))
1276
+ self.assertNotIn("row000", pages[0])
1277
+
1278
+
1208
1279
  class CellHeightAttributeTestCase(TestCase):
1209
1280
  """
1210
1281
  <td height="..."> sets the row's height, as style="height: ..." does.