rustyprint 1.0.1-x86_64-linux-musl
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.
- checksums.yaml +7 -0
- data/.yardopts +5 -0
- data/LICENSE-APACHE +176 -0
- data/LICENSE-MIT +21 -0
- data/OFL.txt +93 -0
- data/README.md +103 -0
- data/lib/rustyprint/asset_collector.rb +93 -0
- data/lib/rustyprint/errors.rb +42 -0
- data/lib/rustyprint/native/librustyprint_ffi.so +0 -0
- data/lib/rustyprint/native.rb +47 -0
- data/lib/rustyprint/pdf_renderer.rb +98 -0
- data/lib/rustyprint/railtie.rb +17 -0
- data/lib/rustyprint/version.rb +6 -0
- data/lib/rustyprint.rb +160 -0
- metadata +70 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: a3e0dfdb65a26d83d70076e9a62ae9c7a60025fe247670d77839fc10db006e69
|
|
4
|
+
data.tar.gz: bd00cbe151125aa267a9a692218ff5a8e1cfe9b9b4abdcc1a6f6bcf264d1cc10
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 0fb682c2df5ee2132926a393e746328a1b1f169c1adfd805758a8fa14d03f8b25fdc76145a436cc14e1ccee9d826606249ca00dc4ff5c83dde8c4167effd71b7
|
|
7
|
+
data.tar.gz: 3cce9af5b3062fb7c3528909a8a75765820f905e35f6390cc4c8a4d5f404650a07b7709cb75a3401eb3245d1cf4a1c8e8555672bf43a9998ca41e3b0c1dcbc89
|
data/.yardopts
ADDED
data/LICENSE-APACHE
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
data/LICENSE-MIT
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ryan Verschuren
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
data/OFL.txt
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
Copyright 2022 The Noto Project Authors (https://github.com/notofonts/latin-greek-cyrillic)
|
|
2
|
+
|
|
3
|
+
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
|
4
|
+
This license is copied below, and is also available with a FAQ at:
|
|
5
|
+
https://scripts.sil.org/OFL
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
-----------------------------------------------------------
|
|
9
|
+
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
|
10
|
+
-----------------------------------------------------------
|
|
11
|
+
|
|
12
|
+
PREAMBLE
|
|
13
|
+
The goals of the Open Font License (OFL) are to stimulate worldwide
|
|
14
|
+
development of collaborative font projects, to support the font creation
|
|
15
|
+
efforts of academic and linguistic communities, and to provide a free and
|
|
16
|
+
open framework in which fonts may be shared and improved in partnership
|
|
17
|
+
with others.
|
|
18
|
+
|
|
19
|
+
The OFL allows the licensed fonts to be used, studied, modified and
|
|
20
|
+
redistributed freely as long as they are not sold by themselves. The
|
|
21
|
+
fonts, including any derivative works, can be bundled, embedded,
|
|
22
|
+
redistributed and/or sold with any software provided that any reserved
|
|
23
|
+
names are not used by derivative works. The fonts and derivatives,
|
|
24
|
+
however, cannot be released under any other type of license. The
|
|
25
|
+
requirement for fonts to remain under this license does not apply
|
|
26
|
+
to any document created using the fonts or their derivatives.
|
|
27
|
+
|
|
28
|
+
DEFINITIONS
|
|
29
|
+
"Font Software" refers to the set of files released by the Copyright
|
|
30
|
+
Holder(s) under this license and clearly marked as such. This may
|
|
31
|
+
include source files, build scripts and documentation.
|
|
32
|
+
|
|
33
|
+
"Reserved Font Name" refers to any names specified as such after the
|
|
34
|
+
copyright statement(s).
|
|
35
|
+
|
|
36
|
+
"Original Version" refers to the collection of Font Software components as
|
|
37
|
+
distributed by the Copyright Holder(s).
|
|
38
|
+
|
|
39
|
+
"Modified Version" refers to any derivative made by adding to, deleting,
|
|
40
|
+
or substituting -- in part or in whole -- any of the components of the
|
|
41
|
+
Original Version, by changing formats or by porting the Font Software to a
|
|
42
|
+
new environment.
|
|
43
|
+
|
|
44
|
+
"Author" refers to any designer, engineer, programmer, technical
|
|
45
|
+
writer or other person who contributed to the Font Software.
|
|
46
|
+
|
|
47
|
+
PERMISSION & CONDITIONS
|
|
48
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
49
|
+
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
|
50
|
+
redistribute, and sell modified and unmodified copies of the Font
|
|
51
|
+
Software, subject to the following conditions:
|
|
52
|
+
|
|
53
|
+
1) Neither the Font Software nor any of its individual components,
|
|
54
|
+
in Original or Modified Versions, may be sold by itself.
|
|
55
|
+
|
|
56
|
+
2) Original or Modified Versions of the Font Software may be bundled,
|
|
57
|
+
redistributed and/or sold with any software, provided that each copy
|
|
58
|
+
contains the above copyright notice and this license. These can be
|
|
59
|
+
included either as stand-alone text files, human-readable headers or
|
|
60
|
+
in the appropriate machine-readable metadata fields within text or
|
|
61
|
+
binary files as long as those fields can be easily viewed by the user.
|
|
62
|
+
|
|
63
|
+
3) No Modified Version of the Font Software may use the Reserved Font
|
|
64
|
+
Name(s) unless explicit written permission is granted by the corresponding
|
|
65
|
+
Copyright Holder. This restriction only applies to the primary font name as
|
|
66
|
+
presented to the users.
|
|
67
|
+
|
|
68
|
+
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
|
69
|
+
Software shall not be used to promote, endorse or advertise any
|
|
70
|
+
Modified Version, except to acknowledge the contribution(s) of the
|
|
71
|
+
Copyright Holder(s) and the Author(s) or with their explicit written
|
|
72
|
+
permission.
|
|
73
|
+
|
|
74
|
+
5) The Font Software, modified or unmodified, in part or in whole,
|
|
75
|
+
must be distributed entirely under this license, and must not be
|
|
76
|
+
distributed under any other license. The requirement for fonts to
|
|
77
|
+
remain under this license does not apply to any document created
|
|
78
|
+
using the Font Software.
|
|
79
|
+
|
|
80
|
+
TERMINATION
|
|
81
|
+
This license becomes null and void if any of the above conditions are
|
|
82
|
+
not met.
|
|
83
|
+
|
|
84
|
+
DISCLAIMER
|
|
85
|
+
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
86
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
|
87
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
|
88
|
+
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
|
89
|
+
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
90
|
+
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
|
91
|
+
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
92
|
+
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
|
93
|
+
OTHER DEALINGS IN THE FONT SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# rustyprint for Ruby
|
|
2
|
+
|
|
3
|
+
Renders HTML and CSS to PDF with [rustyprint](https://github.com/vryan95/rustyprint), a layout engine of its own written in Rust. It needs no browser, no external runtime and no network access, and the fonts it needs are built in.
|
|
4
|
+
|
|
5
|
+
```ruby
|
|
6
|
+
gem "rustyprint"
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Ruby 3.2 or newer. Each platform has a gem with the native library built in: Linux (glibc and musl) and macOS on x64 and arm64, and Windows (RubyInstaller, UCRT) on x64 and arm64.
|
|
10
|
+
|
|
11
|
+
## Render
|
|
12
|
+
|
|
13
|
+
The API documentation, built from the gem's doc comments, is at [rubydoc.info/gems/rustyprint](https://rubydoc.info/gems/rustyprint).
|
|
14
|
+
|
|
15
|
+
```ruby
|
|
16
|
+
require "rustyprint"
|
|
17
|
+
|
|
18
|
+
output = Rustyprint.render(html, page_size: "A4", margin: "15mm", title: "Invoice 42",
|
|
19
|
+
assets: { "logo.png" => File.binread("logo.png"),
|
|
20
|
+
"invoice.css" => Pathname("app/pdf/invoice.css") })
|
|
21
|
+
File.binwrite("invoice.pdf", output.pdf)
|
|
22
|
+
output.warnings # => ["invoice.css:12: unsupported property `colr`"]
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
`render` returns a `Rustyprint::Output` with `pdf`, a binary String, and `warnings`, problems found in the document's CSS and assets, as an Array of Strings.
|
|
26
|
+
|
|
27
|
+
**Options** are keywords, the JSON options every rustyprint front end shares ([schema/render-options.schema.json](../../schema/render-options.schema.json)):
|
|
28
|
+
|
|
29
|
+
| Option | Example | Default |
|
|
30
|
+
| --- | --- | --- |
|
|
31
|
+
| `page_size` | `"Letter"`, or `{ width: "100mm", height: "150mm" }` | `"A4"` |
|
|
32
|
+
| `landscape` | `true` | `false` |
|
|
33
|
+
| `margin` | `"15mm"`, `"10mm 20mm"` | `"2cm"` |
|
|
34
|
+
| `title` | `"Invoice 42"` | the document's `<title>` |
|
|
35
|
+
| `stylesheet` | `"body { font-family: sans-serif }"` | none |
|
|
36
|
+
| `remote` | `{ allowed_hosts: ["cdn.example.com"] }` | nothing fetched |
|
|
37
|
+
| `limits` | `{ max_pages: 50, timeout_ms: 10_000 }` | 20 MB of HTML, 500,000 nodes, 2,000 pages, 60 s |
|
|
38
|
+
|
|
39
|
+
**Assets** are the files the document refers to by relative or root-relative URL: stylesheets, images, fonts and `iframe` documents. Give each by the path the HTML uses, without a leading slash (`/assets/app.css` is the asset `assets/app.css`), as a String, a Pathname or an IO. Nothing else is read, and nothing is fetched from the network unless `remote` allows the host.
|
|
40
|
+
|
|
41
|
+
**Errors** are `Rustyprint::Error` subclasses, each with a `kind`:
|
|
42
|
+
|
|
43
|
+
| Class | `kind` | When |
|
|
44
|
+
| --- | --- | --- |
|
|
45
|
+
| `Rustyprint::InvalidOptionsError` | `:invalid_options` | An unknown option, or an invalid value |
|
|
46
|
+
| `Rustyprint::LimitExceededError` | `:limit_exceeded` | The document exceeds a limit |
|
|
47
|
+
| `Rustyprint::TimeoutError` | `:timeout` | Rendering took longer than the deadline |
|
|
48
|
+
| `Rustyprint::InternalError` | `:internal` | A bug in rustyprint |
|
|
49
|
+
|
|
50
|
+
HTML that is not valid in its encoding raises `ArgumentError`. HTML in another encoding is converted to UTF-8.
|
|
51
|
+
|
|
52
|
+
**Threads:** a render releases the GVL, so other threads run meanwhile, and renders on several threads run at once.
|
|
53
|
+
|
|
54
|
+
## In Rails
|
|
55
|
+
|
|
56
|
+
In a Rails app the gem adds `render pdf:` to controllers. It renders the view to HTML, as `render_to_string` does, and sends the PDF:
|
|
57
|
+
|
|
58
|
+
```ruby
|
|
59
|
+
def show
|
|
60
|
+
@invoice = Invoice.find(params[:id])
|
|
61
|
+
|
|
62
|
+
respond_to do |format|
|
|
63
|
+
format.html { render layout: "pdf" }
|
|
64
|
+
format.pdf do
|
|
65
|
+
render pdf: "invoice #{@invoice.id}",
|
|
66
|
+
template: "invoices/show",
|
|
67
|
+
layout: "pdf",
|
|
68
|
+
disposition: "inline",
|
|
69
|
+
formats: [:html]
|
|
70
|
+
end
|
|
71
|
+
end
|
|
72
|
+
end
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
- `pdf` names the file; `.pdf` is added.
|
|
76
|
+
- `disposition` is `"inline"`, the default, or `"attachment"`.
|
|
77
|
+
- `formats` defaults to `[:html]`. `template`, `layout`, `locals` and the rest are passed on to `render_to_string`.
|
|
78
|
+
- The render options, such as `page_size: "Letter"` or `margin: "15mm"`, are the same as for `Rustyprint.render`.
|
|
79
|
+
|
|
80
|
+
The view uses the usual helpers, such as `stylesheet_link_tag` and `image_tag`. The stylesheets, images and fonts the HTML and its stylesheets refer to by path are read from `public/`, where precompiled assets are. Anything not found there is fetched from the app's asset pipeline, as Propshaft or Sprockets serves it in development. `assets:` adds files of your own, by the path the HTML uses.
|
|
81
|
+
|
|
82
|
+
Each render is instrumented as `render.rustyprint`, with the asset paths and the warnings, and the warnings are logged.
|
|
83
|
+
|
|
84
|
+
When `config.asset_host` is set, asset URLs point at another host. The renderer only fetches from hosts that `remote:` allows, so leave `asset_host` unset for PDF views.
|
|
85
|
+
|
|
86
|
+
[demos/rails](../../demos/rails) is a Rails app that does this. It also has pages that compare the sample documents with how a browser shows them.
|
|
87
|
+
|
|
88
|
+
## Develop
|
|
89
|
+
|
|
90
|
+
From this directory, with Rust installed:
|
|
91
|
+
|
|
92
|
+
```sh
|
|
93
|
+
bundle install
|
|
94
|
+
bundle exec rake # builds the native library with Cargo, runs the specs, then checks the documentation
|
|
95
|
+
bundle exec rake compile # only builds the library, into lib/rustyprint/native
|
|
96
|
+
bundle exec rake docs # fails unless every public class, method and constant is documented
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
`RUSTYPRINT_LIBRARY` points the gem at a library somewhere else. `rake native PLATFORM=x86_64-linux-gnu LIBRARY=path` builds a platform gem around a library, as the release workflow does for every platform.
|
|
100
|
+
|
|
101
|
+
## License
|
|
102
|
+
|
|
103
|
+
MIT or Apache-2.0, at your option ([LICENSE-MIT](https://github.com/vryan95/rustyprint/blob/master/LICENSE-MIT), [LICENSE-APACHE](https://github.com/vryan95/rustyprint/blob/master/LICENSE-APACHE)). The fonts built into the native library are under the SIL Open Font License ([OFL.txt](https://github.com/vryan95/rustyprint/blob/master/fonts/OFL.txt)). The gem carries all three.
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "cgi"
|
|
4
|
+
|
|
5
|
+
module Rustyprint
|
|
6
|
+
# Finds the files an HTML document refers to, in its tags, its style attributes and blocks,
|
|
7
|
+
# and the stylesheets it loads, and fetches each once, for {Rustyprint.render}'s assets.
|
|
8
|
+
#
|
|
9
|
+
# @example
|
|
10
|
+
# collector = AssetCollector.new { |path| File.binread("public#{path}") if File.file?("public#{path}") }
|
|
11
|
+
# collector.collect(html) # => { "assets/app-1a2b.css" => "...", "images/logo.png" => "..." }
|
|
12
|
+
#
|
|
13
|
+
# The block gets a root-relative path, such as "/assets/app-1a2b.css", and returns the file's
|
|
14
|
+
# contents, or nil if there is none. The result maps the path the document uses, without its
|
|
15
|
+
# leading slash, to the contents. Remote and data: URLs are left to the renderer.
|
|
16
|
+
class AssetCollector
|
|
17
|
+
TAG = %r{<([a-zA-Z][\w-]*)((?:\s+[^\s=>/]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))?)*)\s*/?>}
|
|
18
|
+
ATTRIBUTE = %r{([^\s=>/]+)(?:\s*=\s*("[^"]*"|'[^']*'|[^\s>]+))?}
|
|
19
|
+
STYLE_BLOCK = %r{<style\b[^>]*>(.*?)</style>}mi
|
|
20
|
+
CSS_COMMENT = %r{/\*.*?\*/}m
|
|
21
|
+
CSS_URL = /url\(\s*(?:"([^"]*)"|'([^']*)'|([^)\s]*))\s*\)|@import\s+(?:"([^"]*)"|'([^']*)')/i
|
|
22
|
+
URL_ATTRIBUTES = %w[src poster data].freeze
|
|
23
|
+
STYLESHEET = /\A\s*(\S+\s+)*stylesheet(\s+\S+)*\s*\z/i
|
|
24
|
+
private_constant :TAG, :ATTRIBUTE, :STYLE_BLOCK, :CSS_COMMENT, :CSS_URL, :URL_ATTRIBUTES, :STYLESHEET
|
|
25
|
+
|
|
26
|
+
# @yieldparam path [String] a root-relative path the document uses, such as
|
|
27
|
+
# `"/assets/app-1a2b.css"`
|
|
28
|
+
# @yieldreturn [String, nil] the file's contents, or nil if there is none
|
|
29
|
+
def initialize(&fetch)
|
|
30
|
+
@fetch = fetch
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# The files the document refers to.
|
|
34
|
+
#
|
|
35
|
+
# @param html [String] the document
|
|
36
|
+
# @return [Hash{String => String}] each file's contents, by the path the document uses for it,
|
|
37
|
+
# without its leading slash
|
|
38
|
+
def collect(html)
|
|
39
|
+
@assets = {}
|
|
40
|
+
@seen = {}
|
|
41
|
+
html.scan(STYLE_BLOCK) { |(css)| collect_css(css) }
|
|
42
|
+
html.scan(TAG) { |name, attributes| collect_tag(name.downcase, attributes) }
|
|
43
|
+
@assets
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
private
|
|
47
|
+
|
|
48
|
+
def collect_tag(name, attributes)
|
|
49
|
+
attributes = attributes.scan(ATTRIBUTE).to_h do |key, value|
|
|
50
|
+
[key.downcase, CGI.unescapeHTML(value.to_s.delete_prefix('"').delete_prefix("'").chomp('"').chomp("'"))]
|
|
51
|
+
end
|
|
52
|
+
URL_ATTRIBUTES.each { |key| add(attributes[key]) if attributes[key] }
|
|
53
|
+
attributes["srcset"]&.split(",")&.each { |candidate| add(candidate.split.first) }
|
|
54
|
+
collect_css(attributes["style"]) if attributes["style"]
|
|
55
|
+
add(attributes["href"], stylesheet: true) if name == "link" && STYLESHEET.match?(attributes["rel"].to_s)
|
|
56
|
+
add(attributes["href"]) if %w[image use].include?(name) && attributes["href"]
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
def collect_css(css)
|
|
60
|
+
css.gsub(CSS_COMMENT, "").scan(CSS_URL) do |url, *rest|
|
|
61
|
+
import = rest[2] || rest[3]
|
|
62
|
+
add(url || rest[0] || rest[1] || import, stylesheet: !import.nil?)
|
|
63
|
+
end
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
def add(url, stylesheet: false)
|
|
67
|
+
path = asset_path(url) or return
|
|
68
|
+
return if @seen.key?(path)
|
|
69
|
+
|
|
70
|
+
@seen[path] = true
|
|
71
|
+
data = @fetch.call("/#{path}") or return
|
|
72
|
+
key = decode(path)
|
|
73
|
+
@assets[key] = data
|
|
74
|
+
collect_css(data.dup.force_encoding(Encoding::UTF_8).scrub) if stylesheet || key.end_with?(".css")
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
# The URL's path from the document's root, as the renderer resolves it, or nil for remote,
|
|
78
|
+
# data: and fragment-only URLs and paths that leave the root.
|
|
79
|
+
def asset_path(url)
|
|
80
|
+
url = url.to_s.strip.split(/[?#]/, 2).first.to_s
|
|
81
|
+
return if url.empty? || url.start_with?("//", "\\") || url.match?(/\A[a-z][a-z\d+.-]*:/i)
|
|
82
|
+
|
|
83
|
+
segments = url.split("/").reject { |segment| segment.empty? || segment == "." }
|
|
84
|
+
return if segments.empty? || segments.include?("..")
|
|
85
|
+
|
|
86
|
+
segments.join("/")
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
def decode(path)
|
|
90
|
+
path.b.gsub(/%\h\h/n) { |escape| escape[1..].hex.chr }.force_encoding(Encoding::UTF_8)
|
|
91
|
+
end
|
|
92
|
+
end
|
|
93
|
+
end
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Rustyprint
|
|
4
|
+
# A render that failed. Each kind of failure has its own subclass, so rescue
|
|
5
|
+
# {Rustyprint::Error} for every failure, or a subclass for one kind.
|
|
6
|
+
class Error < StandardError
|
|
7
|
+
# @return [Symbol] the kind of failure: `:invalid_options`, `:limit_exceeded`, `:timeout` or
|
|
8
|
+
# `:internal`
|
|
9
|
+
attr_reader :kind
|
|
10
|
+
|
|
11
|
+
# @param message [String, nil] what went wrong
|
|
12
|
+
# @param kind [Symbol] the kind of failure; the subclass's `KIND` by default
|
|
13
|
+
def initialize(message = nil, kind: self.class::KIND)
|
|
14
|
+
super(message)
|
|
15
|
+
@kind = kind
|
|
16
|
+
end
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
# The options are not valid, such as an unknown option or page size.
|
|
20
|
+
class InvalidOptionsError < Error
|
|
21
|
+
# The {Error#kind} of this class's errors.
|
|
22
|
+
KIND = :invalid_options
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
# The document exceeds one of the limits in the options.
|
|
26
|
+
class LimitExceededError < Error
|
|
27
|
+
# The {Error#kind} of this class's errors.
|
|
28
|
+
KIND = :limit_exceeded
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# Rendering took longer than the deadline in the options.
|
|
32
|
+
class TimeoutError < Error
|
|
33
|
+
# The {Error#kind} of this class's errors.
|
|
34
|
+
KIND = :timeout
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# A bug in rustyprint.
|
|
38
|
+
class InternalError < Error
|
|
39
|
+
# The {Error#kind} of this class's errors.
|
|
40
|
+
KIND = :internal
|
|
41
|
+
end
|
|
42
|
+
end
|
|
Binary file
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "ffi"
|
|
4
|
+
|
|
5
|
+
module Rustyprint
|
|
6
|
+
# The native library's C ABI (crates/rustyprint-ffi/include/rustyprint.h).
|
|
7
|
+
#
|
|
8
|
+
# @private
|
|
9
|
+
module Native
|
|
10
|
+
extend FFI::Library
|
|
11
|
+
|
|
12
|
+
# The library's file name on this platform.
|
|
13
|
+
def self.file_name
|
|
14
|
+
case RbConfig::CONFIG["host_os"]
|
|
15
|
+
when /mswin|mingw|cygwin/ then "rustyprint_ffi.dll"
|
|
16
|
+
when /darwin/ then "librustyprint_ffi.dylib"
|
|
17
|
+
else "librustyprint_ffi.so"
|
|
18
|
+
end
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
# Where the library is: RUSTYPRINT_LIBRARY if set, else the copy in the gem, which a
|
|
22
|
+
# platform gem ships and `rake compile` builds.
|
|
23
|
+
def self.path
|
|
24
|
+
ENV.fetch("RUSTYPRINT_LIBRARY") { File.expand_path("native/#{file_name}", __dir__) }
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
unless File.exist?(path)
|
|
28
|
+
raise LoadError, "rustyprint's native library is missing at #{path}. Install a platform gem of " \
|
|
29
|
+
"rustyprint, run `rake compile` in bindings/ruby, or set RUSTYPRINT_LIBRARY."
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
ffi_lib path
|
|
33
|
+
|
|
34
|
+
Status = enum(:status, %i[ok invalid_argument invalid_options limit_exceeded timeout internal])
|
|
35
|
+
|
|
36
|
+
attach_function :rp_version, [], :string
|
|
37
|
+
attach_function :rp_request_new, %i[pointer size_t], :pointer
|
|
38
|
+
attach_function :rp_request_add_asset, %i[pointer string pointer size_t], :status
|
|
39
|
+
# Renders release the GVL, so other Ruby threads run meanwhile.
|
|
40
|
+
attach_function :rp_render, %i[pointer pointer size_t pointer], :status, blocking: true
|
|
41
|
+
attach_function :rp_result_pdf, %i[pointer pointer], :pointer
|
|
42
|
+
attach_function :rp_result_warnings_json, %i[pointer pointer], :pointer
|
|
43
|
+
attach_function :rp_result_error, %i[pointer pointer], :pointer
|
|
44
|
+
attach_function :rp_result_free, [:pointer], :void
|
|
45
|
+
attach_function :rp_request_free, [:pointer], :void
|
|
46
|
+
end
|
|
47
|
+
end
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "rack/mock_request"
|
|
4
|
+
require_relative "asset_collector"
|
|
5
|
+
|
|
6
|
+
module Rustyprint
|
|
7
|
+
# Renders a controller's view to PDF, for `render pdf:`.
|
|
8
|
+
#
|
|
9
|
+
# @example
|
|
10
|
+
# format.pdf do
|
|
11
|
+
# render pdf: "invoice #{@invoice.id}", template: "invoices/show", layout: "pdf",
|
|
12
|
+
# page_size: "A4", margin: "15mm", disposition: "attachment"
|
|
13
|
+
# end
|
|
14
|
+
#
|
|
15
|
+
# The view renders as HTML, unless `formats` says otherwise, with the other options a
|
|
16
|
+
# `render` takes, such as `template`, `layout` and `locals`. The PDF options are those of
|
|
17
|
+
# {Rustyprint.render}. `pdf` names the file, with `.pdf` added, and `disposition` is "inline"
|
|
18
|
+
# (the default) or "attachment".
|
|
19
|
+
#
|
|
20
|
+
# The stylesheets, images and fonts the HTML refers to by path, such as those
|
|
21
|
+
# `stylesheet_link_tag` and `image_tag` give, are read from `public/` or else served by the
|
|
22
|
+
# app's asset pipeline. `assets` adds files of your own, by the path the HTML uses. Each
|
|
23
|
+
# render is instrumented as "render.rustyprint", with the asset paths and warnings.
|
|
24
|
+
class PdfRenderer
|
|
25
|
+
# The options of `render pdf:` that go to {Rustyprint.render}; the others go to the view.
|
|
26
|
+
PDF_OPTIONS = %i[page_size landscape margin title stylesheet remote limits].freeze
|
|
27
|
+
|
|
28
|
+
# @param controller [ActionController::Base] the controller whose view to render
|
|
29
|
+
def initialize(controller)
|
|
30
|
+
@controller = controller
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# Renders the view to PDF and sets the response's content type and disposition.
|
|
34
|
+
#
|
|
35
|
+
# @param name [String, Symbol] the file name, with `.pdf` added if it lacks it
|
|
36
|
+
# @param options [Hash] the options of `render pdf:`
|
|
37
|
+
# @return [String] the PDF, for the response's body
|
|
38
|
+
def render(name, options)
|
|
39
|
+
view = options.except(:pdf, :assets, :disposition, *PDF_OPTIONS)
|
|
40
|
+
view[:formats] ||= [:html]
|
|
41
|
+
html = @controller.render_to_string(view)
|
|
42
|
+
|
|
43
|
+
payload = { name: name.to_s }
|
|
44
|
+
output = ActiveSupport::Notifications.instrument("render.rustyprint", payload) do
|
|
45
|
+
assets = collect(html).merge(options.fetch(:assets, {}).transform_keys(&:to_s))
|
|
46
|
+
payload[:assets] = assets.keys
|
|
47
|
+
Rustyprint.render(html, assets: assets, **options.slice(*PDF_OPTIONS)).tap do |rendered|
|
|
48
|
+
payload[:warnings] = rendered.warnings
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
output.warnings.each { |warning| @controller.logger&.warn("rustyprint: #{warning}") }
|
|
52
|
+
|
|
53
|
+
@controller.response.charset = false
|
|
54
|
+
@controller.content_type = Mime[:pdf]
|
|
55
|
+
@controller.headers["Content-Disposition"] = ActionDispatch::Http::ContentDisposition.format(
|
|
56
|
+
disposition: options.fetch(:disposition, "inline").to_s, filename: file_name(name)
|
|
57
|
+
)
|
|
58
|
+
output.pdf
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
private
|
|
62
|
+
|
|
63
|
+
def file_name(name)
|
|
64
|
+
name = name.to_s
|
|
65
|
+
name.end_with?(".pdf") ? name : "#{name}.pdf"
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
def collect(html)
|
|
69
|
+
AssetCollector.new { |path| public_file(path) || pipeline_file(path) }.collect(html)
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
# A file under public/, such as a precompiled asset.
|
|
73
|
+
def public_file(path)
|
|
74
|
+
file = ::Rails.public_path.join(path.delete_prefix("/"))
|
|
75
|
+
File.binread(file) if file.file?
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# A file the app's asset pipeline serves, as Propshaft and Sprockets do in development.
|
|
79
|
+
def pipeline_file(path)
|
|
80
|
+
config = ::Rails.application.config
|
|
81
|
+
prefix = config.respond_to?(:assets) ? config.assets.prefix : "/assets"
|
|
82
|
+
return unless path.start_with?("#{prefix}/")
|
|
83
|
+
|
|
84
|
+
request = @controller.request
|
|
85
|
+
# The request's host, so the app's host authorization allows it as it did the request.
|
|
86
|
+
env = Rack::MockRequest.env_for("#{request.protocol}#{request.host_with_port}#{path}",
|
|
87
|
+
"HTTP_HOST" => request.host_with_port)
|
|
88
|
+
status, _headers, body = ::Rails.application.call(env)
|
|
89
|
+
return unless status == 200
|
|
90
|
+
|
|
91
|
+
data = +""
|
|
92
|
+
body.each { |chunk| data << chunk }
|
|
93
|
+
data
|
|
94
|
+
ensure
|
|
95
|
+
body.close if body.respond_to?(:close)
|
|
96
|
+
end
|
|
97
|
+
end
|
|
98
|
+
end
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "rails/railtie"
|
|
4
|
+
require_relative "pdf_renderer"
|
|
5
|
+
|
|
6
|
+
module Rustyprint
|
|
7
|
+
# Adds `render pdf:` to Rails controllers. Loaded when the gem is required after Rails.
|
|
8
|
+
class Railtie < ::Rails::Railtie
|
|
9
|
+
initializer "rustyprint.renderer" do
|
|
10
|
+
ActiveSupport.on_load(:action_controller) do
|
|
11
|
+
ActionController::Renderers.add(:pdf) do |name, options|
|
|
12
|
+
Rustyprint::PdfRenderer.new(self).render(name, options)
|
|
13
|
+
end
|
|
14
|
+
end
|
|
15
|
+
end
|
|
16
|
+
end
|
|
17
|
+
end
|
data/lib/rustyprint.rb
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require_relative "rustyprint/version"
|
|
5
|
+
require_relative "rustyprint/errors"
|
|
6
|
+
require_relative "rustyprint/native"
|
|
7
|
+
require_relative "rustyprint/railtie" if defined?(Rails::Railtie)
|
|
8
|
+
|
|
9
|
+
# Renders HTML and CSS to PDF.
|
|
10
|
+
#
|
|
11
|
+
# @example
|
|
12
|
+
# output = Rustyprint.render(html, page_size: "A4", margin: "15mm",
|
|
13
|
+
# assets: { "logo.png" => File.binread("logo.png") })
|
|
14
|
+
# File.binwrite("invoice.pdf", output.pdf)
|
|
15
|
+
module Rustyprint
|
|
16
|
+
# A rendered document, as {Rustyprint.render} returns it.
|
|
17
|
+
#
|
|
18
|
+
# @!attribute [r] pdf
|
|
19
|
+
# @return [String] the PDF, a binary String
|
|
20
|
+
# @!attribute [r] warnings
|
|
21
|
+
# @return [Array<String>] problems found in the document's CSS and assets, such as
|
|
22
|
+
# ``"invoice.css:12: unsupported property `colr`"``
|
|
23
|
+
Output = Data.define(:pdf, :warnings)
|
|
24
|
+
|
|
25
|
+
ERRORS = {
|
|
26
|
+
invalid_options: InvalidOptionsError,
|
|
27
|
+
limit_exceeded: LimitExceededError,
|
|
28
|
+
timeout: TimeoutError
|
|
29
|
+
}.freeze
|
|
30
|
+
private_constant :ERRORS
|
|
31
|
+
|
|
32
|
+
class << self
|
|
33
|
+
# Renders an HTML document to PDF.
|
|
34
|
+
#
|
|
35
|
+
# The options are those of
|
|
36
|
+
# [render-options.schema.json](https://github.com/vryan95/rustyprint/blob/master/schema/render-options.schema.json),
|
|
37
|
+
# as keywords. An option left out keeps its default. Nothing is read but the assets, and
|
|
38
|
+
# nothing is fetched from the network unless `remote` allows the host. Rendering releases the
|
|
39
|
+
# GVL, so other threads run meanwhile, and renders on several threads run at once.
|
|
40
|
+
#
|
|
41
|
+
# @example A4 with a logo and a stylesheet
|
|
42
|
+
# output = Rustyprint.render(html, page_size: "A4", margin: "15mm", title: "Invoice 42",
|
|
43
|
+
# assets: { "logo.png" => File.binread("logo.png"),
|
|
44
|
+
# "invoice.css" => Pathname("app/pdf/invoice.css") })
|
|
45
|
+
# File.binwrite("invoice.pdf", output.pdf)
|
|
46
|
+
#
|
|
47
|
+
# @param html [String] the document, in any encoding Ruby can convert to UTF-8
|
|
48
|
+
# @param assets [Hash{String => String, Pathname, IO}] the files the document refers to by
|
|
49
|
+
# relative or root-relative URL, by the path it uses without a leading slash (`/css/app.css`
|
|
50
|
+
# is `"css/app.css"`): their contents as a String, a Pathname to read, or an IO to read
|
|
51
|
+
# @param options [Hash] the render options
|
|
52
|
+
# @option options [String, Hash] :page_size `"A4"` (the default), `"Letter"` or another named
|
|
53
|
+
# size, or `{ width: "100mm", height: "150mm" }`
|
|
54
|
+
# @option options [Boolean] :landscape turns the page so that it is wider than it is tall;
|
|
55
|
+
# `false` by default
|
|
56
|
+
# @option options [String] :margin the page margins, as CSS: `"15mm"` or `"10mm 20mm"`;
|
|
57
|
+
# `"2cm"` by default
|
|
58
|
+
# @option options [String] :title the PDF's title; the document's `<title>` by default
|
|
59
|
+
# @option options [String] :stylesheet CSS applied after the document's own
|
|
60
|
+
# @option options [Hash] :remote the hosts to fetch from, such as
|
|
61
|
+
# `{ allowed_hosts: ["cdn.example.com"] }`; nothing is fetched by default
|
|
62
|
+
# @option options [Hash] :limits bounds on the render, such as
|
|
63
|
+
# `{ max_pages: 50, timeout_ms: 10_000 }`; by default 20 MB of HTML, 500,000 nodes, 2,000
|
|
64
|
+
# pages and 60 seconds. Exceeding one fails the render, except that larger images are
|
|
65
|
+
# skipped with a warning
|
|
66
|
+
# @return [Output] the PDF and the warnings
|
|
67
|
+
# @raise [ArgumentError] if the HTML or an asset path is not valid in its encoding, or an asset
|
|
68
|
+
# path is not valid
|
|
69
|
+
# @raise [InvalidOptionsError] if an option is unknown or has an invalid value
|
|
70
|
+
# @raise [LimitExceededError] if the document exceeds a limit
|
|
71
|
+
# @raise [TimeoutError] if rendering takes longer than the deadline
|
|
72
|
+
# @raise [InternalError] if rustyprint has a bug
|
|
73
|
+
def render(html, assets: {}, **options)
|
|
74
|
+
html = utf8(html, "html")
|
|
75
|
+
with_request(options) do |request|
|
|
76
|
+
assets.each { |path, data| add_asset(request, path, data) }
|
|
77
|
+
render_request(request, html)
|
|
78
|
+
end
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# The native library's version.
|
|
82
|
+
#
|
|
83
|
+
# @return [String] the version, the same as {VERSION}
|
|
84
|
+
def native_version
|
|
85
|
+
Native.rp_version
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
private
|
|
89
|
+
|
|
90
|
+
def utf8(text, what)
|
|
91
|
+
text = String(text)
|
|
92
|
+
raise ArgumentError, "#{what} is not valid #{text.encoding}" unless text.valid_encoding?
|
|
93
|
+
|
|
94
|
+
text = text.encode(Encoding::UTF_8)
|
|
95
|
+
raise ArgumentError, "#{what} is not valid UTF-8" unless text.valid_encoding?
|
|
96
|
+
|
|
97
|
+
text
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
def bytes(text)
|
|
101
|
+
pointer = FFI::MemoryPointer.new(:char, [text.bytesize, 1].max)
|
|
102
|
+
pointer.put_bytes(0, text)
|
|
103
|
+
pointer
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
def with_request(options)
|
|
107
|
+
json = JSON.generate(options)
|
|
108
|
+
request = Native.rp_request_new(bytes(json), json.bytesize)
|
|
109
|
+
raise InternalError, "the native library could not make a request" if request.null?
|
|
110
|
+
|
|
111
|
+
begin
|
|
112
|
+
yield request
|
|
113
|
+
ensure
|
|
114
|
+
Native.rp_request_free(request)
|
|
115
|
+
end
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
def add_asset(request, path, data)
|
|
119
|
+
path = utf8(path.to_s, "asset path")
|
|
120
|
+
data = if data.respond_to?(:to_path) then File.binread(data.to_path)
|
|
121
|
+
elsif data.respond_to?(:read) then data.read
|
|
122
|
+
else String(data)
|
|
123
|
+
end.b
|
|
124
|
+
status = Native.rp_request_add_asset(request, path, bytes(data), data.bytesize)
|
|
125
|
+
raise ArgumentError, "invalid asset path #{path.inspect}" unless status == :ok
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
def render_request(request, html)
|
|
129
|
+
out = FFI::MemoryPointer.new(:pointer)
|
|
130
|
+
status = Native.rp_render(request, bytes(html), html.bytesize, out)
|
|
131
|
+
result = out.read_pointer
|
|
132
|
+
raise InternalError, "the native library could not make a result" if result.null?
|
|
133
|
+
|
|
134
|
+
begin
|
|
135
|
+
raise error(status, result) unless status == :ok
|
|
136
|
+
|
|
137
|
+
Output.new(pdf: pdf(result), warnings: JSON.parse(string(result, :rp_result_warnings_json)).freeze)
|
|
138
|
+
ensure
|
|
139
|
+
Native.rp_result_free(result)
|
|
140
|
+
end
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
def pdf(result)
|
|
144
|
+
len = FFI::MemoryPointer.new(:size_t)
|
|
145
|
+
pointer = Native.rp_result_pdf(result, len)
|
|
146
|
+
pointer.read_bytes(len.read(:size_t)).force_encoding(Encoding::BINARY)
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
def string(result, function)
|
|
150
|
+
len = FFI::MemoryPointer.new(:size_t)
|
|
151
|
+
pointer = Native.public_send(function, result, len)
|
|
152
|
+
pointer.null? ? nil : pointer.read_bytes(len.read(:size_t)).force_encoding(Encoding::UTF_8)
|
|
153
|
+
end
|
|
154
|
+
|
|
155
|
+
def error(status, result)
|
|
156
|
+
message = string(result, :rp_result_error)
|
|
157
|
+
ERRORS.fetch(status) { InternalError }.new(message)
|
|
158
|
+
end
|
|
159
|
+
end
|
|
160
|
+
end
|
metadata
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: rustyprint
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 1.0.1
|
|
5
|
+
platform: x86_64-linux-musl
|
|
6
|
+
authors:
|
|
7
|
+
- Ryan Verschuren
|
|
8
|
+
bindir: bin
|
|
9
|
+
cert_chain: []
|
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
|
11
|
+
dependencies:
|
|
12
|
+
- !ruby/object:Gem::Dependency
|
|
13
|
+
name: ffi
|
|
14
|
+
requirement: !ruby/object:Gem::Requirement
|
|
15
|
+
requirements:
|
|
16
|
+
- - "~>"
|
|
17
|
+
- !ruby/object:Gem::Version
|
|
18
|
+
version: '1.17'
|
|
19
|
+
type: :runtime
|
|
20
|
+
prerelease: false
|
|
21
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
22
|
+
requirements:
|
|
23
|
+
- - "~>"
|
|
24
|
+
- !ruby/object:Gem::Version
|
|
25
|
+
version: '1.17'
|
|
26
|
+
description: 'rustyprint renders HTML and CSS to PDF with a layout engine of its own,
|
|
27
|
+
written in Rust: no browser, no external runtime and no network access unless allowed.'
|
|
28
|
+
executables: []
|
|
29
|
+
extensions: []
|
|
30
|
+
extra_rdoc_files: []
|
|
31
|
+
files:
|
|
32
|
+
- ".yardopts"
|
|
33
|
+
- LICENSE-APACHE
|
|
34
|
+
- LICENSE-MIT
|
|
35
|
+
- OFL.txt
|
|
36
|
+
- README.md
|
|
37
|
+
- lib/rustyprint.rb
|
|
38
|
+
- lib/rustyprint/asset_collector.rb
|
|
39
|
+
- lib/rustyprint/errors.rb
|
|
40
|
+
- lib/rustyprint/native.rb
|
|
41
|
+
- lib/rustyprint/native/librustyprint_ffi.so
|
|
42
|
+
- lib/rustyprint/pdf_renderer.rb
|
|
43
|
+
- lib/rustyprint/railtie.rb
|
|
44
|
+
- lib/rustyprint/version.rb
|
|
45
|
+
homepage: https://github.com/vryan95/rustyprint
|
|
46
|
+
licenses:
|
|
47
|
+
- MIT
|
|
48
|
+
- Apache-2.0
|
|
49
|
+
metadata:
|
|
50
|
+
source_code_uri: https://github.com/vryan95/rustyprint/tree/master/bindings/ruby
|
|
51
|
+
documentation_uri: https://rubydoc.info/gems/rustyprint
|
|
52
|
+
rubygems_mfa_required: 'true'
|
|
53
|
+
rdoc_options: []
|
|
54
|
+
require_paths:
|
|
55
|
+
- lib
|
|
56
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
57
|
+
requirements:
|
|
58
|
+
- - ">="
|
|
59
|
+
- !ruby/object:Gem::Version
|
|
60
|
+
version: '3.2'
|
|
61
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
62
|
+
requirements:
|
|
63
|
+
- - ">="
|
|
64
|
+
- !ruby/object:Gem::Version
|
|
65
|
+
version: 3.3.22
|
|
66
|
+
requirements: []
|
|
67
|
+
rubygems_version: 4.0.20
|
|
68
|
+
specification_version: 4
|
|
69
|
+
summary: Render HTML and CSS to PDF
|
|
70
|
+
test_files: []
|