-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrender.rb
More file actions
49 lines (41 loc) · 1.55 KB
/
Copy pathrender.rb
File metadata and controls
49 lines (41 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# Render a CII XML file into a human-readable PDF using the InvoiceXML API.
# The rendered PDF is a preview for people to read: the XML file remains the
# authoritative invoice for compliance and tax purposes.
#
# Get API key: https://www.invoicexml.com/account/authentication
# Docs: https://www.invoicexml.com/docs/api/render/cii/to/pdf
#
# Ruby 3.x, standard library only. Set the INVOICEXML_API_KEY
# environment variable to the raw key, without the "Bearer " prefix.
#
# Usage: ruby render.rb [path/to/invoice.xml] [preview.pdf]
require "net/http"
require "uri"
BASE_URL = "https://api.invoicexml.com"
API_KEY = ENV.fetch("INVOICEXML_API_KEY")
def api_http(uri)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.open_timeout = 10
http.read_timeout = 120
http
end
def render_cii(xml_path, pdf_path)
uri = URI("#{BASE_URL}/v1/render/cii/to/pdf")
request = Net::HTTP::Post.new(uri)
request["Authorization"] = "Bearer #{API_KEY}"
File.open(xml_path, "rb") do |file|
# Label language for the rendered PDF: en, de, or fr. Defaults to en.
request.set_form([["file", file], ["language", "en"]], "multipart/form-data")
response = api_http(uri).request(request)
unless response.is_a?(Net::HTTPSuccess)
warn "InvoiceXML API error #{response.code}: #{response.body}"
exit 1
end
File.binwrite(pdf_path, response.body)
response.body.bytesize
end
end
pdf_path = ARGV.fetch(1, "invoice-preview.pdf")
bytes = render_cii(ARGV.fetch(0, "invoice-cii.xml"), pdf_path)
puts "Saved #{pdf_path} (#{bytes} bytes)"