xhtml2pdf 0.2.26__tar.gz → 0.2.28__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 (105) hide show
  1. {xhtml2pdf-0.2.26/xhtml2pdf.egg-info → xhtml2pdf-0.2.28}/PKG-INFO +6 -1
  2. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/pyproject.toml +15 -1
  3. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_asian_font_support.py +40 -0
  4. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_cli.py +29 -1
  5. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_document.py +33 -0
  6. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_fonts.py +26 -0
  7. xhtml2pdf-0.2.28/tests/test_generated_content.py +211 -0
  8. xhtml2pdf-0.2.28/tests/test_insert_pdf.py +160 -0
  9. xhtml2pdf-0.2.28/tests/test_opentype.py +226 -0
  10. xhtml2pdf-0.2.28/tests/test_print.py +437 -0
  11. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_reportlab_api.py +46 -2
  12. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_security_limits.py +14 -10
  13. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_special_css.py +66 -0
  14. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_tables.py +71 -0
  15. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_tags.py +96 -1
  16. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_watermarks.py +1 -1
  17. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/__init__.py +1 -1
  18. xhtml2pdf-0.2.28/xhtml2pdf/builders/inserts.py +156 -0
  19. xhtml2pdf-0.2.28/xhtml2pdf/builders/pdfx.py +384 -0
  20. xhtml2pdf-0.2.28/xhtml2pdf/builders/preflight.py +358 -0
  21. xhtml2pdf-0.2.28/xhtml2pdf/builders/printmarks.py +176 -0
  22. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/builders/watermarks.py +67 -6
  23. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/context.py +75 -10
  24. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/default.py +1 -0
  25. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/document.py +30 -0
  26. xhtml2pdf-0.2.28/xhtml2pdf/opentype.py +156 -0
  27. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/parser.py +96 -8
  28. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/pisa.py +24 -0
  29. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/properties.py +29 -0
  30. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/reportlab_paragraph.py +116 -9
  31. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/tables.py +16 -6
  32. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/tags.py +29 -35
  33. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/util.py +73 -3
  34. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/w3c/css.py +73 -5
  35. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/w3c/cssDOMElementInterface.py +4 -0
  36. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/w3c/cssSpecial.py +14 -6
  37. xhtml2pdf-0.2.28/xhtml2pdf/w3c/generated_content.py +284 -0
  38. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/xhtml2pdf_reportlab.py +121 -16
  39. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28/xhtml2pdf.egg-info}/PKG-INFO +6 -1
  40. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf.egg-info/SOURCES.txt +11 -1
  41. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf.egg-info/requires.txt +6 -0
  42. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/LICENSE.txt +0 -0
  43. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/MANIFEST.in +0 -0
  44. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/README.rst +0 -0
  45. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/setup.cfg +0 -0
  46. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_bidi.py +0 -0
  47. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_block_box.py +0 -0
  48. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_block_margins.py +0 -0
  49. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_block_width.py +0 -0
  50. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_css_media_rule.py +0 -0
  51. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_css_parser.py +0 -0
  52. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_css_variables.py +0 -0
  53. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_files.py +0 -0
  54. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_flex.py +0 -0
  55. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_flex_flowable.py +0 -0
  56. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_flex_layout.py +0 -0
  57. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_font_isolation.py +0 -0
  58. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_frame_align.py +0 -0
  59. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_frame_pages.py +0 -0
  60. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_http.py +0 -0
  61. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_inline_block.py +0 -0
  62. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_inline_box.py +0 -0
  63. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_optional_dependencies.py +0 -0
  64. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_page_numbering.py +0 -0
  65. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_page_padding.py +0 -0
  66. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_paragraph.py +0 -0
  67. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_paragraph_height.py +0 -0
  68. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_parser.py +0 -0
  69. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_pdf.py +0 -0
  70. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_position.py +0 -0
  71. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_reportlab.py +0 -0
  72. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_reportlab_paragraph.py +0 -0
  73. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_resource_policy.py +0 -0
  74. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_right_to_left_font_support.py +0 -0
  75. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_selectors.py +0 -0
  76. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_signatures.py +0 -0
  77. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_table_border_radius.py +0 -0
  78. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_table_css.py +0 -0
  79. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_update_face_name.py +0 -0
  80. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_utils.py +0 -0
  81. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_word_breaking.py +0 -0
  82. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/tests/test_wsgi.py +0 -0
  83. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/__main__.py +0 -0
  84. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/_bidi_data.py +0 -0
  85. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/bidi.py +0 -0
  86. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/builders/__init__.py +0 -0
  87. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/builders/block.py +0 -0
  88. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/builders/flex.py +0 -0
  89. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/builders/flex_layout.py +0 -0
  90. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/builders/position.py +0 -0
  91. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/builders/signs.py +0 -0
  92. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/charts.py +0 -0
  93. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/config/__init__.py +0 -0
  94. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/config/httpconfig.py +0 -0
  95. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/config/resources.py +0 -0
  96. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/files.py +0 -0
  97. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/paragraph.py +0 -0
  98. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/pdf.py +0 -0
  99. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/w3c/__init__.py +0 -0
  100. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/w3c/cssParser.py +0 -0
  101. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/w3c/css_variables.py +0 -0
  102. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf/wsgi.py +0 -0
  103. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf.egg-info/dependency_links.txt +0 -0
  104. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/xhtml2pdf.egg-info/entry_points.txt +0 -0
  105. {xhtml2pdf-0.2.26 → xhtml2pdf-0.2.28}/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.28
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>
@@ -48,14 +48,19 @@ Requires-Dist: svglib>=1.2.1
48
48
  Provides-Extra: signing
49
49
  Requires-Dist: pyHanko>=0.37.0; extra == "signing"
50
50
  Requires-Dist: pyhanko-certvalidator>=0.32.1; extra == "signing"
51
+ Provides-Extra: fonts
52
+ Requires-Dist: fonttools>=4.40; extra == "fonts"
53
+ Requires-Dist: brotli>=1.0.9; extra == "fonts"
51
54
  Provides-Extra: all
52
55
  Requires-Dist: xhtml2pdf[signing]; extra == "all"
56
+ Requires-Dist: xhtml2pdf[fonts]; extra == "all"
53
57
  Provides-Extra: pycairo
54
58
  Requires-Dist: reportlab[pycairo]<6,>=4.4.9; extra == "pycairo"
55
59
  Provides-Extra: renderpm
56
60
  Requires-Dist: xhtml2pdf[pycairo]; extra == "renderpm"
57
61
  Provides-Extra: test
58
62
  Requires-Dist: xhtml2pdf[signing]; extra == "test"
63
+ Requires-Dist: xhtml2pdf[fonts]; extra == "test"
59
64
  Requires-Dist: tomli>=2.0.1; python_version < "3.11" and extra == "test"
60
65
  Requires-Dist: tox; extra == "test"
61
66
  Requires-Dist: coverage>=5.3; extra == "test"
@@ -68,9 +68,15 @@ signing = [
68
68
  "pyHanko>=0.37.0",
69
69
  "pyhanko-certvalidator>=0.32.1",
70
70
  ]
71
+ # OpenType (CFF), WOFF and WOFF2 fonts in @font-face; brotli reads WOFF2.
72
+ fonts = [
73
+ "fonttools>=4.40",
74
+ "brotli>=1.0.9",
75
+ ]
71
76
  # Every optional feature that needs nothing outside Python.
72
77
  all = [
73
78
  "xhtml2pdf[signing]",
79
+ "xhtml2pdf[fonts]",
74
80
  ]
75
81
  pycairo = [
76
82
  "reportlab[pycairo]>=4.4.9,<6",
@@ -84,6 +90,7 @@ renderpm = [
84
90
  ]
85
91
  test = [
86
92
  "xhtml2pdf[signing]",
93
+ "xhtml2pdf[fonts]",
87
94
  "tomli>=2.0.1; python_version<'3.11'",
88
95
  "tox",
89
96
  "coverage>=5.3"
@@ -123,7 +130,7 @@ legacy_tox_ini = """
123
130
  envlist = py{3.10,3.11,3.12,3.13,3.14}-rl{4,5}, py3.10-rlmin
124
131
 
125
132
  [testenv]
126
- extras = signing
133
+ extras = signing, fonts
127
134
  deps =
128
135
  coverage[toml]
129
136
  rl4: reportlab>=4.4.9,<5
@@ -325,6 +332,13 @@ Hink = "Hink"
325
332
  myu20 = "myu20"
326
333
  opf = "opf"
327
334
  PNGs = "PNGs"
335
+ # pypdf's StreamObject.flate_encode, named after the Flate filter.
336
+ flate_encode = "flate_encode"
337
+ # The TrueType glyph location table.
338
+ loca = "loca"
328
339
 
329
340
  [tool.typos.default.extend-words]
330
341
  splitted = "splitted"
342
+ # The PDF Flate filter (FlateDecode) and the stream key /DecodeParms.
343
+ Flate = "Flate"
344
+ Parms = "Parms"
@@ -126,6 +126,45 @@ class AsianFontSupportTests(TestCase):
126
126
  "Not all asian fonts detected in the PDF file!",
127
127
  )
128
128
 
129
+ def test_asian_font_cmap_matches_its_collection(self):
130
+ """
131
+ Every CJK face is written with a CMap of its own character collection.
132
+
133
+ ReportLab pairs MSung-Light (Adobe-CNS1) with UniGB-UCS2-H, which maps
134
+ to Adobe-GB1; Poppler drops a font with that pair and shows no text.
135
+ """
136
+ orderings = {
137
+ "UniGB": "GB1",
138
+ "UniCNS": "CNS1",
139
+ "UniJIS": "Japan1",
140
+ "UniKS": "Korea1",
141
+ }
142
+ with io.BytesIO() as pdf_file:
143
+ pisaDocument(src=self.HTML_CONTENT, dest=pdf_file)
144
+ pdf_file.seek(0)
145
+ reader = PdfReader(pdf_file)
146
+ found = {}
147
+ for page in reader.pages:
148
+ for ref in page["/Resources"]["/Font"].values():
149
+ font = ref.get_object()
150
+ if font.get("/Subtype") != "/Type0":
151
+ continue
152
+ descendant = font["/DescendantFonts"][0].get_object()
153
+ info = descendant["/CIDSystemInfo"].get_object()
154
+ found[str(font["/BaseFont"])[1:]] = (
155
+ str(font["/Encoding"])[1:],
156
+ str(info["/Ordering"]),
157
+ )
158
+
159
+ self.assertIn("MSung-Light", found)
160
+ self.assertEqual(("UniCNS-UCS2-H", "CNS1"), found["MSung-Light"])
161
+ mismatched = {
162
+ name: pair
163
+ for name, pair in found.items()
164
+ if orderings.get(pair[0].split("-")[0]) != pair[1]
165
+ }
166
+ self.assertEqual({}, mismatched)
167
+
129
168
  def test_get_default_asian_font(self):
130
169
  """Tests if we can successfully extract the default asian fonts"""
131
170
  DEFAULT_ASIAN_FONT = get_default_asian_font()
@@ -151,6 +190,7 @@ class AsianFontSupportTests(TestCase):
151
190
  "HeiseiMin-W3": ("jpn", "UniJIS-UCS2-H"),
152
191
  "HeiseiKakuGo-W5": ("jpn", "UniJIS-UCS2-H"),
153
192
  "STSong-Light": ("chs", "UniGB-UCS2-H"),
193
+ # The wrong CMap for this face; set_asian_fonts writes UniCNS.
154
194
  "MSung-Light": ("cht", "UniGB-UCS2-H"),
155
195
  "HYSMyeongJo-Medium": ("kor", "UniKS-UCS2-H"),
156
196
  "HYGothic-Medium": ("kor", "UniKS-UCS2-H"),
@@ -13,7 +13,7 @@ import os
13
13
  import subprocess
14
14
  import sys
15
15
  import tempfile
16
- from contextlib import redirect_stdout
16
+ from contextlib import redirect_stderr, redirect_stdout
17
17
  from pathlib import Path
18
18
  from unittest import TestCase, mock
19
19
 
@@ -80,6 +80,34 @@ class CommandTest(TestCase):
80
80
  self.assertTrue(dest.is_file())
81
81
  self.assertEqual("cli\nhello", PdfReader(dest).pages[0].extract_text().strip())
82
82
 
83
+ def test_pdfx_options_write_pdf_x(self) -> None:
84
+ from tests.test_print import embedded, fake_profile
85
+
86
+ self.src.write_text(embedded("<p>print</p>"), encoding="utf-8")
87
+ profile = Path(self.tmp.name) / "press.icc"
88
+ profile.write_bytes(fake_profile())
89
+ dest = Path(self.tmp.name) / "out.pdf"
90
+ code, _ = run_cli(
91
+ "-q",
92
+ "--pdfx-profile",
93
+ str(profile),
94
+ "--pdfx-condition",
95
+ "FOGRA39",
96
+ str(self.src),
97
+ str(dest),
98
+ )
99
+ self.assertEqual(0, code)
100
+ reader = PdfReader(dest)
101
+ self.assertEqual("PDF/X-4", reader.metadata["/GTS_PDFXVersion"])
102
+ intent = reader.trailer["/Root"]["/OutputIntents"][0].get_object()
103
+ self.assertEqual("FOGRA39", intent["/OutputConditionIdentifier"])
104
+
105
+ def test_pdfx_condition_without_a_profile_is_a_usage_error(self) -> None:
106
+ dest = Path(self.tmp.name) / "out.pdf"
107
+ with redirect_stderr(io.StringIO()):
108
+ code, _ = run_cli("--pdfx-condition", "FOGRA39", str(self.src), str(dest))
109
+ self.assertEqual(2, code)
110
+
83
111
  def test_destination_defaults_to_the_source_name(self) -> None:
84
112
  cwd = os.getcwd()
85
113
  os.chdir(self.tmp.name)
@@ -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
  """
@@ -12,6 +12,8 @@ announced.
12
12
  from __future__ import annotations
13
13
 
14
14
  import logging
15
+ import shutil
16
+ import tempfile
15
17
  from io import BytesIO
16
18
  from pathlib import Path
17
19
  from unittest import TestCase
@@ -255,3 +257,27 @@ class HashPrefixedFamilyTest(TestCase):
255
257
  fonts = base_fonts(render(html))
256
258
 
257
259
  self.assertTrue(any("NotoSans" in name for name in fonts), sorted(fonts))
260
+
261
+
262
+ class Type1FontTest(TestCase):
263
+ """A Type 1 face is its .pfb outlines and its .afm metrics, side by side."""
264
+
265
+ def setUp(self) -> None:
266
+ import reportlab
267
+
268
+ directory = tempfile.TemporaryDirectory()
269
+ self.addCleanup(directory.cleanup)
270
+ self.directory = Path(directory.name)
271
+ fonts = Path(reportlab.__file__).parent / "fonts"
272
+ for suffix in ("afm", "pfb"):
273
+ shutil.copy(fonts / f"DarkGardenMK.{suffix}", self.directory)
274
+
275
+ def test_either_file_of_the_pair_embeds_the_face(self) -> None:
276
+ for suffix in ("afm", "pfb"):
277
+ with self.subTest(suffix):
278
+ html = document("Garden", src=f"DarkGardenMK.{suffix}", text="abc")
279
+ output = BytesIO()
280
+ pisa.CreatePDF(
281
+ html, dest=output, path=str(self.directory / "document.html")
282
+ )
283
+ self.assertIn("/DarkGardenMK", base_fonts(output.getvalue()))
@@ -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))