nexpdf-cloud 1.1.1
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/README.md +291 -0
- data/lib/nexpdf_cloud/client.rb +511 -0
- data/lib/nexpdf_cloud/error.rb +23 -0
- data/lib/nexpdf_cloud/file.rb +61 -0
- data/lib/nexpdf_cloud/instructions.rb +220 -0
- data/lib/nexpdf_cloud/result.rb +39 -0
- data/lib/nexpdf_cloud/version.rb +6 -0
- data/lib/nexpdf_cloud.rb +18 -0
- metadata +49 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 787e7aef33e75702eef807d9ea0679f669890c501555349e558c5425a1140423
|
|
4
|
+
data.tar.gz: ccae1b6eb19128ee0d6400e854d4da99d7c6163ded37bc53ea9fe40bdb7a24ee
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: b5eb923dcf2755ec35e3153ec3d0b517f6db22068c3e043606ad4d6f44398aa1fe7ddb537b12e51253333ab1840dd374e72800f471d068fbcbead70ef6c9ae5e
|
|
7
|
+
data.tar.gz: 0231b4dd19bdc1996497c3ba183643a6e13ef217a29d126ee84dec85ac4ea769846392fe4467e5062bb3231eb81955c3dd7d910662b9f18d7893a49a0c189982
|
data/README.md
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
# NexPDF Cloud for Ruby
|
|
2
|
+
|
|
3
|
+
The client for the NexPDF Cloud API. Convert, OCR, merge, extract and build PDFs over HTTP.
|
|
4
|
+
|
|
5
|
+
It needs Ruby 3.0 or newer and has no dependencies (it uses `net/http`).
|
|
6
|
+
|
|
7
|
+
Full API reference: https://nexpdf.dev/docs/cloud
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
gem install nexpdf-cloud
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Or in a Gemfile: `gem "nexpdf-cloud"`.
|
|
16
|
+
|
|
17
|
+
## Quick start
|
|
18
|
+
|
|
19
|
+
Set your API key in the environment:
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
export NEXPDF_API_KEY=nxp_live_...
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Convert a Word file to PDF:
|
|
26
|
+
|
|
27
|
+
```ruby
|
|
28
|
+
require "nexpdf_cloud"
|
|
29
|
+
|
|
30
|
+
nexpdf = NexPdfCloud::Client.new
|
|
31
|
+
result = nexpdf.convert_to_pdf("report.docx")
|
|
32
|
+
result.save("report.pdf")
|
|
33
|
+
puts "#{result.units} units, request #{result.request_id}"
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Build a pipeline with the builder:
|
|
37
|
+
|
|
38
|
+
```ruby
|
|
39
|
+
instructions = NexPdfCloud::Instructions.new
|
|
40
|
+
.file("doc", pages: 0..-1)
|
|
41
|
+
.html("cover")
|
|
42
|
+
.redact("email", mode: "pattern")
|
|
43
|
+
.watermark("CONFIDENTIAL")
|
|
44
|
+
.encrypt("owner-secret", user_password: "reader")
|
|
45
|
+
.pdf(linearize: true)
|
|
46
|
+
|
|
47
|
+
result = nexpdf.build(instructions, files: { "doc" => "contract.pdf", "cover" => "cover.html" })
|
|
48
|
+
result.save("contract-final.pdf")
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Or with a plain hash (the same JSON the API takes):
|
|
52
|
+
|
|
53
|
+
```ruby
|
|
54
|
+
result = nexpdf.build({ parts: [{ file: "doc" }], output: { type: "markdown" } },
|
|
55
|
+
files: { "doc" => "a.pdf" })
|
|
56
|
+
puts result.text
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Methods
|
|
60
|
+
|
|
61
|
+
All methods return a `NexPdfCloud::Result`, except `health`, `verify_signatures`, `estimate`,
|
|
62
|
+
`prepare_signature`, `delete_signature`, the job and viewer methods and the AI methods, which return the parsed JSON (Hashes with string keys)
|
|
63
|
+
or `nil`.
|
|
64
|
+
|
|
65
|
+
| Method | API call | What it does |
|
|
66
|
+
| --- | --- | --- |
|
|
67
|
+
| `health` | `GET /v1/health` | Returns `{ ok: true, version: "..." }`. Sends no key. |
|
|
68
|
+
| `build(instructions, files: {})` | `POST /v1/build` | Any mix of parts, actions and one output. `files` maps field names to files. |
|
|
69
|
+
| `convert_to_pdf(document)` | `POST /v1/convert/pdf` | Office, image, EPUB or HTML file to PDF. |
|
|
70
|
+
| `ocr(document, languages: nil)` | `POST /v1/ocr` | A searchable PDF. `languages` such as `"eng+por"`. |
|
|
71
|
+
| `merge([a, b, ...])` | `POST /v1/merge` | 2 to 20 files, in order, into one PDF (else `invalid_request` before any request). |
|
|
72
|
+
| `extract_markdown(document)` | `POST /v1/extract/markdown` | The document as Markdown. Read it with `result.text`. |
|
|
73
|
+
| `edit_xlsx(document, edits)` | `POST /v1/xlsx/edit` | Sets cells and recalculates, for example `{ sheet: "Budget", edits: [{ cell: "C2", value: 6.5 }] }`. |
|
|
74
|
+
| `edit_docx(document, ops)` | `POST /v1/docx/edit` | Applies a list of text operations to a Word file. |
|
|
75
|
+
| `split(document, every: 2)` / `split(document, ranges: [...])` | `POST /v1/split` | Splits a PDF into a ZIP (`application/zip`) of `part-1.pdf`, `part-2.pdf`, ...: every `every` pages, or one part per range (`{ start:, end: }`, a Range or `[start, end]`, 0-based; `-1` is the last page). Give exactly one of the two, else `invalid_request` before any request. |
|
|
76
|
+
| `verify_signatures(document)` | `POST /v1/verify` | Checks a PDF's signatures. Returns an `Array<Hash>` with string keys (`"field"`, `"signer"`, `"digest_ok"`, `"signature_ok"`, `"covers_whole_document"`, `"self_signed"`, `"reason"`, ...), not a `Result`. An unsigned PDF gives `[]`. |
|
|
77
|
+
| `estimate(instructions, files: {...})` | `POST /v1/estimate` | What `build` would cost, without running it. Free. Returns a `Hash`: `"units"`, `"pages"`, `"operations"` (`[{ "op", "units" }]`). |
|
|
78
|
+
| `create_job(instructions, files: {...})` | `POST /v1/jobs` | Runs a `build` in the background. Returns the job (`"id"`, `"status"`, `"created_at"`, `"units"`, ...). |
|
|
79
|
+
| `batch(instructions, [a, b, ...], files: {})` | `POST /v1/batch` | The same instructions on 2 to 24 documents, in the background. Each document is the file `document` of the instructions; `files` are shared. Documents plus shared files are at most 24 and at most 10 inputs may be URLs; otherwise `invalid_request` before any request. Returns the job (with `"items"`). |
|
|
80
|
+
| `get_job(id)` | `GET /v1/jobs/{id}` | The job's state: `"status"` is `queued`, `running`, `succeeded` or `failed`. |
|
|
81
|
+
| `wait_for_job(id, interval: 2.0, timeout: 900.0)` | `GET /v1/jobs/{id}`, repeatedly | Polls until the job succeeds and returns it. The delay starts at `interval` and grows 1.5x per poll up to 5x `interval` (a longer `Retry-After` is waited instead, at most 30 s). A poll that still fails with a retryable error (`rate_limited`, `concurrency_limited`, `busy`, `unavailable`, `network`) does not end the wait; any other error does. A failed job raises its error (status 422, code `processing_failed` when it has none); after `timeout` seconds (one last poll is made at the deadline) it raises code `timeout` (status 0). |
|
|
82
|
+
| `job_result(id)` | `GET /v1/jobs/{id}/result` | The output of a job that succeeded, as a `Result`. |
|
|
83
|
+
| `delete_job(id)` | `DELETE /v1/jobs/{id}` | Cancels the job, or deletes its result. Returns `nil`. |
|
|
84
|
+
| `create_viewer(document, expires_in: nil, download: nil)` | `POST /v1/viewer` | A link that shows the document in the browser. Returns `"id"`, `"url"`, `"expires_at"`, `"pages"`. `expires_in` in seconds. |
|
|
85
|
+
| `delete_viewer(id)` | `DELETE /v1/viewer/{id}` | Ends a viewer link before it expires. Returns `nil`. |
|
|
86
|
+
| `prepare_signature(document, certificate, options: nil, expires_in: nil)` | `POST /v1/sign/prepare` | Step 1 of signing with a key you hold (an ICP-Brasil A3 token, a smart card, an HSM). `certificate` is the signer certificate (PEM or DER); `options` a Hash, sent as given with snake_case keys: `name`, `reason`, `location`, `contact`, `field`, `appearance`, `level`, `policy`, `timestamp_authority` (`{ url:, username:, password: }` or `{ url:, token: }`, needs level `"B-T"` or above). Returns `"id"`, `"to_be_signed"` (base64), `"to_be_signed_sha256"`, `"expires_at"`, `"level"`, `"policy"`. |
|
|
87
|
+
| `complete_signature(id, sig)` | `POST /v1/sign/complete` | Step 2: your signature over `"to_be_signed"` (a binary String, sent base64-encoded). Returns the signed PDF as a `Result`. |
|
|
88
|
+
| `delete_signature(id)` | `DELETE /v1/sign/{id}` | Drops a prepared signature before it expires. Returns `nil`. |
|
|
89
|
+
| `ai_extract(document, schema, prompt: nil)` | `POST /v1/ai/extract` | Data matching a JSON Schema, read from the document. Returns the data itself (string keys). |
|
|
90
|
+
| `ai_classify(document, labels, prompt: nil)` | `POST /v1/ai/classify` | Which label fits the document. `labels` are strings or `{ name:, description: }` Hashes. Returns `{ "label" => ..., "reason" => ... }`. |
|
|
91
|
+
|
|
92
|
+
Split and verify:
|
|
93
|
+
|
|
94
|
+
```ruby
|
|
95
|
+
nexpdf.split("book.pdf", every: 2).save("parts.zip")
|
|
96
|
+
nexpdf.split("book.pdf", ranges: [{ start: 0, end: 0 }, { start: 1, end: -1 }]).save("parts.zip")
|
|
97
|
+
|
|
98
|
+
nexpdf.verify_signatures("signed.pdf").each do |sig|
|
|
99
|
+
puts "#{sig['field']} #{sig['signer']} #{sig['signature_ok'] && sig['digest_ok']}"
|
|
100
|
+
end
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Background jobs, batches, viewer links and AI:
|
|
104
|
+
|
|
105
|
+
```ruby
|
|
106
|
+
job = nexpdf.create_job({ parts: [{ file: "doc" }], output: { type: "markdown" } }, files: { "doc" => "big.pdf" })
|
|
107
|
+
nexpdf.wait_for_job(job["id"])
|
|
108
|
+
puts nexpdf.job_result(job["id"]).text
|
|
109
|
+
nexpdf.delete_job(job["id"])
|
|
110
|
+
|
|
111
|
+
run = nexpdf.batch({ parts: [{ file: "document" }], actions: [{ type: "ocr" }] }, ["a.pdf", "b.pdf"])
|
|
112
|
+
|
|
113
|
+
viewer = nexpdf.create_viewer("report.pdf", expires_in: 3600, download: false)
|
|
114
|
+
puts viewer["url"]
|
|
115
|
+
|
|
116
|
+
invoice = nexpdf.ai_extract("invoice.pdf", {
|
|
117
|
+
type: "object",
|
|
118
|
+
properties: { total: { type: "number" }, vendor: { type: "string" } },
|
|
119
|
+
required: %w[total vendor]
|
|
120
|
+
})
|
|
121
|
+
label = nexpdf.ai_classify("scan.pdf", ["invoice", { name: "receipt", description: "proof of payment" }])["label"]
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
### The builder
|
|
125
|
+
|
|
126
|
+
`NexPdfCloud::Instructions.new` returns a builder. Every method returns the builder.
|
|
127
|
+
|
|
128
|
+
- Parts: `file(name, pages: nil, password: nil)`, `html(name, pages: nil)`. `pages` is a Range
|
|
129
|
+
(`0..-1`), `[start, end]` or `{ start:, end: }`, 0-based; `-1` is the last page.
|
|
130
|
+
- Actions: `ocr(languages = nil)`, `watermark(text)`, `rotate(degrees, pages = nil)`,
|
|
131
|
+
`delete_pages(pages)`, `flatten_annotations`, `flatten_forms`, `fill_form(values)`,
|
|
132
|
+
`redact(query, mode: nil, fill_white: nil)` (mode `"text"`, `"regex"` or `"pattern"`),
|
|
133
|
+
`pdfa(level = nil)`, `pdfua(part: nil, lang: nil)`, `optimize`,
|
|
134
|
+
`encrypt(owner_password, user_password: nil, permissions: nil)` (must be last),
|
|
135
|
+
`sign(certificate: nil, password: nil, name: nil, reason: nil, location: nil, contact: nil,
|
|
136
|
+
field: nil, appearance: nil, level: nil, policy: nil, timestamp_authority: nil)` (must be last, with PDF output that is not
|
|
137
|
+
linearized). `certificate` names an uploaded PKCS#12 file; without it the server signs with a
|
|
138
|
+
self-signed certificate. `appearance` is `{ page: 0, rect: [llx, lly, urx, ury], text: "..." }`
|
|
139
|
+
(`page` and `text` optional) for a visible signature. `level` is the PAdES level: `"B-B"` (the
|
|
140
|
+
default), `"B-T"`, `"B-LT"` or `"B-LTA"`. `policy` is a signature policy: `"icp-brasil"`
|
|
141
|
+
(ICP-Brasil AD-RB at `"B-B"`, AD-RT from `"B-T"`).
|
|
142
|
+
`timestamp_authority` is your own RFC 3161 TSA, `{ url:, username:, password: }` or `{ url:, token: }`, from `"B-T"`.
|
|
143
|
+
- Output (the last call wins): `pdf(linearize: nil)`, `png(page: nil, dpi: nil)`, `markdown`,
|
|
144
|
+
`to_html`, `json`, `docx`, `xlsx`, `split(every: nil, ranges: nil)` (a ZIP of PDFs; give exactly
|
|
145
|
+
one). Without one, the output is PDF.
|
|
146
|
+
- `to_h` returns the plain structure, `to_json` the JSON text. Options you leave out are left out
|
|
147
|
+
of the JSON.
|
|
148
|
+
|
|
149
|
+
Sign with your own certificate:
|
|
150
|
+
|
|
151
|
+
```ruby
|
|
152
|
+
signed = nexpdf.build(
|
|
153
|
+
NexPdfCloud::Instructions.new
|
|
154
|
+
.file("doc")
|
|
155
|
+
.sign(certificate: "cert", password: "p12-password", reason: "Approved",
|
|
156
|
+
appearance: { page: 0, rect: [36, 36, 236, 96], text: "Signed" })
|
|
157
|
+
.pdf,
|
|
158
|
+
files: { "doc" => "contract.pdf", "cert" => "signer.p12" }
|
|
159
|
+
)
|
|
160
|
+
signed.save("contract-signed.pdf")
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
## Files
|
|
164
|
+
|
|
165
|
+
A file is a path on disk, bytes with a name, or a URL:
|
|
166
|
+
|
|
167
|
+
```ruby
|
|
168
|
+
"a.pdf" # a path string (or a Pathname); never a URL
|
|
169
|
+
NexPdfCloud::File.path("a.pdf") # the same, explicit
|
|
170
|
+
NexPdfCloud::File.bytes(data, "a.pdf") # bytes in memory
|
|
171
|
+
NexPdfCloud::File.url("https://example.com/a.pdf") # the server downloads it
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
The upload uses the path's base name, or the name you give. A URL is not downloaded by the
|
|
175
|
+
client: it is sent as the text field `<name>_url` (for example `document_url`) and the server
|
|
176
|
+
fetches it. Only `http` and `https` URLs are accepted; anything else raises `invalid_request`
|
|
177
|
+
before any request.
|
|
178
|
+
|
|
179
|
+
## Results
|
|
180
|
+
|
|
181
|
+
| Member | Value |
|
|
182
|
+
| --- | --- |
|
|
183
|
+
| `bytes` (or `body`) | The output file, a binary String. |
|
|
184
|
+
| `content_type` | The `Content-Type` header. |
|
|
185
|
+
| `units` | Units charged for the call. |
|
|
186
|
+
| `request_id` | The request id. Quote it when you contact support. |
|
|
187
|
+
| `save(path)` | Writes the file. Returns the path. |
|
|
188
|
+
| `text` | The body as UTF-8 text, for Markdown, HTML and JSON outputs. |
|
|
189
|
+
|
|
190
|
+
## Errors
|
|
191
|
+
|
|
192
|
+
Every failure raises `NexPdfCloud::Error`:
|
|
193
|
+
|
|
194
|
+
```ruby
|
|
195
|
+
begin
|
|
196
|
+
nexpdf.convert_to_pdf("report.docx")
|
|
197
|
+
rescue NexPdfCloud::Error => e
|
|
198
|
+
warn [e.status, e.code, e.message, e.request_id, e.retry_after].inspect
|
|
199
|
+
end
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
- `status`: the HTTP status, or `0` for client-side and network errors.
|
|
203
|
+
- `code`: the API's error code (for example `unauthorized`, `quota_exceeded`, `invalid_request`),
|
|
204
|
+
or `missing_api_key`, `invalid_request` (client-side checks), `network` (connection failures and
|
|
205
|
+
timeouts), `http_<status>` (an error body that is not JSON).
|
|
206
|
+
- `request_id` and `retry_after` (seconds) when the server sent them.
|
|
207
|
+
|
|
208
|
+
Client-side checks (`invalid_request`, before any request): field names (the keys of `files`, and
|
|
209
|
+
`<name>_url` for URL inputs) are 1 to 64 letters, digits, `_`, `-` or `.`; at most 25 fields in a
|
|
210
|
+
request (24 files for `build`, `estimate`, `create_job`); at most 10 URL inputs; `merge` takes 2 to
|
|
211
|
+
20 files; `batch` as above.
|
|
212
|
+
|
|
213
|
+
A body that cannot be read to the end is a `network` error, and a 2xx answer that is not the JSON
|
|
214
|
+
the method needs (for example `health` or `verify_signatures`) is an error with the answer's status
|
|
215
|
+
and code `http_<status>` (for example `http_200`), never a `JSON::ParserError`.
|
|
216
|
+
|
|
217
|
+
### Retries
|
|
218
|
+
|
|
219
|
+
The client retries up to `max_retries` times (default 2, so 3 attempts):
|
|
220
|
+
|
|
221
|
+
- When the API answers `429` `rate_limited` or `concurrency_limited`, or `503` `busy`,
|
|
222
|
+
`unavailable` or with no code: any method, because the API has not acted on the request. Never
|
|
223
|
+
`429 quota_exceeded`, `503 ai_unavailable`, `502`, `504`, `422` or other `4xx`.
|
|
224
|
+
- `GET` and `DELETE` also on any transport failure (connect errors, timeouts, resets, a body cut
|
|
225
|
+
short).
|
|
226
|
+
- `POST` on a transport failure only when it is known to have happened before the request was
|
|
227
|
+
sent (DNS failure, connection refused or unreachable, TLS handshake failure, connect timeout).
|
|
228
|
+
After the request may have reached the server (a read timeout, a reset, a truncated answer) it
|
|
229
|
+
raises code `network` and does not resend, so a lost answer to `create_job` or `batch` never
|
|
230
|
+
starts a second job. Check with `get_job` or your own records before retrying such a call.
|
|
231
|
+
|
|
232
|
+
The wait before a retry is the `Retry-After` of the answer, in seconds or an HTTP-date (at most
|
|
233
|
+
30 s), else 0.5 s, 1 s, 2 s, ... Retried requests resend the same bytes. Every `POST` carries an
|
|
234
|
+
`Idempotency-Key` header (a random UUID v4, generated once per call and kept on retries); `GET`
|
|
235
|
+
and `DELETE` send none. The API ignores it today, so the rules above are what make a retry safe.
|
|
236
|
+
Proxy environment variables (`http_proxy`, ...) are honoured by `net/http` as usual. The whole
|
|
237
|
+
response is buffered in memory (`Result#bytes`); the connect phase alone is limited to 10 s (or
|
|
238
|
+
`timeout`, when smaller).
|
|
239
|
+
|
|
240
|
+
## Signing with a key you hold (two steps)
|
|
241
|
+
|
|
242
|
+
```ruby
|
|
243
|
+
prepared = nexpdf.prepare_signature("contract.pdf", "signer.pem",
|
|
244
|
+
options: { name: "Ana", level: "B-T", policy: "icp-brasil",
|
|
245
|
+
timestamp_authority: { url: "https://act.example.com.br/tsp",
|
|
246
|
+
username: "client", password: "secret" } },
|
|
247
|
+
expires_in: 600)
|
|
248
|
+
tbs = prepared["to_be_signed"].unpack1("m") # base64 text -> bytes (DER SET OF Attribute, starts 0x31)
|
|
249
|
+
sig = key.sign(OpenSSL::Digest.new("SHA256"), tbs) # OpenSSL::PKey::EC: DER, accepted
|
|
250
|
+
# sig = key.sign("SHA256", tbs) # OpenSSL::PKey::RSA: PKCS#1 v1.5
|
|
251
|
+
nexpdf.complete_signature(prepared["id"], sig).save("contract-signed.pdf") # sig: a binary String, base64-encoded by the client
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
- Sign `to_be_signed` (decoded) with **SHA-256**, whatever the curve (P-384 also uses SHA-256).
|
|
255
|
+
`to_be_signed_sha256` is the **hex** SHA-256 of those bytes, for signers that take a digest.
|
|
256
|
+
- RSA: PKCS#1 v1.5 with SHA-256 (no PSS), the signature is as long as the key. A raw "sign this
|
|
257
|
+
digest" primitive (PKCS#11 `CKM_RSA_PKCS`) needs the `DigestInfo` prefix added by you; a hash-and-sign
|
|
258
|
+
one (`CKM_SHA256_RSA_PKCS`, `OpenSSL::PKey::RSA#sign("SHA256", ...)`) does not.
|
|
259
|
+
- ECDSA (P-256 or P-384): the DER `SEQUENCE { r, s }` that `OpenSSL::PKey::EC#sign` returns, or raw
|
|
260
|
+
`r||s` (64 bytes for P-256, 96 for P-384), both accepted. PKCS#11 `CKM_ECDSA` / `CKM_ECDSA_SHA256`
|
|
261
|
+
give raw `r||s` (plain `CKM_ECDSA` takes the digest); AWS KMS `ECDSA_SHA_256` gives DER (`MessageType: RAW`
|
|
262
|
+
with the bytes, or `DIGEST` with `[prepared["to_be_signed_sha256"]].pack("H*")`).
|
|
263
|
+
- Never pass the base64 text or the hex digest as the data to sign, and pass `complete_signature`
|
|
264
|
+
the raw signature bytes, not base64 (the client encodes them). A signature that does not verify
|
|
265
|
+
is refused with `422 processing_failed` and the prepared signature is kept, so you can send a corrected one.
|
|
266
|
+
|
|
267
|
+
## Configuration
|
|
268
|
+
|
|
269
|
+
```ruby
|
|
270
|
+
nexpdf = NexPdfCloud::Client.new(
|
|
271
|
+
api_key: "nxp_live_...", # default: env NEXPDF_API_KEY
|
|
272
|
+
base_url: "https://api.nexpdf.dev", # default: env NEXPDF_API_BASE, else this
|
|
273
|
+
timeout: 300, # seconds, whole request
|
|
274
|
+
max_retries: 2 # retries after the first attempt
|
|
275
|
+
)
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
Without a key, `Client.new` raises `NexPdfCloud::Error` with code `missing_api_key`.
|
|
279
|
+
|
|
280
|
+
## Test keys
|
|
281
|
+
|
|
282
|
+
Keys that start with `nxp_test_` are for development. Every PDF they make carries a "NexPDF Cloud
|
|
283
|
+
test key" watermark. Editing Excel and Word files needs a live key (`nxp_live_`).
|
|
284
|
+
|
|
285
|
+
## Development
|
|
286
|
+
|
|
287
|
+
```sh
|
|
288
|
+
NEXPDF_MOCK_URL=http://127.0.0.1:4010 ./test.sh # minitest
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
Start the mock first: `node ../conformance/mock-server.mjs`.
|
|
@@ -0,0 +1,511 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "net/http"
|
|
5
|
+
require "openssl"
|
|
6
|
+
require "securerandom"
|
|
7
|
+
require "time"
|
|
8
|
+
require "timeout"
|
|
9
|
+
require "uri"
|
|
10
|
+
require "zlib"
|
|
11
|
+
|
|
12
|
+
module NexPdfCloud
|
|
13
|
+
# The NexPDF Cloud client.
|
|
14
|
+
#
|
|
15
|
+
# nexpdf = NexPdfCloud::Client.new # reads NEXPDF_API_KEY
|
|
16
|
+
# nexpdf.convert_to_pdf("report.docx").save("report.pdf")
|
|
17
|
+
class Client
|
|
18
|
+
DEFAULT_BASE_URL = "https://api.nexpdf.dev"
|
|
19
|
+
# Answers that mean "not done, try later": safe to resend, POST included. A 503 whose body has
|
|
20
|
+
# no error code (code "http_503") counts too. 429 quota_exceeded and 503 ai_unavailable never.
|
|
21
|
+
RETRY = { 429 => %w[rate_limited concurrency_limited], 503 => %w[busy unavailable http_503] }.freeze
|
|
22
|
+
MAX_RETRY_WAIT = 30.0
|
|
23
|
+
CONNECT_TIMEOUT = 10.0
|
|
24
|
+
MAX_FIELDS = 25
|
|
25
|
+
MAX_URL_FIELDS = 10
|
|
26
|
+
MAX_BATCH_DOCUMENTS = 24
|
|
27
|
+
MAX_MERGE_FILES = 20
|
|
28
|
+
FIELD_NAME = /\A[A-Za-z0-9_.-]{1,64}\z/
|
|
29
|
+
NETWORK_ERRORS = [
|
|
30
|
+
SocketError, SystemCallError, IOError, EOFError, Timeout::Error, Zlib::Error,
|
|
31
|
+
Net::OpenTimeout, Net::ReadTimeout, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError,
|
|
32
|
+
Net::ProtocolError, OpenSSL::SSL::SSLError
|
|
33
|
+
].freeze
|
|
34
|
+
# Failures that, while connecting (before anything of the request is sent), mean the request
|
|
35
|
+
# cannot have reached the server, so even a POST may be resent.
|
|
36
|
+
CONNECT_ERRORS = [
|
|
37
|
+
SocketError, Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Errno::ENETUNREACH,
|
|
38
|
+
Timeout::Error, OpenSSL::SSL::SSLError
|
|
39
|
+
].freeze
|
|
40
|
+
|
|
41
|
+
# A transport failure. +before_send+ is true when it is known to have happened before the
|
|
42
|
+
# request was sent (so a POST may be retried).
|
|
43
|
+
class NetworkError < Error
|
|
44
|
+
attr_reader :before_send
|
|
45
|
+
|
|
46
|
+
def initialize(message:, before_send:)
|
|
47
|
+
super(status: 0, code: "network", message: message)
|
|
48
|
+
@before_send = before_send
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
private_constant :NetworkError
|
|
52
|
+
|
|
53
|
+
attr_reader :base_url, :timeout, :max_retries
|
|
54
|
+
|
|
55
|
+
# api_key: default env NEXPDF_API_KEY. base_url: default env NEXPDF_API_BASE, else
|
|
56
|
+
# https://api.nexpdf.dev. timeout: seconds for a whole request (300). max_retries: retries
|
|
57
|
+
# after the first attempt (2).
|
|
58
|
+
def initialize(api_key: nil, base_url: nil, timeout: 300, max_retries: 2)
|
|
59
|
+
key = api_key.nil? ? ENV["NEXPDF_API_KEY"] : api_key
|
|
60
|
+
if key.nil? || key.empty?
|
|
61
|
+
raise Error.new(status: 0, code: "missing_api_key",
|
|
62
|
+
message: "No API key: pass api_key: or set NEXPDF_API_KEY")
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
@api_key = key
|
|
66
|
+
base = base_url
|
|
67
|
+
base = ENV["NEXPDF_API_BASE"] if base.nil? || base.empty?
|
|
68
|
+
base = DEFAULT_BASE_URL if base.nil? || base.empty?
|
|
69
|
+
@base_url = base.sub(%r{/+\z}, "")
|
|
70
|
+
@timeout = timeout.to_f
|
|
71
|
+
@max_retries = Integer(max_retries)
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
def inspect
|
|
75
|
+
"#<NexPdfCloud::Client base_url=#{@base_url.inspect}>"
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# GET /v1/health (no key sent). Returns { ok: true, version: "..." }.
|
|
79
|
+
def health
|
|
80
|
+
h = parse_json(request(:get, "/v1/health", nil))
|
|
81
|
+
h.transform_keys(&:to_sym)
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
# POST /v1/build: the files under their field names, then the instructions (an Instructions
|
|
85
|
+
# builder or a plain Hash).
|
|
86
|
+
def build(instructions, files: {})
|
|
87
|
+
request(:post, "/v1/build", build_fields(instructions, files))
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
# POST /v1/estimate: what build with these instructions and files would cost. Free. Returns a
|
|
91
|
+
# Hash with string keys: { "units" => 2, "pages" => 3, "operations" => [{ "op", "units" }, ...] }.
|
|
92
|
+
def estimate(instructions, files: {})
|
|
93
|
+
parse_json(request(:post, "/v1/estimate", build_fields(instructions, files)))
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
# POST /v1/jobs: runs a build in the background. Returns the queued job (a Hash with string
|
|
97
|
+
# keys: "id", "status", "created_at", "units", ...).
|
|
98
|
+
def create_job(instructions, files: {})
|
|
99
|
+
parse_json(request(:post, "/v1/jobs", build_fields(instructions, files)))
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
# POST /v1/batch: the same instructions on 2 to 24 documents, in the background. Each document
|
|
103
|
+
# is the file "document" of the instructions; +files+ are shared by every run. Documents plus
|
|
104
|
+
# shared files are at most 24 and at most 10 inputs may be URLs (checked before any request).
|
|
105
|
+
# Returns the job.
|
|
106
|
+
def batch(instructions, documents, files: {})
|
|
107
|
+
docs = Array(documents)
|
|
108
|
+
shared = files || {}
|
|
109
|
+
if docs.size < 2
|
|
110
|
+
raise invalid("batch needs at least 2 documents (got #{docs.size})")
|
|
111
|
+
end
|
|
112
|
+
if docs.size + shared.size > MAX_BATCH_DOCUMENTS
|
|
113
|
+
raise invalid("batch takes at most #{MAX_BATCH_DOCUMENTS} documents and shared files together " \
|
|
114
|
+
"(got #{docs.size} documents and #{shared.size} shared files)")
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
fields = docs.each_with_index.map { |d, i| file_field("document#{i + 1}", d) }
|
|
118
|
+
parse_json(request(:post, "/v1/batch", fields + build_fields(instructions, shared)))
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
# GET /v1/jobs/{id}: the job's current state.
|
|
122
|
+
def get_job(id)
|
|
123
|
+
parse_json(request(:get, "/v1/jobs/#{segment(id)}", nil))
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
# Polls get_job until the job succeeds (returns it). Raises the job's error (status 422, code
|
|
127
|
+
# "processing_failed" when it has none) when it fails, or code "timeout" (status 0) after
|
|
128
|
+
# +timeout+ seconds. A poll that still fails with a retryable error (rate limit, busy, network)
|
|
129
|
+
# does not end the wait; any other error does. The delay between polls starts at +interval+ and
|
|
130
|
+
# grows 1.5x per poll up to 5x +interval+ (a longer Retry-After is waited instead, at most 30 s);
|
|
131
|
+
# one last poll is made at the deadline.
|
|
132
|
+
def wait_for_job(id, interval: 2.0, timeout: 900.0)
|
|
133
|
+
interval = interval.to_f
|
|
134
|
+
interval = 2.0 unless interval.positive?
|
|
135
|
+
delay = interval
|
|
136
|
+
deadline = now + timeout.to_f
|
|
137
|
+
last = nil
|
|
138
|
+
loop do
|
|
139
|
+
begin
|
|
140
|
+
job = get_job(id)
|
|
141
|
+
last = nil
|
|
142
|
+
return job if job["status"] == "succeeded"
|
|
143
|
+
raise job_failure(job) if job["status"] == "failed"
|
|
144
|
+
rescue Error => e
|
|
145
|
+
raise unless retryable_answer?(e) || e.code == "network"
|
|
146
|
+
|
|
147
|
+
last = e
|
|
148
|
+
end
|
|
149
|
+
left = deadline - now
|
|
150
|
+
if left <= 0
|
|
151
|
+
detail = last ? " (last error: #{last.code}: #{last.message})" : ""
|
|
152
|
+
raise Error.new(status: 0, code: "timeout", message: "job #{id} did not finish in time#{detail}")
|
|
153
|
+
end
|
|
154
|
+
|
|
155
|
+
wait = delay
|
|
156
|
+
wait = [wait, [last.retry_after, MAX_RETRY_WAIT].min].max if last&.retry_after
|
|
157
|
+
sleep([wait, left].min)
|
|
158
|
+
delay = [delay * 1.5, interval * 5].min
|
|
159
|
+
end
|
|
160
|
+
end
|
|
161
|
+
|
|
162
|
+
# GET /v1/jobs/{id}/result: the output of a job that succeeded.
|
|
163
|
+
def job_result(id)
|
|
164
|
+
request(:get, "/v1/jobs/#{segment(id)}/result", nil)
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
# DELETE /v1/jobs/{id}: cancels the job, or deletes its result.
|
|
168
|
+
def delete_job(id)
|
|
169
|
+
request(:delete, "/v1/jobs/#{segment(id)}", nil)
|
|
170
|
+
nil
|
|
171
|
+
end
|
|
172
|
+
|
|
173
|
+
# POST /v1/viewer: a link that shows the document in the browser. Returns a Hash with string
|
|
174
|
+
# keys: "id", "url", "expires_at", "pages". +expires_in+ is in seconds.
|
|
175
|
+
def create_viewer(document, expires_in: nil, download: nil)
|
|
176
|
+
fields = [file_field("document", document)]
|
|
177
|
+
fields << [:text, "expires_in", Integer(expires_in).to_s] unless expires_in.nil?
|
|
178
|
+
fields << [:text, "download", download ? "true" : "false"] unless download.nil?
|
|
179
|
+
parse_json(request(:post, "/v1/viewer", fields))
|
|
180
|
+
end
|
|
181
|
+
|
|
182
|
+
# DELETE /v1/viewer/{id}: ends a viewer link before it expires.
|
|
183
|
+
def delete_viewer(id)
|
|
184
|
+
request(:delete, "/v1/viewer/#{segment(id)}", nil)
|
|
185
|
+
nil
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
# POST /v1/sign/prepare: step 1 of signing with a key you hold (smart card, token, HSM, KMS).
|
|
189
|
+
# +certificate+ is the signer certificate (PEM or DER); +options+ a Hash sent as given (keys are
|
|
190
|
+
# never renamed, so use snake_case): name, reason, location, contact, field, appearance, level,
|
|
191
|
+
# policy, timestamp_authority ({ url:, username:, password: } or { url:, token: }, level B-T or
|
|
192
|
+
# above). +expires_in+ is in seconds (60 to 86400). Returns a Hash with string keys: "id",
|
|
193
|
+
# "to_be_signed" (base64 text), "to_be_signed_sha256" (hex), "expires_at", "level", "policy".
|
|
194
|
+
#
|
|
195
|
+
# Decode "to_be_signed" (<tt>to_be_signed.unpack1("m")</tt>) to bytes, the DER SET OF Attribute
|
|
196
|
+
# (first byte 0x31), and sign exactly those bytes with SHA-256 (also for P-384 keys):
|
|
197
|
+
#
|
|
198
|
+
# tbs = prepared["to_be_signed"].unpack1("m")
|
|
199
|
+
# sig = key.sign(OpenSSL::Digest.new("SHA256"), tbs) # EC key: DER, accepted
|
|
200
|
+
# sig = key.sign("SHA256", tbs) # RSA key: PKCS#1 v1.5, accepted
|
|
201
|
+
# nexpdf.complete_signature(prepared["id"], sig)
|
|
202
|
+
#
|
|
203
|
+
# RSA: RSASSA-PKCS1-v1_5 with SHA-256 (no PSS); a raw "sign this digest" primitive (PKCS#11
|
|
204
|
+
# CKM_RSA_PKCS, some KMS raw modes) needs the DigestInfo prefix added by you. ECDSA: DER
|
|
205
|
+
# SEQUENCE { r, s } or raw r||s (64 bytes for P-256, 96 for P-384) are both accepted. For KMS or
|
|
206
|
+
# PKCS#11 give the data (or the digest, "to_be_signed_sha256" hex-decoded with
|
|
207
|
+
# <tt>[hex].pack("H*")</tt>), never the base64 text or the hex string.
|
|
208
|
+
def prepare_signature(document, certificate, options: nil, expires_in: nil)
|
|
209
|
+
fields = [file_field("document", document), file_field("certificate", certificate)]
|
|
210
|
+
fields << [:text, "options", JSON.generate(options)] unless options.nil?
|
|
211
|
+
fields << [:text, "expires_in", Integer(expires_in).to_s] unless expires_in.nil?
|
|
212
|
+
parse_json(request(:post, "/v1/sign/prepare", fields))
|
|
213
|
+
end
|
|
214
|
+
|
|
215
|
+
# POST /v1/sign/complete: the signed PDF, from +signature+ (a binary String of the signature
|
|
216
|
+
# bytes over the decoded "to_be_signed") returned as a Result. Pass the raw bytes (as
|
|
217
|
+
# <tt>OpenSSL::PKey#sign</tt> returns them): this method base64-encodes them for you, so do not
|
|
218
|
+
# encode them first. A signature that does not verify with the certificate is refused with
|
|
219
|
+
# 422 processing_failed and the prepared signature is kept, so you can send a corrected one.
|
|
220
|
+
def complete_signature(id, signature)
|
|
221
|
+
request(:post, "/v1/sign/complete", [[:text, "id", id.to_s], [:text, "signature", [signature.to_s].pack("m0")]])
|
|
222
|
+
end
|
|
223
|
+
|
|
224
|
+
# DELETE /v1/sign/{id}: drops a prepared signature before it expires.
|
|
225
|
+
def delete_signature(id)
|
|
226
|
+
request(:delete, "/v1/sign/#{segment(id)}", nil)
|
|
227
|
+
nil
|
|
228
|
+
end
|
|
229
|
+
|
|
230
|
+
# POST /v1/ai/extract: data matching the JSON Schema +schema+, read from the document (parsed
|
|
231
|
+
# JSON, string keys).
|
|
232
|
+
def ai_extract(document, schema, prompt: nil)
|
|
233
|
+
fields = [file_field("document", document), [:text, "schema", JSON.generate(schema)]]
|
|
234
|
+
fields << [:text, "prompt", prompt.to_s] unless prompt.nil?
|
|
235
|
+
parse_json(request(:post, "/v1/ai/extract", fields))["data"]
|
|
236
|
+
end
|
|
237
|
+
|
|
238
|
+
# POST /v1/ai/classify: which of +labels+ (strings or { name:, description: } Hashes) fits the
|
|
239
|
+
# document. Returns { "label" => "...", "reason" => "..." }.
|
|
240
|
+
def ai_classify(document, labels, prompt: nil)
|
|
241
|
+
fields = [file_field("document", document), [:text, "labels", JSON.generate(labels.to_a)]]
|
|
242
|
+
fields << [:text, "prompt", prompt.to_s] unless prompt.nil?
|
|
243
|
+
parse_json(request(:post, "/v1/ai/classify", fields))
|
|
244
|
+
end
|
|
245
|
+
|
|
246
|
+
# POST /v1/convert/pdf: an Office, image, EPUB or HTML file to PDF.
|
|
247
|
+
def convert_to_pdf(document)
|
|
248
|
+
request(:post, "/v1/convert/pdf", [file_field("document", document)])
|
|
249
|
+
end
|
|
250
|
+
|
|
251
|
+
# POST /v1/ocr: a searchable PDF. languages such as "eng+por".
|
|
252
|
+
def ocr(document, languages: nil)
|
|
253
|
+
fields = [file_field("document", document)]
|
|
254
|
+
fields << [:text, "languages", languages.to_s] unless languages.nil?
|
|
255
|
+
request(:post, "/v1/ocr", fields)
|
|
256
|
+
end
|
|
257
|
+
|
|
258
|
+
# POST /v1/merge: two or more files, in order, into one PDF.
|
|
259
|
+
def merge(documents)
|
|
260
|
+
docs = Array(documents)
|
|
261
|
+
unless docs.size.between?(2, MAX_MERGE_FILES)
|
|
262
|
+
raise invalid("merge needs 2 to #{MAX_MERGE_FILES} files (got #{docs.size})")
|
|
263
|
+
end
|
|
264
|
+
|
|
265
|
+
request(:post, "/v1/merge", docs.each_with_index.map { |d, i| file_field("file#{i + 1}", d) })
|
|
266
|
+
end
|
|
267
|
+
|
|
268
|
+
# POST /v1/extract/markdown: the document as Markdown (use result.text).
|
|
269
|
+
def extract_markdown(document)
|
|
270
|
+
request(:post, "/v1/extract/markdown", [file_field("document", document)])
|
|
271
|
+
end
|
|
272
|
+
|
|
273
|
+
# POST /v1/xlsx/edit: sets cells and recalculates the workbook.
|
|
274
|
+
def edit_xlsx(document, edits)
|
|
275
|
+
request(:post, "/v1/xlsx/edit", [file_field("document", document), [:text, "edits", JSON.generate(edits)]])
|
|
276
|
+
end
|
|
277
|
+
|
|
278
|
+
# POST /v1/docx/edit: applies text operations to a Word file.
|
|
279
|
+
def edit_docx(document, ops)
|
|
280
|
+
request(:post, "/v1/docx/edit", [file_field("document", document), [:text, "ops", JSON.generate(ops.to_a)]])
|
|
281
|
+
end
|
|
282
|
+
|
|
283
|
+
# POST /v1/split: a ZIP (part-1.pdf, part-2.pdf, ...). Give exactly one of +every+ (pages per
|
|
284
|
+
# part) or +ranges+ (each a Hash { start:, end: }, a Range or [start, end]; 0-based, negative
|
|
285
|
+
# counts from the end).
|
|
286
|
+
def split(document, every: nil, ranges: nil)
|
|
287
|
+
if every.nil? == ranges.nil?
|
|
288
|
+
raise invalid("split needs exactly one of every: or ranges:")
|
|
289
|
+
end
|
|
290
|
+
|
|
291
|
+
fields = [file_field("document", document)]
|
|
292
|
+
fields << if every.nil?
|
|
293
|
+
[:text, "ranges", JSON.generate(Instructions.page_ranges(ranges))]
|
|
294
|
+
else
|
|
295
|
+
[:text, "every", Integer(every).to_s]
|
|
296
|
+
end
|
|
297
|
+
request(:post, "/v1/split", fields)
|
|
298
|
+
end
|
|
299
|
+
|
|
300
|
+
# POST /v1/verify: the PDF's signatures, checked. Returns an Array of Hashes with string keys
|
|
301
|
+
# ("field", "signer", "digest_ok", "signature_ok", "covers_whole_document", "self_signed",
|
|
302
|
+
# "reason", ...). An unsigned PDF gives [].
|
|
303
|
+
def verify_signatures(document)
|
|
304
|
+
parse_json(request(:post, "/v1/verify", [file_field("document", document)]), Array)
|
|
305
|
+
end
|
|
306
|
+
|
|
307
|
+
private
|
|
308
|
+
|
|
309
|
+
def file_field(name, value)
|
|
310
|
+
f = NexPdfCloud::File.coerce(value)
|
|
311
|
+
return [:file, name, f.read, f.name] unless f.url
|
|
312
|
+
|
|
313
|
+
scheme = begin
|
|
314
|
+
URI.parse(f.url).scheme.to_s.downcase
|
|
315
|
+
rescue URI::InvalidURIError
|
|
316
|
+
""
|
|
317
|
+
end
|
|
318
|
+
unless %w[http https].include?(scheme)
|
|
319
|
+
raise invalid("#{name}: only http and https URLs are accepted")
|
|
320
|
+
end
|
|
321
|
+
|
|
322
|
+
[:text, "#{name}_url", f.url]
|
|
323
|
+
end
|
|
324
|
+
|
|
325
|
+
def build_fields(instructions, files)
|
|
326
|
+
fields = files.map { |name, f| file_field(name.to_s, f) }
|
|
327
|
+
fields << [:text, "instructions", JSON.generate(instructions.is_a?(Instructions) ? instructions.to_h : instructions)]
|
|
328
|
+
end
|
|
329
|
+
|
|
330
|
+
# An id as one percent-encoded path segment.
|
|
331
|
+
def segment(id)
|
|
332
|
+
id.to_s.b.gsub(/[^A-Za-z0-9\-._~]/) { |c| format("%%%02X", c.ord) }
|
|
333
|
+
end
|
|
334
|
+
|
|
335
|
+
def invalid(message)
|
|
336
|
+
Error.new(status: 0, code: "invalid_request", message: message)
|
|
337
|
+
end
|
|
338
|
+
|
|
339
|
+
def now
|
|
340
|
+
Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
341
|
+
end
|
|
342
|
+
|
|
343
|
+
def job_failure(job)
|
|
344
|
+
err = job["error"].is_a?(Hash) ? job["error"] : {}
|
|
345
|
+
code = err["code"].is_a?(String) && !err["code"].empty? ? err["code"] : "processing_failed"
|
|
346
|
+
message = err["message"].is_a?(String) ? err["message"] : "the job failed"
|
|
347
|
+
Error.new(status: 422, code: code, message: message, request_id: "")
|
|
348
|
+
end
|
|
349
|
+
|
|
350
|
+
# The answer's JSON, which must be a +kind+ (Hash or Array); anything else is an error with the
|
|
351
|
+
# answer's status and code http_<status>, never a raw parse exception.
|
|
352
|
+
def parse_json(result, kind = Hash)
|
|
353
|
+
value = JSON.parse(result.text)
|
|
354
|
+
return value if value.is_a?(kind)
|
|
355
|
+
|
|
356
|
+
raise ArgumentError, "not a #{kind}"
|
|
357
|
+
rescue JSON::ParserError, ArgumentError, EncodingError
|
|
358
|
+
raise Error.new(status: result.status, code: "http_#{result.status}",
|
|
359
|
+
message: "the answer is not the expected JSON #{kind == Array ? 'list' : 'object'}",
|
|
360
|
+
request_id: result.request_id)
|
|
361
|
+
end
|
|
362
|
+
|
|
363
|
+
# The API's multipart limits, checked before any request.
|
|
364
|
+
def check_fields(fields)
|
|
365
|
+
fields.each do |_, name, _|
|
|
366
|
+
next if FIELD_NAME.match?(name)
|
|
367
|
+
|
|
368
|
+
raise invalid("field name #{name.inspect} must be 1 to 64 letters, digits, '_', '-' or '.'")
|
|
369
|
+
end
|
|
370
|
+
if fields.size > MAX_FIELDS
|
|
371
|
+
raise invalid("a request takes at most #{MAX_FIELDS} fields (got #{fields.size}, including the instructions)")
|
|
372
|
+
end
|
|
373
|
+
|
|
374
|
+
urls = fields.count { |kind, name, _| kind == :text && name.end_with?("_url") }
|
|
375
|
+
raise invalid("at most #{MAX_URL_FIELDS} inputs may be URLs (got #{urls})") if urls > MAX_URL_FIELDS
|
|
376
|
+
end
|
|
377
|
+
|
|
378
|
+
def request(method, path, fields)
|
|
379
|
+
body, content_type = Multipart.encode(fields) if fields
|
|
380
|
+
check_fields(fields) if fields
|
|
381
|
+
idempotency_key = SecureRandom.uuid if method == :post
|
|
382
|
+
attempt = 0
|
|
383
|
+
loop do
|
|
384
|
+
return perform(method, path, body, content_type, idempotency_key)
|
|
385
|
+
rescue Error => e
|
|
386
|
+
raise if attempt >= @max_retries || !retryable?(e, method)
|
|
387
|
+
|
|
388
|
+
sleep(e.retry_after.nil? ? 0.5 * (2**attempt) : [e.retry_after, MAX_RETRY_WAIT].min)
|
|
389
|
+
attempt += 1
|
|
390
|
+
end
|
|
391
|
+
end
|
|
392
|
+
|
|
393
|
+
def retryable_answer?(err)
|
|
394
|
+
RETRY.fetch(err.status, []).include?(err.code)
|
|
395
|
+
end
|
|
396
|
+
|
|
397
|
+
# GET and DELETE: any answer above and any transport failure. POST: only the answers above and
|
|
398
|
+
# transport failures known to precede the request being sent.
|
|
399
|
+
def retryable?(err, method)
|
|
400
|
+
return retryable_answer?(err) unless err.code == "network"
|
|
401
|
+
|
|
402
|
+
method != :post || (err.is_a?(NetworkError) && err.before_send)
|
|
403
|
+
end
|
|
404
|
+
|
|
405
|
+
def perform(method, path, body, content_type, idempotency_key)
|
|
406
|
+
uri = URI.parse(@base_url + path)
|
|
407
|
+
req = { get: Net::HTTP::Get, post: Net::HTTP::Post, delete: Net::HTTP::Delete }.fetch(method).new(uri)
|
|
408
|
+
req["User-Agent"] = USER_AGENT
|
|
409
|
+
req["Accept"] = "*/*"
|
|
410
|
+
req["Authorization"] = "Bearer #{@api_key}" unless path == "/v1/health"
|
|
411
|
+
req["Idempotency-Key"] = idempotency_key if idempotency_key
|
|
412
|
+
if body
|
|
413
|
+
req["Content-Type"] = content_type
|
|
414
|
+
req.body = body
|
|
415
|
+
end
|
|
416
|
+
http = Net::HTTP.new(uri.hostname, uri.port)
|
|
417
|
+
http.use_ssl = uri.scheme == "https"
|
|
418
|
+
http.open_timeout = [CONNECT_TIMEOUT, @timeout].min
|
|
419
|
+
http.read_timeout = @timeout
|
|
420
|
+
http.write_timeout = @timeout
|
|
421
|
+
http.max_retries = 0
|
|
422
|
+
http.ignore_eof = false # a body shorter than its Content-Length is a network error
|
|
423
|
+
phase = :connect
|
|
424
|
+
res = Timeout.timeout(@timeout) do
|
|
425
|
+
http.start do |h|
|
|
426
|
+
# Connected: from here on the request may have reached the server.
|
|
427
|
+
phase = :sent
|
|
428
|
+
h.request(req)
|
|
429
|
+
end
|
|
430
|
+
end
|
|
431
|
+
to_result(res)
|
|
432
|
+
rescue *NETWORK_ERRORS => e
|
|
433
|
+
before = phase == :connect && CONNECT_ERRORS.any? { |k| e.is_a?(k) }
|
|
434
|
+
raise NetworkError.new(message: "Network error: #{e.message}", before_send: before)
|
|
435
|
+
end
|
|
436
|
+
|
|
437
|
+
def to_result(res)
|
|
438
|
+
status = res.code.to_i
|
|
439
|
+
data = (res.body || "").b
|
|
440
|
+
request_id = res["x-request-id"]
|
|
441
|
+
if status >= 200 && status < 300
|
|
442
|
+
units = Integer(res["x-nexpdf-units"] || "0", exception: false) || 0
|
|
443
|
+
return Result.new(bytes: data, content_type: res["content-type"].to_s, units: units,
|
|
444
|
+
request_id: request_id.to_s, status: status)
|
|
445
|
+
end
|
|
446
|
+
raise error_for(status, data, request_id, res["retry-after"])
|
|
447
|
+
end
|
|
448
|
+
|
|
449
|
+
def error_for(status, data, request_id, retry_after)
|
|
450
|
+
code = "http_#{status}"
|
|
451
|
+
message = "HTTP #{status}"
|
|
452
|
+
parsed = begin
|
|
453
|
+
JSON.parse(data.dup.force_encoding(Encoding::UTF_8))
|
|
454
|
+
rescue JSON::ParserError, EncodingError
|
|
455
|
+
nil
|
|
456
|
+
end
|
|
457
|
+
if parsed.is_a?(Hash)
|
|
458
|
+
err = parsed["error"]
|
|
459
|
+
if err.is_a?(Hash) && err["code"].is_a?(String)
|
|
460
|
+
code = err["code"]
|
|
461
|
+
message = err["message"] if err["message"].is_a?(String)
|
|
462
|
+
end
|
|
463
|
+
request_id = parsed["request_id"] if parsed["request_id"].is_a?(String)
|
|
464
|
+
end
|
|
465
|
+
Error.new(status: status, code: code, message: message, request_id: request_id,
|
|
466
|
+
retry_after: parse_retry_after(retry_after))
|
|
467
|
+
end
|
|
468
|
+
|
|
469
|
+
def parse_retry_after(value)
|
|
470
|
+
return nil if value.nil? || value.strip.empty?
|
|
471
|
+
|
|
472
|
+
n = Float(value.strip, exception: false)
|
|
473
|
+
return [n, 0.0].max if n
|
|
474
|
+
|
|
475
|
+
[Time.httpdate(value) - Time.now, 0.0].max
|
|
476
|
+
rescue ArgumentError
|
|
477
|
+
nil
|
|
478
|
+
end
|
|
479
|
+
end
|
|
480
|
+
|
|
481
|
+
# multipart/form-data (RFC 7578) with CRLF line endings, built by hand.
|
|
482
|
+
module Multipart
|
|
483
|
+
CRLF = "\r\n"
|
|
484
|
+
|
|
485
|
+
# fields: [:file, name, data, filename] or [:text, name, value]. Returns [body, content_type].
|
|
486
|
+
def self.encode(fields)
|
|
487
|
+
boundary = nil
|
|
488
|
+
loop do
|
|
489
|
+
boundary = "----nexpdf-cloud-#{SecureRandom.hex(16)}"
|
|
490
|
+
break unless fields.any? { |f| f[2].b.include?(boundary) }
|
|
491
|
+
end
|
|
492
|
+
out = String.new(encoding: Encoding::BINARY)
|
|
493
|
+
fields.each do |kind, name, value, filename|
|
|
494
|
+
out << "--#{boundary}#{CRLF}"
|
|
495
|
+
if kind == :file
|
|
496
|
+
out << %(Content-Disposition: form-data; name="#{quote(name)}"; filename="#{quote(filename)}"#{CRLF}).b
|
|
497
|
+
out << "Content-Type: application/octet-stream#{CRLF}#{CRLF}"
|
|
498
|
+
else
|
|
499
|
+
out << %(Content-Disposition: form-data; name="#{quote(name)}"#{CRLF}#{CRLF}).b
|
|
500
|
+
end
|
|
501
|
+
out << value.b << CRLF
|
|
502
|
+
end
|
|
503
|
+
out << "--#{boundary}--#{CRLF}"
|
|
504
|
+
[out, "multipart/form-data; boundary=#{boundary}"]
|
|
505
|
+
end
|
|
506
|
+
|
|
507
|
+
def self.quote(value)
|
|
508
|
+
value.to_s.gsub('"', "%22").gsub("\r", "%0D").gsub("\n", "%0A")
|
|
509
|
+
end
|
|
510
|
+
end
|
|
511
|
+
end
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module NexPdfCloud
|
|
4
|
+
# The one error every NexPDF Cloud call raises.
|
|
5
|
+
#
|
|
6
|
+
# - +status+: HTTP status, or 0 for client-side and network errors.
|
|
7
|
+
# - +code+: the API's +error.code+, or +missing_api_key+, +invalid_request+, +network+ or
|
|
8
|
+
# +http_<status>+.
|
|
9
|
+
# - +message+: a readable explanation.
|
|
10
|
+
# - +request_id+: the request id, when the server gave one.
|
|
11
|
+
# - +retry_after+: seconds to wait, when the response had +Retry-After+.
|
|
12
|
+
class Error < StandardError
|
|
13
|
+
attr_reader :status, :code, :request_id, :retry_after
|
|
14
|
+
|
|
15
|
+
def initialize(status:, code:, message:, request_id: nil, retry_after: nil)
|
|
16
|
+
super(message)
|
|
17
|
+
@status = status
|
|
18
|
+
@code = code
|
|
19
|
+
@request_id = request_id
|
|
20
|
+
@retry_after = retry_after
|
|
21
|
+
end
|
|
22
|
+
end
|
|
23
|
+
end
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module NexPdfCloud
|
|
4
|
+
# A file to upload: a path on disk, bytes with a file name, or a URL the server downloads.
|
|
5
|
+
# A plain path string (or Pathname) is accepted wherever a file is; a plain string is always a
|
|
6
|
+
# path, never a URL (use File.url).
|
|
7
|
+
class File
|
|
8
|
+
attr_reader :name, :url
|
|
9
|
+
|
|
10
|
+
# A file on disk, read when the request is sent. Its name is the path's base name.
|
|
11
|
+
def self.path(path)
|
|
12
|
+
new(path: path.to_s)
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
# Bytes in memory, uploaded under +name+ (for example "report.pdf").
|
|
16
|
+
def self.bytes(data, name)
|
|
17
|
+
new(data: data, name: name)
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
# A file the server downloads from an http or https URL. It is sent as the text field
|
|
21
|
+
# "<name>_url"; any other scheme is refused with invalid_request before the request.
|
|
22
|
+
def self.url(url)
|
|
23
|
+
new(url: url.to_s)
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
class << self
|
|
27
|
+
alias from_path path
|
|
28
|
+
alias from_bytes bytes
|
|
29
|
+
alias from_url url
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
def initialize(path: nil, data: nil, name: nil, url: nil)
|
|
33
|
+
raise ArgumentError, "give one of path:, data: or url:" unless [path, data, url].compact.size == 1
|
|
34
|
+
raise ArgumentError, "bytes need a file name" if data && (name.nil? || name.to_s.empty?)
|
|
35
|
+
|
|
36
|
+
@path = path
|
|
37
|
+
@data = data&.b
|
|
38
|
+
@url = url
|
|
39
|
+
@name = (name || (path && ::File.basename(path)) || "file").to_s
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
# The file's bytes (not for a URL input).
|
|
43
|
+
def read
|
|
44
|
+
raise ArgumentError, "a URL input has no bytes" if @url
|
|
45
|
+
|
|
46
|
+
@data || ::File.binread(@path)
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
# Turns a path string, Pathname or File into a File.
|
|
50
|
+
def self.coerce(value)
|
|
51
|
+
case value
|
|
52
|
+
when File then value
|
|
53
|
+
when String then path(value)
|
|
54
|
+
else
|
|
55
|
+
return path(value.to_path) if value.respond_to?(:to_path)
|
|
56
|
+
|
|
57
|
+
raise ArgumentError, "not a file input: #{value.inspect} (use NexPdfCloud::File.bytes(data, name) for bytes)"
|
|
58
|
+
end
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
end
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
|
|
5
|
+
module NexPdfCloud
|
|
6
|
+
# A fluent builder for /v1/build instructions. Every method returns the builder.
|
|
7
|
+
#
|
|
8
|
+
# NexPdfCloud::Instructions.new.file("doc", pages: 0..-1).watermark("DRAFT").pdf
|
|
9
|
+
class Instructions
|
|
10
|
+
def initialize
|
|
11
|
+
@parts = []
|
|
12
|
+
@actions = []
|
|
13
|
+
@output = nil
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
# Parts
|
|
17
|
+
|
|
18
|
+
# A part read from the uploaded file field +name+. +pages+ is a Range (0..-1), an Array
|
|
19
|
+
# [start, end] or a Hash { start:, end: }; 0-based, -1 is the last page.
|
|
20
|
+
def file(name, pages: nil, password: nil)
|
|
21
|
+
@parts << compact(file: name, pages: page_range(pages), password: password)
|
|
22
|
+
self
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
# A part made by rendering the uploaded HTML field +name+.
|
|
26
|
+
def html(name, pages: nil)
|
|
27
|
+
@parts << compact(html: name, pages: page_range(pages))
|
|
28
|
+
self
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# Actions
|
|
32
|
+
|
|
33
|
+
# Adds a searchable text layer, for example ocr("eng+por").
|
|
34
|
+
def ocr(languages = nil)
|
|
35
|
+
act(compact(type: "ocr", languages: languages))
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def watermark(text)
|
|
39
|
+
act(type: "watermark", text: text)
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
# Rotates +pages+ (all pages when omitted) by a multiple of 90 degrees.
|
|
43
|
+
def rotate(degrees, pages = nil)
|
|
44
|
+
act(compact(type: "rotate", degrees: degrees, pages: pages&.to_a))
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
def delete_pages(pages)
|
|
48
|
+
act(type: "delete_pages", pages: pages.to_a)
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
def flatten_annotations
|
|
52
|
+
act(type: "flatten_annotations")
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
def flatten_forms
|
|
56
|
+
act(type: "flatten_forms")
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
def fill_form(values)
|
|
60
|
+
act(type: "fill_form", values: values)
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
# Redacts +query+; +mode+ is "text", "regex" or "pattern".
|
|
64
|
+
def redact(query, mode: nil, fill_white: nil)
|
|
65
|
+
act(compact(type: "redact", query: query, mode: mode&.to_s, fill_white: fill_white))
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
# Converts to PDF/A, for example pdfa("2b").
|
|
69
|
+
def pdfa(level = nil)
|
|
70
|
+
act(compact(type: "pdfa", level: level))
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
def pdfua(part: nil, lang: nil)
|
|
74
|
+
act(compact(type: "pdfua", part: part, lang: lang))
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
def optimize
|
|
78
|
+
act(type: "optimize")
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# Encrypts the PDF. Must be the last action.
|
|
82
|
+
def encrypt(owner_password, user_password: nil, permissions: nil)
|
|
83
|
+
act(compact(type: "encrypt", owner_password: owner_password, user_password: user_password,
|
|
84
|
+
permissions: permissions))
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# Signs the PDF. Must be the last action, with PDF output that is not linearized.
|
|
88
|
+
# +certificate+ names an uploaded PKCS#12 file; without it the server signs with a
|
|
89
|
+
# self-signed certificate. +appearance+ is { page: 0, rect: [llx, lly, urx, ury], text: "..." }
|
|
90
|
+
# (page and text optional) for a visible signature. +level+ is the PAdES level: "B-B" (the
|
|
91
|
+
# default), "B-T", "B-LT" or "B-LTA". +policy+ is a signature policy: "icp-brasil"
|
|
92
|
+
# (ICP-Brasil AD-RB at "B-B", AD-RT from "B-T"). +timestamp_authority+ is your own RFC 3161
|
|
93
|
+
# time-stamp authority, { url: "...", username: "...", password: "..." } or
|
|
94
|
+
# { url: "...", token: "..." } (credentials optional, only over https; needs "B-T" or above).
|
|
95
|
+
def sign(certificate: nil, password: nil, name: nil, reason: nil, location: nil, contact: nil,
|
|
96
|
+
field: nil, appearance: nil, level: nil, policy: nil, timestamp_authority: nil)
|
|
97
|
+
act(compact(type: "sign", certificate: certificate, password: password, name: name, reason: reason,
|
|
98
|
+
location: location, contact: contact, field: field,
|
|
99
|
+
appearance: sign_appearance(appearance), level: level, policy: policy,
|
|
100
|
+
timestamp_authority: sign_timestamp_authority(timestamp_authority)))
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
# Outputs (the last call wins)
|
|
104
|
+
|
|
105
|
+
def pdf(linearize: nil)
|
|
106
|
+
out(compact(type: "pdf", linearize: linearize))
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
def png(page: nil, dpi: nil)
|
|
110
|
+
out(compact(type: "png", page: page, dpi: dpi))
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
def markdown
|
|
114
|
+
out(type: "markdown")
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
# HTML output (named to_html because html adds an HTML part).
|
|
118
|
+
def to_html
|
|
119
|
+
out(type: "html")
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
def json
|
|
123
|
+
out(type: "json")
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
def docx
|
|
127
|
+
out(type: "docx")
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
def xlsx
|
|
131
|
+
out(type: "xlsx")
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
# A ZIP of PDFs: every +every+ pages, or one per range (each a Range, [start, end] or
|
|
135
|
+
# { start:, end: }). Give exactly one of the two.
|
|
136
|
+
def split(every: nil, ranges: nil)
|
|
137
|
+
out(compact(type: "split", every: every, ranges: ranges.nil? ? nil : self.class.page_ranges(ranges)))
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
# The plain instructions structure (a Hash with symbol keys).
|
|
141
|
+
def to_h
|
|
142
|
+
h = { parts: deep_copy(@parts) }
|
|
143
|
+
h[:actions] = deep_copy(@actions) unless @actions.empty?
|
|
144
|
+
h[:output] = deep_copy(@output) if @output
|
|
145
|
+
h
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
def to_json(*args)
|
|
149
|
+
to_h.to_json(*args)
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
private
|
|
153
|
+
|
|
154
|
+
def act(action)
|
|
155
|
+
@actions << action
|
|
156
|
+
self
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
def out(output)
|
|
160
|
+
@output = output
|
|
161
|
+
self
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
def compact(**fields)
|
|
165
|
+
fields.compact
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
def deep_copy(value)
|
|
169
|
+
Marshal.load(Marshal.dump(value))
|
|
170
|
+
end
|
|
171
|
+
|
|
172
|
+
def page_range(pages)
|
|
173
|
+
self.class.page_range(pages)
|
|
174
|
+
end
|
|
175
|
+
|
|
176
|
+
def sign_appearance(appearance)
|
|
177
|
+
return nil if appearance.nil?
|
|
178
|
+
|
|
179
|
+
get = ->(k) { appearance.key?(k) ? appearance[k] : appearance[k.to_s] }
|
|
180
|
+
compact(page: get.call(:page), rect: get.call(:rect).to_a, text: get.call(:text))
|
|
181
|
+
end
|
|
182
|
+
|
|
183
|
+
def sign_timestamp_authority(tsa)
|
|
184
|
+
return nil if tsa.nil?
|
|
185
|
+
|
|
186
|
+
get = ->(k) { tsa.key?(k) ? tsa[k] : tsa[k.to_s] }
|
|
187
|
+
compact(url: get.call(:url), username: get.call(:username), password: get.call(:password),
|
|
188
|
+
token: get.call(:token))
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
# A list of page ranges as [{ start:, end: }, ...].
|
|
192
|
+
def self.page_ranges(ranges)
|
|
193
|
+
ranges.map { |r| page_range(r) }
|
|
194
|
+
end
|
|
195
|
+
|
|
196
|
+
# A Ruby Range as { start:, end: } (both inclusive, 0-based, negative counts from the end): an exclusive
|
|
197
|
+
# range loses its last page (0...2 is pages 0 and 1) and an endless one runs to the last page (-1).
|
|
198
|
+
def self.range_hash(range)
|
|
199
|
+
first = range.begin || 0
|
|
200
|
+
last = range.end
|
|
201
|
+
if last.nil?
|
|
202
|
+
last = -1
|
|
203
|
+
elsif range.exclude_end?
|
|
204
|
+
raise ArgumentError, "empty page range #{range}" if last == first
|
|
205
|
+
last -= 1
|
|
206
|
+
end
|
|
207
|
+
{ start: first, end: last }
|
|
208
|
+
end
|
|
209
|
+
|
|
210
|
+
def self.page_range(pages)
|
|
211
|
+
case pages
|
|
212
|
+
when nil then nil
|
|
213
|
+
when Range then range_hash(pages)
|
|
214
|
+
when Array then { start: pages[0], end: pages[1] }
|
|
215
|
+
when Hash then { start: pages[:start] || pages["start"], end: pages[:end] || pages["end"] }
|
|
216
|
+
else raise ArgumentError, "pages must be a Range, [start, end] or { start:, end: }"
|
|
217
|
+
end
|
|
218
|
+
end
|
|
219
|
+
end
|
|
220
|
+
end
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module NexPdfCloud
|
|
4
|
+
# A successful answer: the output file and its metadata.
|
|
5
|
+
#
|
|
6
|
+
# - +bytes+ (alias +body+): the response body (a binary String).
|
|
7
|
+
# - +content_type+: the +Content-Type+ header.
|
|
8
|
+
# - +units+: units charged (+x-nexpdf-units+), 0 when absent.
|
|
9
|
+
# - +request_id+: the request id (+x-request-id+).
|
|
10
|
+
# - +status+: the HTTP status (200).
|
|
11
|
+
class Result
|
|
12
|
+
attr_reader :bytes, :content_type, :units, :request_id, :status
|
|
13
|
+
alias body bytes
|
|
14
|
+
|
|
15
|
+
def initialize(bytes:, content_type:, units:, request_id:, status: 200)
|
|
16
|
+
@bytes = bytes
|
|
17
|
+
@content_type = content_type
|
|
18
|
+
@units = units
|
|
19
|
+
@request_id = request_id
|
|
20
|
+
@status = status
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
# The body decoded as UTF-8 (Markdown, HTML and JSON outputs).
|
|
24
|
+
def text
|
|
25
|
+
@bytes.dup.force_encoding(Encoding::UTF_8)
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
# Writes the bytes to +path+ and returns the path.
|
|
29
|
+
def save(path)
|
|
30
|
+
::File.binwrite(path, @bytes)
|
|
31
|
+
path
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def inspect
|
|
35
|
+
"#<NexPdfCloud::Result content_type=#{@content_type.inspect} units=#{@units} " \
|
|
36
|
+
"request_id=#{@request_id.inspect} bytes=#{@bytes.bytesize}>"
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
end
|
data/lib/nexpdf_cloud.rb
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Client for the NexPDF Cloud API: convert, OCR, merge, extract and build PDFs over HTTP.
|
|
4
|
+
#
|
|
5
|
+
# require "nexpdf_cloud"
|
|
6
|
+
# nexpdf = NexPdfCloud::Client.new # reads NEXPDF_API_KEY
|
|
7
|
+
# nexpdf.convert_to_pdf("report.docx").save("report.pdf")
|
|
8
|
+
#
|
|
9
|
+
# Docs: https://nexpdf.dev/docs/cloud
|
|
10
|
+
module NexPdfCloud
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
require_relative "nexpdf_cloud/version"
|
|
14
|
+
require_relative "nexpdf_cloud/error"
|
|
15
|
+
require_relative "nexpdf_cloud/file"
|
|
16
|
+
require_relative "nexpdf_cloud/result"
|
|
17
|
+
require_relative "nexpdf_cloud/instructions"
|
|
18
|
+
require_relative "nexpdf_cloud/client"
|
metadata
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: nexpdf-cloud
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 1.1.1
|
|
5
|
+
platform: ruby
|
|
6
|
+
authors:
|
|
7
|
+
- NexDevIT
|
|
8
|
+
bindir: bin
|
|
9
|
+
cert_chain: []
|
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
|
11
|
+
dependencies: []
|
|
12
|
+
description: Convert, OCR, merge, extract and build PDFs with the NexPDF Cloud HTTP
|
|
13
|
+
API. Uses only the Ruby standard library.
|
|
14
|
+
executables: []
|
|
15
|
+
extensions: []
|
|
16
|
+
extra_rdoc_files: []
|
|
17
|
+
files:
|
|
18
|
+
- README.md
|
|
19
|
+
- lib/nexpdf_cloud.rb
|
|
20
|
+
- lib/nexpdf_cloud/client.rb
|
|
21
|
+
- lib/nexpdf_cloud/error.rb
|
|
22
|
+
- lib/nexpdf_cloud/file.rb
|
|
23
|
+
- lib/nexpdf_cloud/instructions.rb
|
|
24
|
+
- lib/nexpdf_cloud/result.rb
|
|
25
|
+
- lib/nexpdf_cloud/version.rb
|
|
26
|
+
homepage: https://nexpdf.dev/docs/cloud
|
|
27
|
+
licenses:
|
|
28
|
+
- LicenseRef-Proprietary
|
|
29
|
+
metadata:
|
|
30
|
+
documentation_uri: https://nexpdf.dev/docs/cloud
|
|
31
|
+
rubygems_mfa_required: 'true'
|
|
32
|
+
rdoc_options: []
|
|
33
|
+
require_paths:
|
|
34
|
+
- lib
|
|
35
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
36
|
+
requirements:
|
|
37
|
+
- - ">="
|
|
38
|
+
- !ruby/object:Gem::Version
|
|
39
|
+
version: '3.0'
|
|
40
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
41
|
+
requirements:
|
|
42
|
+
- - ">="
|
|
43
|
+
- !ruby/object:Gem::Version
|
|
44
|
+
version: '0'
|
|
45
|
+
requirements: []
|
|
46
|
+
rubygems_version: 4.0.16
|
|
47
|
+
specification_version: 4
|
|
48
|
+
summary: Client for the NexPDF Cloud API
|
|
49
|
+
test_files: []
|