xhtml2pdf 0.2.27__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.27/xhtml2pdf.egg-info → xhtml2pdf-0.2.28}/PKG-INFO +6 -1
  2. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/pyproject.toml +15 -1
  3. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_asian_font_support.py +40 -0
  4. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_cli.py +29 -1
  5. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_fonts.py +26 -0
  6. xhtml2pdf-0.2.28/tests/test_opentype.py +226 -0
  7. xhtml2pdf-0.2.28/tests/test_print.py +437 -0
  8. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_reportlab_api.py +35 -2
  9. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_security_limits.py +14 -10
  10. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_tags.py +19 -0
  11. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_watermarks.py +1 -1
  12. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/__init__.py +1 -1
  13. xhtml2pdf-0.2.28/xhtml2pdf/builders/pdfx.py +384 -0
  14. xhtml2pdf-0.2.28/xhtml2pdf/builders/preflight.py +358 -0
  15. xhtml2pdf-0.2.28/xhtml2pdf/builders/printmarks.py +176 -0
  16. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/builders/watermarks.py +54 -5
  17. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/context.py +64 -10
  18. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/document.py +25 -0
  19. xhtml2pdf-0.2.28/xhtml2pdf/opentype.py +156 -0
  20. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/parser.py +6 -3
  21. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/pisa.py +24 -0
  22. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/reportlab_paragraph.py +8 -9
  23. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/util.py +57 -3
  24. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/w3c/cssSpecial.py +14 -6
  25. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/xhtml2pdf_reportlab.py +24 -2
  26. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28/xhtml2pdf.egg-info}/PKG-INFO +6 -1
  27. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf.egg-info/SOURCES.txt +6 -0
  28. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf.egg-info/requires.txt +6 -0
  29. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/LICENSE.txt +0 -0
  30. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/MANIFEST.in +0 -0
  31. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/README.rst +0 -0
  32. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/setup.cfg +0 -0
  33. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_bidi.py +0 -0
  34. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_block_box.py +0 -0
  35. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_block_margins.py +0 -0
  36. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_block_width.py +0 -0
  37. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_css_media_rule.py +0 -0
  38. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_css_parser.py +0 -0
  39. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_css_variables.py +0 -0
  40. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_document.py +0 -0
  41. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_files.py +0 -0
  42. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_flex.py +0 -0
  43. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_flex_flowable.py +0 -0
  44. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_flex_layout.py +0 -0
  45. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_font_isolation.py +0 -0
  46. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_frame_align.py +0 -0
  47. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_frame_pages.py +0 -0
  48. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_generated_content.py +0 -0
  49. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_http.py +0 -0
  50. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_inline_block.py +0 -0
  51. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_inline_box.py +0 -0
  52. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_insert_pdf.py +0 -0
  53. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_optional_dependencies.py +0 -0
  54. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_page_numbering.py +0 -0
  55. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_page_padding.py +0 -0
  56. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_paragraph.py +0 -0
  57. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_paragraph_height.py +0 -0
  58. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_parser.py +0 -0
  59. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_pdf.py +0 -0
  60. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_position.py +0 -0
  61. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_reportlab.py +0 -0
  62. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_reportlab_paragraph.py +0 -0
  63. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_resource_policy.py +0 -0
  64. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_right_to_left_font_support.py +0 -0
  65. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_selectors.py +0 -0
  66. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_signatures.py +0 -0
  67. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_special_css.py +0 -0
  68. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_table_border_radius.py +0 -0
  69. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_table_css.py +0 -0
  70. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_tables.py +0 -0
  71. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_update_face_name.py +0 -0
  72. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_utils.py +0 -0
  73. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_word_breaking.py +0 -0
  74. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/tests/test_wsgi.py +0 -0
  75. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/__main__.py +0 -0
  76. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/_bidi_data.py +0 -0
  77. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/bidi.py +0 -0
  78. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/builders/__init__.py +0 -0
  79. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/builders/block.py +0 -0
  80. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/builders/flex.py +0 -0
  81. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/builders/flex_layout.py +0 -0
  82. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/builders/inserts.py +0 -0
  83. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/builders/position.py +0 -0
  84. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/builders/signs.py +0 -0
  85. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/charts.py +0 -0
  86. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/config/__init__.py +0 -0
  87. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/config/httpconfig.py +0 -0
  88. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/config/resources.py +0 -0
  89. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/default.py +0 -0
  90. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/files.py +0 -0
  91. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/paragraph.py +0 -0
  92. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/pdf.py +0 -0
  93. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/properties.py +0 -0
  94. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/tables.py +0 -0
  95. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/tags.py +0 -0
  96. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/w3c/__init__.py +0 -0
  97. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/w3c/css.py +0 -0
  98. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/w3c/cssDOMElementInterface.py +0 -0
  99. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/w3c/cssParser.py +0 -0
  100. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/w3c/css_variables.py +0 -0
  101. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/w3c/generated_content.py +0 -0
  102. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf/wsgi.py +0 -0
  103. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf.egg-info/dependency_links.txt +0 -0
  104. {xhtml2pdf-0.2.27 → xhtml2pdf-0.2.28}/xhtml2pdf.egg-info/entry_points.txt +0 -0
  105. {xhtml2pdf-0.2.27 → 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.27
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)
@@ -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,226 @@
1
+ """OpenType (CFF), WOFF and WOFF2 fonts in @font-face, through fontTools."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import io
7
+ import subprocess
8
+ import sys
9
+ import tempfile
10
+ import textwrap
11
+ from pathlib import Path
12
+ from unittest import TestCase, mock, skipUnless
13
+
14
+ import pypdf
15
+
16
+ from xhtml2pdf.document import pisaDocument
17
+
18
+ try:
19
+ from fontTools.fontBuilder import FontBuilder
20
+ from fontTools.pens.t2CharStringPen import T2CharStringPen
21
+ from fontTools.ttLib import TTFont
22
+ except ImportError: # pragma: no cover
23
+ FontBuilder = None
24
+
25
+ try:
26
+ import brotli
27
+ except ImportError: # pragma: no cover
28
+ brotli = None
29
+
30
+ TTF = Path(__file__).parent / "samples" / "font" / "Noto_Sans" / "NotoSans-Regular.ttf"
31
+
32
+
33
+ def cff_font(family: str = "Square") -> bytes:
34
+ """An OpenType font with PostScript outlines and one glyph, "A", a square."""
35
+ builder = FontBuilder(1000, isTTF=False)
36
+ builder.setupGlyphOrder([".notdef", "A"])
37
+ builder.setupCharacterMap({ord("A"): "A"})
38
+ charstrings = {}
39
+ for name in (".notdef", "A"):
40
+ pen = T2CharStringPen(600, None)
41
+ if name == "A":
42
+ pen.moveTo((100, 0))
43
+ pen.lineTo((500, 0))
44
+ pen.curveTo((550, 200), (550, 500), (500, 700))
45
+ pen.lineTo((100, 700))
46
+ pen.closePath()
47
+ charstrings[name] = pen.getCharString()
48
+ builder.setupCFF(family, {"FullName": family}, charstrings, {})
49
+ builder.setupHorizontalMetrics({".notdef": (600, 0), "A": (600, 100)})
50
+ builder.setupHorizontalHeader(ascent=800, descent=-200)
51
+ builder.setupNameTable({"familyName": family, "styleName": "Regular"})
52
+ builder.setupOS2(sTypoAscender=800, usWinAscent=800, usWinDescent=200)
53
+ builder.setupPost()
54
+ out = io.BytesIO()
55
+ builder.save(out)
56
+ return out.getvalue()
57
+
58
+
59
+ def wrapped(data: bytes, flavor: str) -> bytes:
60
+ font = TTFont(io.BytesIO(data))
61
+ font.flavor = flavor
62
+ out = io.BytesIO()
63
+ font.save(out)
64
+ return out.getvalue()
65
+
66
+
67
+ def data_uri(data: bytes, mimetype: str) -> str:
68
+ return f"data:{mimetype};base64,{base64.b64encode(data).decode()}"
69
+
70
+
71
+ def render(src: str, path: str = "") -> pypdf.PdfReader:
72
+ html = (
73
+ f"<style>@font-face {{ font-family: Test; src: {src} }}"
74
+ " p { font-family: Test }</style><p>AAA</p>"
75
+ )
76
+ out = io.BytesIO()
77
+ pisaDocument(html, dest=out, path=path)
78
+ return pypdf.PdfReader(io.BytesIO(out.getvalue()))
79
+
80
+
81
+ def embedded_fonts(reader: pypdf.PdfReader) -> dict[str, bool]:
82
+ fonts = {}
83
+ for font in reader.pages[0]["/Resources"]["/Font"].values():
84
+ font = font.get_object()
85
+ descriptor = font.get("/FontDescriptor")
86
+ fonts[str(font["/BaseFont"])] = descriptor is not None and (
87
+ "/FontFile2" in descriptor.get_object()
88
+ )
89
+ return fonts
90
+
91
+
92
+ def text_font(reader: pypdf.PdfReader) -> str:
93
+ """The base font of the face that sets the paragraph."""
94
+ names = {
95
+ str(name): str(font.get_object()["/BaseFont"])
96
+ for name, font in reader.pages[0]["/Resources"]["/Font"].items()
97
+ }
98
+ stream = reader.pages[0].get_contents().get_data().decode("latin-1")
99
+ used = [name for name in names if f"{name} " in stream and name != "/F1"]
100
+ return names[used[-1]]
101
+
102
+
103
+ @skipUnless(FontBuilder is not None, "needs fontTools (the fonts extra)")
104
+ class OpenTypeFontTestCase(TestCase):
105
+ def assertEmbedded(self, reader: pypdf.PdfReader, family: str) -> None:
106
+ font = text_font(reader)
107
+ self.assertIn(family, font)
108
+ self.assertTrue(embedded_fonts(reader)[font], font)
109
+
110
+ def test_cff_font_from_a_file(self) -> None:
111
+ directory = tempfile.TemporaryDirectory()
112
+ self.addCleanup(directory.cleanup)
113
+ font = Path(directory.name) / "square.otf"
114
+ font.write_bytes(cff_font())
115
+ document = Path(directory.name) / "document.html"
116
+ self.assertEmbedded(render("url(square.otf)", str(document)), "Square")
117
+
118
+ def test_cff_font_from_a_data_uri(self) -> None:
119
+ reader = render(f"url({data_uri(cff_font(), 'font/otf')})")
120
+ self.assertEmbedded(reader, "Square")
121
+
122
+ def test_woff_with_cff_outlines(self) -> None:
123
+ reader = render(f"url({data_uri(wrapped(cff_font(), 'woff'), 'font/woff')})")
124
+ self.assertEmbedded(reader, "Square")
125
+
126
+ @skipUnless(brotli is not None, "WOFF2 needs brotli")
127
+ def test_woff2_with_truetype_outlines(self) -> None:
128
+ woff2 = wrapped(TTF.read_bytes(), "woff2")
129
+ reader = render(f"url({data_uri(woff2, 'font/woff2')}) format('woff2')")
130
+ self.assertEmbedded(reader, "NotoSans")
131
+
132
+ def test_the_glyph_keeps_its_shape(self) -> None:
133
+ """The converted outline stays within a font unit of the original."""
134
+ from xhtml2pdf.opentype import to_truetype
135
+
136
+ converted = TTFont(io.BytesIO(to_truetype(cff_font())))
137
+ self.assertIn("glyf", converted)
138
+ self.assertNotIn("CFF ", converted)
139
+ glyph = converted["glyf"]["A"]
140
+ glyph.recalcBounds(converted["glyf"])
141
+ self.assertEqual(
142
+ (100, 0, 538, 700), (glyph.xMin, glyph.yMin, glyph.xMax, glyph.yMax)
143
+ )
144
+
145
+ def test_truetype_in_an_otf_file_is_not_converted(self) -> None:
146
+ from xhtml2pdf.opentype import needs_conversion, to_truetype
147
+
148
+ data = TTF.read_bytes()
149
+ self.assertFalse(needs_conversion(data))
150
+ self.assertIs(data, to_truetype(data))
151
+
152
+ def test_the_first_source_that_loads_wins(self) -> None:
153
+ """A later url() is a fallback, not a second embed of the family."""
154
+ src = (
155
+ f"url({data_uri(cff_font(), 'font/otf')}) format('opentype'),"
156
+ f" url({TTF.as_posix()})"
157
+ )
158
+ with self.assertNoLogs("xhtml2pdf.context", level="WARNING"):
159
+ reader = render(src)
160
+ self.assertEmbedded(reader, "Square")
161
+
162
+ def test_an_unreadable_font_falls_back_to_the_next_source(self) -> None:
163
+ src = (
164
+ f"url({data_uri(b'wOF2 not a font', 'font/woff2')}), url({TTF.as_posix()})"
165
+ )
166
+ with self.assertLogs("xhtml2pdf.context", level="WARNING") as logs:
167
+ reader = render(src)
168
+ self.assertTrue(any("Cannot embed the font" in line for line in logs.output))
169
+ self.assertEmbedded(reader, "NotoSans")
170
+
171
+ def test_a_damaged_cff_table_falls_back_to_the_next_source(self) -> None:
172
+ """The CFF table is read only once a glyph is drawn from it."""
173
+ data = bytearray(cff_font("Damaged"))
174
+ table = TTFont(io.BytesIO(bytes(data))).reader.tables["CFF "]
175
+ data[table.offset + 4 : table.offset + table.length] = b"\xff" * (
176
+ table.length - 4
177
+ )
178
+ src = f"url({data_uri(bytes(data), 'font/otf')}), url({TTF.as_posix()})"
179
+ with self.assertLogs("xhtml2pdf.context", level="WARNING") as logs:
180
+ reader = render(src)
181
+ self.assertTrue(any("Cannot embed the font" in line for line in logs.output))
182
+ self.assertEmbedded(reader, "NotoSans")
183
+
184
+ def test_a_font_converts_to_the_same_bytes_every_time(self) -> None:
185
+ """The same source font is registered once, under one digest."""
186
+ from xhtml2pdf import opentype
187
+
188
+ data = cff_font("Stable")
189
+ converted = []
190
+ for now in (3_000_000_000, 3_000_000_001):
191
+ opentype._cache.clear()
192
+ with mock.patch(
193
+ "fontTools.ttLib.tables._h_e_a_d.timestampNow", return_value=now
194
+ ):
195
+ converted.append(opentype.to_truetype(data))
196
+ self.assertEqual(converted[0], converted[1])
197
+
198
+
199
+ class WithoutFontToolsTest(TestCase):
200
+ def test_a_cff_font_asks_for_the_extra(self) -> None:
201
+ if FontBuilder is None:
202
+ self.skipTest("needs fontTools to build the test font")
203
+ script = textwrap.dedent(
204
+ f"""
205
+ import io, logging, sys
206
+ sys.modules["fontTools"] = None
207
+ logging.basicConfig(level=logging.WARNING, stream=sys.stdout)
208
+ from xhtml2pdf.document import pisaDocument
209
+ pisaDocument({render_html(data_uri(cff_font(), 'font/otf'))!r}, dest=io.BytesIO())
210
+ """
211
+ )
212
+ result = subprocess.run(
213
+ [sys.executable, "-c", script],
214
+ capture_output=True,
215
+ text=True,
216
+ timeout=120,
217
+ check=False,
218
+ )
219
+ self.assertIn("xhtml2pdf[fonts]", result.stdout, result.stderr)
220
+
221
+
222
+ def render_html(uri: str) -> str:
223
+ return (
224
+ f"<style>@font-face {{ font-family: Test; src: url({uri}) }}"
225
+ " p { font-family: Test }</style><p>AAA</p>"
226
+ )