prawn-svg 0.40.4 → 1.0.0

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 (257) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +190 -33
  3. data/lib/prawn/svg/angle.rb +12 -0
  4. data/lib/prawn/svg/attribute_value.rb +38 -0
  5. data/lib/prawn/svg/attributes/clip_path.rb +3 -9
  6. data/lib/prawn/svg/attributes/mask.rb +2 -7
  7. data/lib/prawn/svg/calculators/document_sizing.rb +17 -8
  8. data/lib/prawn/svg/calculators/pixels.rb +6 -9
  9. data/lib/prawn/svg/color.rb +1 -1
  10. data/lib/prawn/svg/css/selector_matcher.rb +109 -0
  11. data/lib/prawn/svg/css/selector_parser.rb +3 -1
  12. data/lib/prawn/svg/css/stylesheets.rb +68 -153
  13. data/lib/prawn/svg/css/values_parser.rb +18 -29
  14. data/lib/prawn/svg/document.rb +136 -42
  15. data/lib/prawn/svg/elements/base.rb +160 -33
  16. data/lib/prawn/svg/elements/bbox_scaling.rb +5 -0
  17. data/lib/prawn/svg/elements/call_duplicator.rb +18 -5
  18. data/lib/prawn/svg/elements/clip_path.rb +11 -1
  19. data/lib/prawn/svg/elements/direct_render_base.rb +2 -2
  20. data/lib/prawn/svg/elements/gradient.rb +47 -29
  21. data/lib/prawn/svg/elements/ignored.rb +1 -3
  22. data/lib/prawn/svg/elements/image.rb +47 -22
  23. data/lib/prawn/svg/elements/marker.rb +7 -4
  24. data/lib/prawn/svg/elements/mask.rb +5 -5
  25. data/lib/prawn/svg/elements/path.rb +20 -16
  26. data/lib/prawn/svg/elements/pattern.rb +5 -5
  27. data/lib/prawn/svg/elements/stop.rb +8 -0
  28. data/lib/prawn/svg/elements/switch.rb +0 -71
  29. data/lib/prawn/svg/elements/text.rb +15 -2
  30. data/lib/prawn/svg/elements/text_component.rb +29 -26
  31. data/lib/prawn/svg/elements/text_node.rb +16 -3
  32. data/lib/prawn/svg/elements/text_path.rb +30 -19
  33. data/lib/prawn/svg/elements/unsupported.rb +5 -0
  34. data/lib/prawn/svg/elements/use.rb +54 -14
  35. data/lib/prawn/svg/elements/viewport.rb +2 -0
  36. data/lib/prawn/svg/elements.rb +161 -31
  37. data/lib/prawn/svg/error.rb +9 -0
  38. data/lib/prawn/svg/extension.rb +2 -2
  39. data/lib/prawn/svg/font_metrics.rb +24 -128
  40. data/lib/prawn/svg/font_registry.rb +84 -6
  41. data/lib/prawn/svg/gradient_renderer.rb +23 -10
  42. data/lib/prawn/svg/gradients.rb +44 -10
  43. data/lib/prawn/svg/interface.rb +33 -14
  44. data/lib/prawn/svg/issue.rb +18 -0
  45. data/lib/prawn/svg/length.rb +2 -2
  46. data/lib/prawn/svg/link_renderer.rb +6 -1
  47. data/lib/prawn/svg/loaders/data.rb +1 -1
  48. data/lib/prawn/svg/loaders/file.rb +22 -67
  49. data/lib/prawn/svg/loaders/web.rb +16 -7
  50. data/lib/prawn/svg/number.rb +17 -0
  51. data/lib/prawn/svg/paint.rb +5 -4
  52. data/lib/prawn/svg/pathable.rb +16 -11
  53. data/lib/prawn/svg/percentage.rb +2 -2
  54. data/lib/prawn/svg/properties.rb +136 -32
  55. data/lib/prawn/svg/renderer.rb +46 -26
  56. data/lib/prawn/svg/requests/file.rb +50 -0
  57. data/lib/prawn/svg/requests/http.rb +44 -0
  58. data/lib/prawn/svg/requests/ssrf_filter.rb +16 -0
  59. data/lib/prawn/svg/requests/unfiltered.rb +25 -0
  60. data/lib/prawn/svg/resource_loader.rb +24 -0
  61. data/lib/prawn/svg/state.rb +4 -1
  62. data/lib/prawn/svg/transform_parser.rb +16 -7
  63. data/lib/prawn/svg/url_loader.rb +34 -18
  64. data/lib/prawn/svg/version.rb +1 -1
  65. data/lib/prawn/svg/work_budget.rb +18 -0
  66. data/lib/prawn-svg.rb +16 -0
  67. metadata +56 -195
  68. data/.github/workflows/lint.yml +0 -19
  69. data/.github/workflows/test.yml +0 -22
  70. data/.gitignore +0 -10
  71. data/.rspec +0 -2
  72. data/.rubocop.yml +0 -86
  73. data/.rubocop_todo.yml +0 -51
  74. data/Gemfile +0 -15
  75. data/Gemfile.lock +0 -81
  76. data/Rakefile +0 -26
  77. data/prawn-svg.gemspec +0 -26
  78. data/scripts/compare_samples +0 -25
  79. data/spec/integration_spec.rb +0 -168
  80. data/spec/prawn/svg/attributes/clip_path_spec.rb +0 -246
  81. data/spec/prawn/svg/attributes/opacity_spec.rb +0 -88
  82. data/spec/prawn/svg/attributes/stroke_spec.rb +0 -126
  83. data/spec/prawn/svg/attributes/transform_spec.rb +0 -58
  84. data/spec/prawn/svg/calculators/aspect_ratio_spec.rb +0 -95
  85. data/spec/prawn/svg/calculators/document_sizing_spec.rb +0 -156
  86. data/spec/prawn/svg/calculators/path_length_spec.rb +0 -141
  87. data/spec/prawn/svg/calculators/pixels_spec.rb +0 -77
  88. data/spec/prawn/svg/color_spec.rb +0 -44
  89. data/spec/prawn/svg/css/font_face_parser_spec.rb +0 -72
  90. data/spec/prawn/svg/css/font_family_parser_spec.rb +0 -24
  91. data/spec/prawn/svg/css/selector_parser_spec.rb +0 -39
  92. data/spec/prawn/svg/css/stylesheets_spec.rb +0 -499
  93. data/spec/prawn/svg/css/values_parser_spec.rb +0 -16
  94. data/spec/prawn/svg/document_spec.rb +0 -257
  95. data/spec/prawn/svg/elements/anchor_spec.rb +0 -43
  96. data/spec/prawn/svg/elements/base_spec.rb +0 -194
  97. data/spec/prawn/svg/elements/gradient_spec.rb +0 -210
  98. data/spec/prawn/svg/elements/image_spec.rb +0 -169
  99. data/spec/prawn/svg/elements/line_spec.rb +0 -55
  100. data/spec/prawn/svg/elements/marker_spec.rb +0 -91
  101. data/spec/prawn/svg/elements/mask_spec.rb +0 -382
  102. data/spec/prawn/svg/elements/path_spec.rb +0 -332
  103. data/spec/prawn/svg/elements/pattern_spec.rb +0 -232
  104. data/spec/prawn/svg/elements/polygon_spec.rb +0 -49
  105. data/spec/prawn/svg/elements/polyline_spec.rb +0 -47
  106. data/spec/prawn/svg/elements/root_spec.rb +0 -28
  107. data/spec/prawn/svg/elements/switch_spec.rb +0 -310
  108. data/spec/prawn/svg/elements/text_path_spec.rb +0 -183
  109. data/spec/prawn/svg/elements/text_spec.rb +0 -871
  110. data/spec/prawn/svg/elements/use_spec.rb +0 -274
  111. data/spec/prawn/svg/font_metrics_spec.rb +0 -14
  112. data/spec/prawn/svg/font_registry_spec.rb +0 -407
  113. data/spec/prawn/svg/font_spec.rb +0 -76
  114. data/spec/prawn/svg/funciri_spec.rb +0 -59
  115. data/spec/prawn/svg/interface_spec.rb +0 -185
  116. data/spec/prawn/svg/length_spec.rb +0 -89
  117. data/spec/prawn/svg/loaders/data_spec.rb +0 -63
  118. data/spec/prawn/svg/loaders/file_spec.rb +0 -106
  119. data/spec/prawn/svg/loaders/web_spec.rb +0 -37
  120. data/spec/prawn/svg/paint_spec.rb +0 -96
  121. data/spec/prawn/svg/pathable_spec.rb +0 -92
  122. data/spec/prawn/svg/pdfmatrix_spec.rb +0 -60
  123. data/spec/prawn/svg/percentage_spec.rb +0 -60
  124. data/spec/prawn/svg/properties_spec.rb +0 -401
  125. data/spec/prawn/svg/transform_parser_spec.rb +0 -94
  126. data/spec/prawn/svg/ttc_spec.rb +0 -31
  127. data/spec/prawn/svg/ttf_spec.rb +0 -32
  128. data/spec/prawn/svg/url_loader_spec.rb +0 -114
  129. data/spec/sample_css/import_base.css +0 -4
  130. data/spec/sample_css/import_nested.css +0 -1
  131. data/spec/sample_images/image_svg_embed.svg +0 -6
  132. data/spec/sample_images/mushroom-long.jpg +0 -0
  133. data/spec/sample_images/mushroom-wide.jpg +0 -0
  134. data/spec/sample_output/.keep +0 -0
  135. data/spec/sample_svg/alignment_baseline.svg +0 -61
  136. data/spec/sample_svg/arc_test_a.svg +0 -186
  137. data/spec/sample_svg/arc_test_b.svg +0 -194
  138. data/spec/sample_svg/arcs01.svg +0 -23
  139. data/spec/sample_svg/arrows.svg +0 -73
  140. data/spec/sample_svg/baseline_shift.svg +0 -55
  141. data/spec/sample_svg/bytes.svg +0 -121
  142. data/spec/sample_svg/cap_styles.svg +0 -13
  143. data/spec/sample_svg/circle01.svg +0 -12
  144. data/spec/sample_svg/clip_path.svg +0 -10
  145. data/spec/sample_svg/clip_path_text.svg +0 -104
  146. data/spec/sample_svg/clip_path_units.svg +0 -102
  147. data/spec/sample_svg/close_path.svg +0 -10
  148. data/spec/sample_svg/cmyk.svg +0 -5
  149. data/spec/sample_svg/css_import.svg +0 -38
  150. data/spec/sample_svg/cubic01.svg +0 -37
  151. data/spec/sample_svg/cubic01a.svg +0 -40
  152. data/spec/sample_svg/cubic02.svg +0 -86
  153. data/spec/sample_svg/display_none.svg +0 -13
  154. data/spec/sample_svg/dominant_baseline.svg +0 -41
  155. data/spec/sample_svg/double_opacity.svg +0 -6
  156. data/spec/sample_svg/ellipse01.svg +0 -17
  157. data/spec/sample_svg/font_face.svg +0 -77
  158. data/spec/sample_svg/font_stretch.svg +0 -54
  159. data/spec/sample_svg/font_weights.svg +0 -140
  160. data/spec/sample_svg/gistfile1.svg +0 -36
  161. data/spec/sample_svg/google_charts.svg +0 -181
  162. data/spec/sample_svg/gradient_offset_transparency.svg +0 -45
  163. data/spec/sample_svg/gradient_stress_test.svg +0 -115
  164. data/spec/sample_svg/gradient_transform.svg +0 -19
  165. data/spec/sample_svg/gradients-cmyk.svg +0 -40
  166. data/spec/sample_svg/gradients.svg +0 -40
  167. data/spec/sample_svg/hidden_paths.svg +0 -6
  168. data/spec/sample_svg/highcharts.svg +0 -52
  169. data/spec/sample_svg/image01.svg +0 -130
  170. data/spec/sample_svg/image02_base64.svg +0 -54
  171. data/spec/sample_svg/image03.svg +0 -30
  172. data/spec/sample_svg/image_svg.svg +0 -9
  173. data/spec/sample_svg/important.svg +0 -14
  174. data/spec/sample_svg/kerning.svg +0 -45
  175. data/spec/sample_svg/lang.svg +0 -117
  176. data/spec/sample_svg/line01.svg +0 -22
  177. data/spec/sample_svg/links.svg +0 -58
  178. data/spec/sample_svg/marker.svg +0 -32
  179. data/spec/sample_svg/marker_shorthand.svg +0 -48
  180. data/spec/sample_svg/markers_degenerate_cp.svg +0 -19
  181. data/spec/sample_svg/mask3.svg +0 -13
  182. data/spec/sample_svg/mask3b.svg +0 -13
  183. data/spec/sample_svg/mask_basic.svg +0 -11
  184. data/spec/sample_svg/mask_contentUnits_objectBoundingBox.svg +0 -11
  185. data/spec/sample_svg/mask_gradient.svg +0 -13
  186. data/spec/sample_svg/mask_image.svg +0 -10
  187. data/spec/sample_svg/mask_multiple.svg +0 -15
  188. data/spec/sample_svg/mask_nested.svg +0 -15
  189. data/spec/sample_svg/mask_opacity.svg +0 -21
  190. data/spec/sample_svg/mask_text.svg +0 -10
  191. data/spec/sample_svg/mask_text_gradient.svg +0 -31
  192. data/spec/sample_svg/mask_units_objectBoundingBox.svg +0 -11
  193. data/spec/sample_svg/mask_units_userSpaceOnUse.svg +0 -10
  194. data/spec/sample_svg/mask_with_transform.svg +0 -11
  195. data/spec/sample_svg/maths.svg +0 -34
  196. data/spec/sample_svg/matrix_transform.svg +0 -13
  197. data/spec/sample_svg/matrix_transform_3.svg +0 -33
  198. data/spec/sample_svg/multilingual.svg +0 -7
  199. data/spec/sample_svg/negminy.svg +0 -25
  200. data/spec/sample_svg/no_width_or_height.svg +0 -4
  201. data/spec/sample_svg/offset_viewport.svg +0 -8
  202. data/spec/sample_svg/omnigraffle.svg +0 -41
  203. data/spec/sample_svg/opacity01.svg +0 -42
  204. data/spec/sample_svg/ordering.svg +0 -12
  205. data/spec/sample_svg/path.svg +0 -5
  206. data/spec/sample_svg/pattern.svg +0 -80
  207. data/spec/sample_svg/pie_piece.svg +0 -7
  208. data/spec/sample_svg/polygon01.svg +0 -37
  209. data/spec/sample_svg/polyline01.svg +0 -18
  210. data/spec/sample_svg/positioning.svg +0 -26
  211. data/spec/sample_svg/presentation_attribute_precedence.svg +0 -12
  212. data/spec/sample_svg/preserve-space.svg +0 -19
  213. data/spec/sample_svg/quad01.svg +0 -28
  214. data/spec/sample_svg/radgrad01-bounding.svg +0 -26
  215. data/spec/sample_svg/radgrad01.svg +0 -26
  216. data/spec/sample_svg/rect01.svg +0 -12
  217. data/spec/sample_svg/rect02.svg +0 -13
  218. data/spec/sample_svg/rotate_scale.svg +0 -38
  219. data/spec/sample_svg/rounded_rectangle.svg +0 -101
  220. data/spec/sample_svg/scale.svg +0 -17
  221. data/spec/sample_svg/scruffy_graph.svg +0 -134
  222. data/spec/sample_svg/stroke_dashoffset.svg +0 -48
  223. data/spec/sample_svg/stroke_miterlimit.svg +0 -48
  224. data/spec/sample_svg/subfamilies.svg +0 -17
  225. data/spec/sample_svg/subviewports.svg +0 -173
  226. data/spec/sample_svg/subviewports2.svg +0 -16
  227. data/spec/sample_svg/svg_fill.svg +0 -5
  228. data/spec/sample_svg/switch.svg +0 -106
  229. data/spec/sample_svg/symbol.svg +0 -12
  230. data/spec/sample_svg/text-decoration.svg +0 -6
  231. data/spec/sample_svg/text_entities.svg +0 -11
  232. data/spec/sample_svg/text_path.svg +0 -25
  233. data/spec/sample_svg/text_stroke.svg +0 -41
  234. data/spec/sample_svg/text_use.svg +0 -37
  235. data/spec/sample_svg/transform.svg +0 -20
  236. data/spec/sample_svg/tref01.svg +0 -21
  237. data/spec/sample_svg/triangle01.svg +0 -12
  238. data/spec/sample_svg/tspan01.svg +0 -17
  239. data/spec/sample_svg/tspan02.svg +0 -22
  240. data/spec/sample_svg/tspan03-cc.svg +0 -21
  241. data/spec/sample_svg/tspan03.svg +0 -21
  242. data/spec/sample_svg/tspan04.svg +0 -16
  243. data/spec/sample_svg/tspan05.svg +0 -40
  244. data/spec/sample_svg/tspan91.svg +0 -34
  245. data/spec/sample_svg/use.svg +0 -17
  246. data/spec/sample_svg/use_disordered.svg +0 -17
  247. data/spec/sample_svg/use_external.svg +0 -51
  248. data/spec/sample_svg/use_external_icons.svg +0 -29
  249. data/spec/sample_svg/vertical-text.svg +0 -152
  250. data/spec/sample_svg/view.svg +0 -48
  251. data/spec/sample_svg/viewbox.svg +0 -4
  252. data/spec/sample_svg/viewport.svg +0 -23
  253. data/spec/sample_svg/warning-radioactive.svg +0 -98
  254. data/spec/sample_svg/word_spacing.svg +0 -45
  255. data/spec/sample_ttf/OpenSans-SemiboldItalic.ttf +0 -0
  256. data/spec/sample_ttf/TestFamily.ttc +0 -0
  257. data/spec/spec_helper.rb +0 -63
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 37f7a560005c2271a73fe47fd533915d785ac1752a3325f501d554915acf3e96
4
- data.tar.gz: b9e16e8a36bcc9bf583509804a14544f9f905be0ce8e9416be73f5990c232e12
3
+ metadata.gz: 48a12f6d50a8ba2b788ed58979e4c9bc569a01cff8824e6878c251ee80b169a2
4
+ data.tar.gz: 21a4d300bf80a59327438bd5657b72173cf7e66e4e2d4290ce7650ee340bf986
5
5
  SHA512:
6
- metadata.gz: dbc3cea5b1574d57feac632dbe7b18243c4071900e8f410494cb00baf52eec6624e2661b58df3038b859dc1ab3147a387bf046b41040ea508068ad58ad6fd96d
7
- data.tar.gz: 7e39ddd55b35c633c03b2a9d8b791789090fa813518816986dc6547e22a06288a9ad254d5398a0b4fbbfa0ab730a46454ffeefb912f7f7dafb08ab4b8b1480ab
6
+ metadata.gz: e95c3fe8eebf97536ad2a1e978df44a7989bb9d7cf395d2f15dd6306abc157da772c89d21d1182c2cd1680ce142d6bd8eb983f90f0fe46978e2af71842ecb8ab
7
+ data.tar.gz: 8848368977cc3eb4e063623a46e2596a23bca58b7a979c58d940aa18a29b5d178b0ea86f233d7a437c912a361c3b7f311141efda41b9cd34f66cdda66c5f2f22
data/README.md CHANGED
@@ -7,8 +7,7 @@ An SVG renderer for the [Prawn PDF library](https://github.com/prawnpdf/prawn).
7
7
 
8
8
  This will take an SVG document as input and render it into your PDF, along with whatever else you build with Prawn.
9
9
 
10
- prawn-svg is compatible with all versions of Prawn from 0.11.1 onwards, including the 1.x and 2.x series, although
11
- you'll need version 2.2.0 onwards if you want color gradients. The minimum Ruby version required is 2.7.
10
+ prawn-svg requires Prawn 2.3.0 or later, and Ruby 2.7 or later.
12
11
 
13
12
  ## Using prawn-svg
14
13
 
@@ -19,22 +18,81 @@ end
19
18
  ```
20
19
 
21
20
  prawn-svg will do something sensible if you call it with only an SVG document, but you can also
22
- pass the following options to tailor its operation:
23
-
24
- Option | Data type | Description
25
- ----------- | --------- | -----------
26
- :at | [integer, integer] | Specify the location on the page you want the SVG to appear.
27
- :position | :left, :center, :right, integer | If :at not specified, specifies the horizontal position to show the SVG. Defaults to :left.
28
- :vposition | :top, :center, :bottom, integer | If :at not specified, specifies the vertical position to show the SVG. Defaults to current cursor position.
29
- :width | integer | Desired width of the SVG. Defaults to horizontal space available.
30
- :height | integer | Desired height of the SVG. Defaults to vertical space available.
31
- :enable_web_requests | boolean | If true, prawn-svg will make http and https requests to fetch images, `@font-face` fonts, and external `<use>` references.<br><br>Defaults to true, but will **default to false** in the upcoming 1.0 release. It's recommended you explicitly set this option for now.
32
- :enable_file_requests_with_root | string | If not nil, prawn-svg will serve `file:` URLs and relative paths from your local disk if the file is located under the specified directory. Required for `@font-face` fonts and external `<use>` references loaded via file paths.<br><br>It is very dangerous to specify the root path ("/") if you're not fully in control of your input SVG. Defaults to `nil` (off).
33
- :cache_images | boolean | If true, prawn-svg will cache the result of all URL requests. Defaults to false.
34
- :fallback_font_name | string | A font name which will override the default fallback font of Times-Roman. If this value is set to `nil`, prawn-svg will ignore a request for an unknown font and log a warning.
35
- :color_mode | :rgb, :cmyk | Output color mode. Defaults to :rgb.
36
- :language | string | BCP 47 language tag for `<switch>` `systemLanguage` matching. Defaults to `"en"`.
37
- :log_warnings | boolean | If true, warnings that occur when parsing/rendering the SVG are output to stderr via `warn`. Use this when you're not getting the output you expect. Defaults to false.
21
+ pass the following options to tailor its operation. Unknown options raise `ArgumentError`.
22
+
23
+ - **`:at`**\
24
+ Type: `[x, y]` · Default: none\
25
+ Location on the page to draw the SVG.
26
+
27
+ - **`:position`**\
28
+ Type: `:left`, `:center`, `:right`, integer · Default: `:left`\
29
+ Horizontal position, if `:at` isn't given.
30
+
31
+ - **`:vposition`**\
32
+ Type: `:top`, `:center`, `:bottom`, integer · Default: current cursor position\
33
+ Vertical position, if `:at` isn't given.
34
+
35
+ - **`:width`**\
36
+ Type: integer · Default: horizontal space available\
37
+ Desired width of the SVG.
38
+
39
+ - **`:height`**\
40
+ Type: integer · Default: vertical space available\
41
+ Desired height of the SVG.
42
+
43
+ - **`:web_requests`**\
44
+ Type: boolean, callable · Default: `false`\
45
+ If true, prawn-svg will fetch http and https URLs for images, `@font-face` fonts, `@import` stylesheets and external
46
+ `<use>` references. Requests go through [`ssrf_filter`](https://github.com/arkadiyt/ssrf_filter), which refuses
47
+ private, loopback and link-local addresses. Can also be a callable; see [Web requests](#web-requests). `false`
48
+ denies all web requests.
49
+
50
+ - **`:file_requests`**\
51
+ Type: `false`, string, Pathname, callable · Default: `false`\
52
+ If a directory path, prawn-svg will read `file:` URLs and relative paths for images, `@font-face` fonts, `@import`
53
+ stylesheets and external `<use>` references from under that directory. Can also be a callable; see
54
+ [File requests](#file-requests). Not available to SVGs loaded by `<image>`, or to content fetched from the web.
55
+ `false` denies all file requests.
56
+
57
+ - **`:cache_requests`**\
58
+ Type: Hash-like, `false` · Default: a new `Hash` for each render\
59
+ Where responses are cached. prawn-svg looks up each URL in it before making a request, and stores each successful
60
+ response in it, so by default each URL is requested at most once per render. To share the cache across renders, pass
61
+ your own `Hash`, or any object with `[]` and `[]=` that returns `nil` for a missing key. `false` turns caching off.
62
+ Keys are URLs as written in the SVG. Failed requests and `data:` URLs are not stored. A cached response is returned
63
+ without checking `:web_requests` or `:file_requests`.
64
+
65
+ - **`:fallback_font_name`**\
66
+ Type: string, `nil` · Default: `"Times-Roman"`\
67
+ Font used when the SVG asks for an unknown font. If `nil`, text in an unknown font is skipped and reported as a
68
+ `:resource` issue.
69
+
70
+ - **`:color_mode`**\
71
+ Type: `:rgb`, `:cmyk` · Default: `:rgb`\
72
+ Output color mode.
73
+
74
+ - **`:language`**\
75
+ Type: string · Default: `"en"`\
76
+ BCP 47 language tag for `<switch>` `systemLanguage` matching.
77
+
78
+ - **`:log_issues`**\
79
+ Type: boolean · Default: `false`\
80
+ If true, issues that occur when parsing/rendering the SVG are output to stderr via `warn`. Use this when you're not
81
+ getting the output you expect.
82
+
83
+ - **`:raise_on_issue`**\
84
+ Type: boolean, symbol, array · Default: `false`\
85
+ If true, raises `Prawn::SVG::IssueError` after rendering if any issues occurred. If a category or array of
86
+ categories, only issues in those categories raise, and an unknown category raises `ArgumentError`. See
87
+ [Issues](#issues).
88
+
89
+ - **`:max_work`**\
90
+ Type: integer, `false` · Default: `1_000_000`\
91
+ Limits how much work rendering may take, so that a small hostile SVG can't use excessive time or memory. If exceeded,
92
+ `Prawn::SVG::WorkLimitExceeded` is raised before anything is drawn. One unit is roughly an element, a
93
+ drawing call, a character of text, or a few hundred bytes of image data, counting every time `<use>`, markers,
94
+ patterns, masks and clip paths repeat them. Very large drawings, such as a path with millions of points, may need a
95
+ higher value. `false` turns the limit off. `svg` returns the work used in `result[:work]`.
38
96
 
39
97
  ## Examples
40
98
 
@@ -45,9 +103,29 @@ Option | Data type | Description
45
103
  # Render the logo at the current Y cursor position, centered in the current bounding box
46
104
  svg IO.read("logo.svg"), position: :center
47
105
 
48
- # Render the logo at the current Y cursor position, and serve file: links relative to its directory
106
+ # Render the logo and allow loading of file: resources relative to its directory
49
107
  root_path = "/apps/myapp/current/images"
50
- svg IO.read("#{root_path}/logo.svg"), enable_file_requests_with_root: root_path, log_warnings: true
108
+ svg IO.read("#{root_path}/logo.svg"), file_requests: root_path, log_issues: true
109
+ ```
110
+
111
+ All options with their defaults:
112
+
113
+ ```ruby
114
+ svg data,
115
+ at: nil, # [x, y]
116
+ position: :left, # :left, :center, :right, integer
117
+ vposition: nil, # :top, :center, :bottom, integer; nil = cursor
118
+ width: nil, # nil = available width
119
+ height: nil, # nil = available height
120
+ web_requests: false, # true, callable
121
+ file_requests: false, # directory path, callable
122
+ cache_requests: {}, # Hash-like, false; default is new per render
123
+ fallback_font_name: "Times-Roman", # nil = skip unknown fonts
124
+ color_mode: :rgb, # :rgb, :cmyk
125
+ language: "en", # BCP 47 tag
126
+ log_issues: false,
127
+ raise_on_issue: false, # true, category, [categories]
128
+ max_work: 1_000_000 # false = unlimited
51
129
  ```
52
130
 
53
131
  ## Supported features
@@ -65,13 +143,13 @@ prawn-svg supports almost all of the full SVG 1.1 specification:
65
143
 
66
144
  - `<svg>`, `<g>` and `<symbol>`
67
145
 
68
- - `<use>` with local and external references (e.g. `other.svg#elementId`), subject to `enable_web_requests` and `enable_file_requests_with_root`
146
+ - `<use>` with local and external references (e.g. `other.svg#elementId`), subject to `web_requests` and `file_requests`
69
147
 
70
148
  - `<style>` (see CSS section below)
71
149
 
72
150
  - `<image>` referencing a JPEG, PNG, or SVG image, with `http:`, `https:`, `data:image/jpeg;base64`,
73
- `data:image/png;base64`, `data:image/svg+xml;base64` and `file:` schemes (`file:` is disabled by default for
74
- security reasons, see Options section above)
151
+ `data:image/png;base64`, `data:image/svg+xml;base64` and `file:` schemes (`http:`, `https:` and `file:` are
152
+ disabled by default for security reasons, see Options section above)
75
153
 
76
154
  - `<clipPath>` with `clipPathUnits` attribute and text content
77
155
 
@@ -79,15 +157,16 @@ prawn-svg supports almost all of the full SVG 1.1 specification:
79
157
 
80
158
  - `<marker>`
81
159
 
82
- - `<linearGradient>` and `<radialGradient>` are implemented on Prawn 2.2.0+ with attributes `gradientUnits` and
160
+ - `<linearGradient>` and `<radialGradient>` are implemented with attributes `gradientUnits` and
83
161
  `gradientTransform`
84
162
 
85
163
  - `<pattern>` with attributes `patternUnits`, `patternContentUnits`, `patternTransform`, `viewBox`,
86
164
  `preserveAspectRatio`, and `href` inheritance. Patterns can be used for both fill and stroke.
87
165
  Nested patterns (a pattern whose content references another pattern) are not supported.
88
166
 
89
- - `<switch>` with conditional processing (`requiredFeatures`, `requiredExtensions`, `systemLanguage`).
90
- `<foreignObject>` tags are always ignored as prawn-svg cannot handle non-SVG data.
167
+ - `<switch>`, and conditional processing (`requiredFeatures`, `requiredExtensions`, `systemLanguage`)
168
+ on the elements SVG 1.1 gives them to.
169
+ `<foreignObject>` tags are ignored as prawn-svg cannot handle non-SVG data.
91
170
 
92
171
  - `<view>` element for defining named views. Fragment identifiers (`#viewId` and `#svgView(...)`) on
93
172
  `<image>` hrefs select which view to render an external SVG with.
@@ -115,15 +194,15 @@ prawn-svg supports almost all of the full SVG 1.1 specification:
115
194
  the measurements above plus `em` or `rem`
116
195
 
117
196
  - `@font-face` in `<style>` blocks: `url()` sources (TTF/OTF formats) and `local()` references, with `font-weight`,
118
- `font-style` and `font-stretch` descriptors. Font loading is subject to the `enable_web_requests` and
119
- `enable_file_requests_with_root` options.
197
+ `font-style` and `font-stretch` descriptors. Font loading is subject to the `web_requests` and
198
+ `file_requests` options.
120
199
 
121
200
  ## CSS
122
201
 
123
202
  prawn-svg fully supports CSS2, both in `<style>` blocks and `style` attributes.
124
203
 
125
- `@import` rules are supported for loading external stylesheets (requires `enable_web_requests` or
126
- `enable_file_requests_with_root` options enabled).
204
+ `@import` rules are supported for loading external stylesheets (requires `web_requests` or
205
+ `file_requests` options enabled).
127
206
 
128
207
  In CSS selectors you can use element names, IDs, classes, attributes (existence, `=`, `^=`, `$=`, `*=`, `~=`, `|=`)
129
208
  and all combinators (` `, `>`, `+`, `~`). The pseudo-classes `:first-child`, `:last-child`, `:link`, `:nth-child()`
@@ -137,7 +216,7 @@ the screen.
137
216
 
138
217
  prawn-svg does not support filters, as rasterised effects is not something the PDF format was designed to handle.
139
218
 
140
- writing-mode is partially supported: vertical-rl and vertical-lr rotate the text 90 degrees, which
219
+ writing-mode is partially supported: vertical-rl and vertical-lr (and SVG 1.1's tb-rl and tb) rotate the text 90 degrees, which
141
220
  handles the common case of sideways Latin text. CJK upright glyph orientation is not supported.
142
221
 
143
222
  direction and unicode-bidi are not supported.
@@ -146,13 +225,76 @@ Features that will probably never be supported because either they don't make se
146
225
  in SVG 2, and/or they are rarely used: filters, SVG fonts, altGlyph, font-size-adjust, glyph-orientation, rendering
147
226
  hints, ICC color profiles, color-interpolation, enable-background, deprecated CSS clip, @media.
148
227
 
228
+ ## Issues
229
+
230
+ When prawn-svg can't render something as a browser would, it records an issue and carries on. `svg` returns them
231
+ in `result[:issues]` as `Prawn::SVG::Issue` objects, each with a `category` and `message`. The categories are
232
+ `:unsupported` (a valid feature prawn-svg ignores), `:unknown` (a tag, attribute or property it doesn't recognise,
233
+ usually one browsers ignore too), `:invalid` (malformed SVG, such as an unusable value or a reference to a missing
234
+ element) and `:resource` (an image, font or stylesheet couldn't be loaded).
235
+
236
+ To reject SVGs that won't render as they would in a browser:
237
+
238
+ ```ruby
239
+ svg data, raise_on_issue: [:unsupported, :invalid, :resource]
240
+ ```
241
+
242
+ SVG data that can't be parsed raises `Prawn::SVG::InvalidSVGData`. prawn-svg's own errors, including
243
+ `Prawn::SVG::IssueError`, inherit from `Prawn::SVG::Error`.
244
+
149
245
  ## Configuration
150
246
 
247
+ ### Web requests
248
+
249
+ `web_requests: true` uses `ssrf_filter` with Net::HTTP's default 60 second timeouts, giving up on any request that takes
250
+ longer than 30 seconds in total or whose response is larger than 20 MB after decompression. To change how requests are made,
251
+ pass a callable as `:web_requests` instead. prawn-svg provides two:
252
+
253
+ ```ruby
254
+ # ssrf_filter with your own options
255
+ svg data, web_requests: Prawn::SVG::Requests::SsrfFilter.new(http_options: { open_timeout: 5 })
256
+
257
+ # Net::HTTP with no address checks, for trusted SVGs that need internal hosts
258
+ svg data, web_requests: Prawn::SVG::Requests::Unfiltered.new(open_timeout: 5)
259
+ ```
260
+
261
+ `Requests::SsrfFilter` takes [ssrf_filter options](https://github.com/arkadiyt/ssrf_filter#options). Setting a proxy in
262
+ `http_options` bypasses its address checks, and setting `verify_mode` can disable certificate checks.
263
+ `Requests::Unfiltered` takes `max_redirects` (default 10) and Net::HTTP options. Both also take `total_timeout` in seconds
264
+ and `max_response_bytes`.
265
+
266
+ Your own callable is given a `URI` and returns the response body as a string. If the resource can't be loaded, raise
267
+ `Prawn::SVG::Requests::Error` and it's reported as a `:resource` issue; any other error aborts rendering.
268
+ `Prawn::SVG::Requests::Http::EXPECTED_ERRORS` lists the network errors the provided callables rescue.
269
+
270
+ Content fetched from the web can only refer to other web or data URLs, which are resolved against its own URL, so it
271
+ can't read local files even when `:file_requests` is set. Its `<use>` elements can't refer to data
272
+ URLs either.
273
+
274
+ ### File requests
275
+
276
+ A directory path given as `:file_requests` reads files only from under that directory, resolving relative paths
277
+ against it and refusing paths that leave it, including through symlinks. It is very dangerous to use `"/"` if you're
278
+ not fully in control of your input SVG.
279
+
280
+ ```ruby
281
+ # Read files from under a directory
282
+ svg data, file_requests: "/apps/myapp/current/images"
283
+
284
+ # Your own callable, here serving files from memory
285
+ files = { "logo.png" => File.binread("logo.png") }
286
+ svg data, file_requests: ->(path) { files.fetch(path) { raise Prawn::SVG::Requests::Error, "#{path} not found" } }
287
+ ```
288
+
289
+ To change how files are read, pass a callable instead. It is given the decoded path as a string, which may be
290
+ relative, and returns the file's contents as a binary string. As with web requests, raise `Prawn::SVG::Requests::Error`
291
+ to report the file as a `:resource` issue.
292
+
151
293
  ### Fonts
152
294
 
153
295
  By default, prawn-svg has a fonts path of `["/Library/Fonts", "/System/Library/Fonts",
154
- "#{ENV["HOME"]}/Library/Fonts", "/usr/share/fonts/truetype"]` to catch MacOS and Debian Linux users. You can add
155
- to the font path:
296
+ "#{ENV["HOME"]}/Library/Fonts", "/usr/share/fonts/truetype", "/mnt/c/Windows/Fonts"]` to catch MacOS, Debian Linux
297
+ and WSL users. You can add to the font path:
156
298
 
157
299
  ```ruby
158
300
  Prawn::SVG::FontRegistry.font_path << "/my/font/directory"
@@ -162,6 +304,21 @@ to the font path:
162
304
 
163
305
  In your Gemfile, put `gem 'prawn-svg'` before `gem 'prawn-rails'` so that prawn-rails can see the prawn-svg extension.
164
306
 
307
+ ### Deprecated options
308
+
309
+ These are still accepted from earlier versions. If both a deprecated option and its replacement are given, the
310
+ replacement wins.
311
+
312
+ Deprecated | Replacement
313
+ ---------- | -----------
314
+ `:enable_web_requests` | `:web_requests`. Note that web requests are now off by default.
315
+ `:enable_file_requests_with_root` | `:file_requests`
316
+ `:cache_images` | `:cache_requests`. `cache_images: true` is now the default; `cache_images: false` becomes `cache_requests: false`.
317
+ `:log_warnings` | `:log_issues`
318
+ `result[:warnings]` | `result[:issues]`, whose `message`s are the same strings
319
+ `Prawn::SVG::Document::InvalidSVGData` | `Prawn::SVG::InvalidSVGData`
320
+ `Prawn::SVG::Document::Error` | `Prawn::SVG::Error`
321
+
165
322
  ## Licence
166
323
 
167
324
  MIT licence. Copyright Mog Nesbitt.
@@ -0,0 +1,12 @@
1
+ module Prawn::SVG::Angle
2
+ REGEXP = /\A([+-]?\d*(?:\.\d+)?(?:e[+-]?\d+)?)(deg|grad|rad)?\z/i.freeze
3
+ DEGREES_PER_UNIT = { nil => 1, 'deg' => 1, 'grad' => 0.9, 'rad' => 180 / Math::PI }.freeze
4
+
5
+ # Returns the angle in degrees, or nil if it can't be parsed
6
+ def self.parse(value)
7
+ matches = value.strip.match(REGEXP) or return
8
+ number = Prawn::SVG::Number.parse(matches[1]) or return
9
+
10
+ number * DEGREES_PER_UNIT[matches[2]&.downcase]
11
+ end
12
+ end
@@ -0,0 +1,38 @@
1
+ module Prawn::SVG::AttributeValue
2
+ PRESERVE_ASPECT_RATIO_REGEXP = /\A(?:defer\s+)?(?:none|x(?:Min|Mid|Max)Y(?:Min|Mid|Max))(?:\s+(?:meet|slice))?\z/.freeze
3
+
4
+ # Whether prawn-svg can use the value for an attribute of the given type
5
+ def self.valid?(type, value)
6
+ # Keywords are compared exactly where they're used, so must match exactly here too
7
+ return type.include?(value) if type.is_a?(Array)
8
+
9
+ value = value.strip
10
+
11
+ case type
12
+ when :length then length?(value)
13
+ when :number_or_percentage then number?(value) || Prawn::SVG::Percentage.parse(value)
14
+ when :length_list then list(value).all? { |item| length?(item) }
15
+ when :number_list then list(value).all? { |item| number?(item) }
16
+ when :view_box then view_box?(list(value))
17
+ when :preserve_aspect_ratio then value.match?(PRESERVE_ASPECT_RATIO_REGEXP)
18
+ when :orient then value == 'auto' || Prawn::SVG::Angle.parse(value)
19
+ else raise ArgumentError, "Unknown attribute type #{type.inspect}"
20
+ end
21
+ end
22
+
23
+ def self.length?(value)
24
+ Prawn::SVG::Length.parse(value) || Prawn::SVG::Percentage.parse(value)
25
+ end
26
+
27
+ def self.number?(value)
28
+ !Prawn::SVG::Number.parse(value).nil?
29
+ end
30
+
31
+ def self.list(value)
32
+ value.split(Prawn::SVG::Elements::COMMA_WSP_REGEXP)
33
+ end
34
+
35
+ def self.view_box?(values)
36
+ values.length == 4 && values.all? { |item| number?(item) }
37
+ end
38
+ end
@@ -1,13 +1,8 @@
1
1
  module Prawn::SVG::Attributes::ClipPath
2
2
  def parse_clip_path_attribute_and_call
3
- return unless (clip_path = properties.clip_path)
4
- return if clip_path == 'none'
3
+ clip_path_element = extract_element_from_url_id_reference(properties.clip_path, 'clipPath', 'clip-path')
5
4
 
6
- clip_path_element = extract_element_from_url_id_reference(clip_path, 'clipPath')
7
-
8
- if clip_path_element.nil?
9
- document.warnings << 'Could not resolve clip-path URI to a clipPath element'
10
- else
5
+ if clip_path_element
11
6
  clip_calls = clip_path_element.build_clip_calls(self)
12
7
  return if clip_calls.nil?
13
8
 
@@ -26,8 +21,7 @@ module Prawn::SVG::Attributes::ClipPath
26
21
  # then elements are unioned. PDF's W* applies even-odd to the entire combined
27
22
  # path, which incorrectly creates holes between separate shapes. Only use W*
28
23
  # when there's a single child element, where self-intersection matters.
29
- child_elements = clip_path_element.svg_child_elements
30
- if child_elements.length == 1 && clip_path_element.computed_properties.clip_rule == 'evenodd'
24
+ if clip_path_element.drawn_child_count == 1 && clip_path_element.computed_properties.clip_rule == 'evenodd'
31
25
  add_call 'clip', clip_rule: :even_odd
32
26
  else
33
27
  add_call 'clip'
@@ -1,13 +1,8 @@
1
1
  module Prawn::SVG::Attributes::Mask
2
2
  def parse_mask_attribute_and_call
3
- return unless (mask = properties.mask)
4
- return if mask == 'none'
3
+ mask_element = extract_element_from_url_id_reference(properties.mask, 'mask', 'mask')
5
4
 
6
- mask_element = extract_element_from_url_id_reference(mask, 'mask')
7
-
8
- if mask_element.nil?
9
- document.warnings << 'Could not resolve mask URI to a mask element'
10
- else
5
+ if mask_element
11
6
  add_call_and_enter 'save_graphics_state'
12
7
  mask_calls = mask_element.build_mask_calls(self)
13
8
  @calls << ['soft_mask', [], {}, mask_calls]
@@ -31,9 +31,8 @@ module Prawn::SVG::Calculators
31
31
  @output_width = Pixels::Measurement.to_pixels(@document_width || @requested_width, container_width)
32
32
  @output_height = Pixels::Measurement.to_pixels(@document_height || @requested_height, container_height)
33
33
 
34
- if @view_box
35
- values = @view_box.strip.split(Prawn::SVG::Elements::COMMA_WSP_REGEXP)
36
- @x_offset, @y_offset, @viewport_width, @viewport_height = values.map(&:to_f)
34
+ if (view_box = parse_view_box)
35
+ @x_offset, @y_offset, @viewport_width, @viewport_height = view_box
37
36
 
38
37
  if @viewport_width.positive? && @viewport_height.positive?
39
38
  # If neither the width nor height was specified, use the entire width and the viewbox ratio
@@ -63,7 +62,7 @@ module Prawn::SVG::Calculators
63
62
  return if invalid?
64
63
 
65
64
  # SVG 1.1 section 7.10
66
- @viewport_diagonal = Math.sqrt((@viewport_width**2) + (@viewport_height**2)) / Math.sqrt(2)
65
+ @viewport_diagonal = Math.hypot(@viewport_width, @viewport_height) / Math.sqrt(2)
67
66
 
68
67
  if @requested_width
69
68
  scale = @requested_width / @output_width
@@ -84,10 +83,8 @@ module Prawn::SVG::Calculators
84
83
  end
85
84
 
86
85
  def invalid?
87
- @viewport_width <= 0 ||
88
- @viewport_height <= 0 ||
89
- @output_width <= 0 ||
90
- @output_height <= 0 ||
86
+ # Nested percentage sizes can compound beyond what's representable.
87
+ [@viewport_width, @viewport_height, @output_width, @output_height].any? { |size| size <= 0 || !size.finite? } ||
91
88
  (@requested_width && @requested_width <= 0) ||
92
89
  (@requested_height && @requested_height <= 0)
93
90
  end
@@ -99,5 +96,17 @@ module Prawn::SVG::Calculators
99
96
  def requested_height=(value)
100
97
  @requested_height = value&.to_f
101
98
  end
99
+
100
+ def negative?
101
+ [@viewport_width, @viewport_height, @output_width, @output_height, @requested_width, @requested_height].any? { |size| size&.negative? }
102
+ end
103
+
104
+ private
105
+
106
+ def parse_view_box
107
+ return unless @view_box && Prawn::SVG::AttributeValue.valid?(:view_box, @view_box)
108
+
109
+ @view_box.strip.split(Prawn::SVG::Elements::COMMA_WSP_REGEXP).map { |value| Prawn::SVG::Number.parse(value) }
110
+ end
102
111
  end
103
112
  end
@@ -42,16 +42,13 @@ module Prawn::SVG::Calculators::Pixels
42
42
 
43
43
  def percentage_or_proportion(string, default = 0)
44
44
  string = string.to_s.strip
45
- percentage = false
46
45
 
47
- if string[-1] == '%'
48
- percentage = true
49
- string = string[0..-2]
46
+ if (percentage = Prawn::SVG::Percentage.parse(string))
47
+ percentage.to_factor
48
+ elsif (length = Prawn::SVG::Length.parse(string))
49
+ length.to_pixels(nil, computed_properties.numeric_font_size)
50
+ else
51
+ default
50
52
  end
51
-
52
- value = Float(string, exception: false)
53
- return default unless value
54
-
55
- percentage ? value / 100.0 : value
56
53
  end
57
54
  end
@@ -190,7 +190,7 @@ class Prawn::SVG::Color
190
190
  rgb =
191
191
  args.map do |arg|
192
192
  number = to_float(arg, 2.55) or break
193
- format('%02x', number.round.clamp(0, 255))
193
+ format('%02x', number.clamp(0, 255).round)
194
194
  end
195
195
 
196
196
  rgb && RGB.new(rgb.join)
@@ -0,0 +1,109 @@
1
+ module Prawn::SVG::CSS
2
+ # Matches a selector one compound selector at a time, each a single pass over the elements, so the time taken is
3
+ # proportional to the number of elements however the selector's combinators nest.
4
+ class SelectorMatcher
5
+ Node = Struct.new(:element, :parent, :previous, :position, :last, :attributes, :classes, :lang)
6
+
7
+ NTH_CHILD_FORMULA = /\A(?:([+-]?\d*)n)?\s*(?:([+-]?)\s*(\d+))?\z/.freeze
8
+
9
+ # Nodes are indexed breadth first, so each node's parent and previous sibling come before it. Attributes are
10
+ # copied out because REXML walks up to the document on every lookup of an attribute that isn't there.
11
+ def initialize(root)
12
+ @nodes = [new_node(root, nil, nil, 1, true)]
13
+
14
+ @nodes.each_with_index do |node, index|
15
+ children = node.element.children.grep(REXML::Element)
16
+ children.each_with_index do |child, position|
17
+ previous = @nodes.length - 1 unless position.zero?
18
+ @nodes << new_node(child, index, previous, position + 1, position == children.length - 1)
19
+ end
20
+ end
21
+ end
22
+
23
+ def size
24
+ @nodes.length
25
+ end
26
+
27
+ def match(selector)
28
+ matched = selector.reduce(nil) do |previous, compound|
29
+ related = previous ? related(previous, compound[:combinator]) : Array.new(@nodes.length, true)
30
+ pseudo_classes = (compound[:pseudo_class] || []).map { |pseudo_class| compile_pseudo_class(pseudo_class) }
31
+ @nodes.each_with_index.map { |node, index| related[index] && matches?(node, compound, pseudo_classes) }
32
+ end
33
+
34
+ @nodes.select.with_index { |_, index| matched[index] }.map(&:element)
35
+ end
36
+
37
+ private
38
+
39
+ def new_node(element, parent, previous, position, last)
40
+ attributes = {}
41
+ element.attributes.each_attribute { |attribute| attributes[attribute.expanded_name] = attribute.value }
42
+ lang = attributes['xml:lang']&.downcase || (@nodes[parent].lang if parent)
43
+
44
+ Node.new(element, parent, previous, position, last, attributes, attributes['class'].to_s.split.to_set, lang)
45
+ end
46
+
47
+ def related(matched, combinator)
48
+ @nodes.each_with_object([]) do |node, result|
49
+ result << case combinator
50
+ when :child then node.parent && matched[node.parent]
51
+ when :adjacent then node.previous && matched[node.previous]
52
+ when :siblings then node.previous && (matched[node.previous] || result[node.previous])
53
+ else node.parent && (matched[node.parent] || result[node.parent])
54
+ end
55
+ end
56
+ end
57
+
58
+ def matches?(node, compound, pseudo_classes)
59
+ [nil, '*', node.element.name].include?(compound[:name]) &&
60
+ (compound[:id] || []).all? { |id| node.attributes['id'] == id } &&
61
+ (compound[:class] || []).all? { |name| node.classes.include?(name) } &&
62
+ (compound[:attribute] || []).all? { |key, operator, value| attribute_matches?(node.attributes[key], operator, value) } &&
63
+ pseudo_classes.all? { |pseudo_class| pseudo_class.call(node) }
64
+ end
65
+
66
+ def attribute_matches?(actual, operator, value)
67
+ return false if actual.nil?
68
+
69
+ case operator
70
+ when nil then true
71
+ when '=' then actual == value
72
+ when '~=' then actual.split.include?(value)
73
+ when '|=' then actual == value || actual.start_with?("#{value}-")
74
+ when '^=' then !value.empty? && actual.start_with?(value)
75
+ when '$=' then !value.empty? && actual.end_with?(value)
76
+ when '*=' then !value.empty? && actual.include?(value)
77
+ end
78
+ end
79
+
80
+ def compile_pseudo_class(pseudo_class)
81
+ case pseudo_class
82
+ when 'first-child' then ->(node) { node.position == 1 }
83
+ when 'last-child' then lambda(&:last)
84
+ when 'link' then ->(node) { node.attributes.key?('href') || node.attributes.key?('xlink:href') }
85
+ when /\Anth-child\((.*)\)\z/
86
+ a, b = nth_child_formula(Regexp.last_match(1).strip.downcase)
87
+ return ->(_) { false } unless a
88
+
89
+ ->(node) { a.zero? ? node.position == b : ((node.position - b) % a).zero? && (node.position - b) / a >= 0 }
90
+ when /\Alang\((.*)\)\z/
91
+ lang = Regexp.last_match(1).downcase
92
+ ->(node) { node.lang == lang || !!node.lang&.start_with?("#{lang}-") }
93
+ else ->(_) { false }
94
+ end
95
+ end
96
+
97
+ def nth_child_formula(expression)
98
+ match = NTH_CHILD_FORMULA.match({ 'odd' => '2n+1', 'even' => '2n' }.fetch(expression, expression)) or return
99
+
100
+ a = case match[1]
101
+ when nil then 0
102
+ when '', '+' then 1
103
+ when '-' then -1
104
+ else match[1].to_i
105
+ end
106
+ [a, "#{match[2]}#{match[3]}".to_i]
107
+ end
108
+ end
109
+ end
@@ -25,7 +25,7 @@ module Prawn::SVG::CSS
25
25
  end
26
26
  end
27
27
 
28
- result
28
+ result unless result.any? { |compound| (parts = compound.reject { |key, _| key == :combinator }).empty? || parts.values.any?(&:empty?) }
29
29
  end
30
30
 
31
31
  VALID_CSS_IDENTIFIER_CHAR = /[a-zA-Z0-9_\u00a0-\uffff-]/.freeze
@@ -129,6 +129,8 @@ module Prawn::SVG::CSS
129
129
  when Identifier
130
130
  result.last.name << char
131
131
  else
132
+ return if char.match?(/\d/) # identifiers can't start with a digit
133
+
132
134
  result << Modifier.new(:name) unless result.last.is_a?(Modifier)
133
135
  result << Identifier.new(char)
134
136
  end