Ruby
Basic script
require "net/http"
require "json"
require "uri"
API_URL = "https://api.markpdf.tech"
API_KEY = "YOUR_API_KEY"
def convert(pdf_path)
uri = URI("#{API_URL}/convert/raw?filename=#{File.basename(pdf_path)}&mode=fast")
req = Net::HTTP::Post.new(uri)
req["x-api-key"] = API_KEY
req["content-type"] = "application/pdf"
req.body = File.binread(pdf_path)
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: 300) { |http| http.request(req) }
return res.body if res.code == "200"
if res.code == "202"
job = JSON.parse(res.body)
poll_job(job["job_id"])
else
raise "HTTP #{res.code}: #{res.body}"
end
end
def poll_job(job_id)
loop do
sleep 5
uri = URI("#{API_URL}/jobs/#{job_id}")
req = Net::HTTP::Get.new(uri)
req["x-api-key"] = API_KEY
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
data = JSON.parse(res.body)
return data["body"] if data["status"] == "completed"
raise "Job failed: #{data['error']}" if data["status"] == "failed"
end
end
puts convert("report.pdf")
Rails controller
# app/controllers/convert_controller.rb
class ConvertController < ApplicationController
def create
file = params.require(:file)
api_url = Rails.application.credentials.flash_md_api_url
api_key = Rails.application.credentials.flash_md_api_key
uri = URI("#{api_url}/convert/raw?filename=#{CGI.escape(file.original_filename)}&mode=fast")
req = Net::HTTP::Post.new(uri)
req["x-api-key"] = api_key
req["content-type"] = file.content_type
req.body = file.read
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: 300) { |http| http.request(req) }
if res.code == "200"
render plain: res.body, content_type: "text/markdown"
elsif res.code == "202"
job = JSON.parse(res.body)
markdown = poll_job(api_url, api_key, job["job_id"])
render plain: markdown, content_type: "text/markdown"
else
render plain: res.body, status: res.code.to_i
end
end
private
def poll_job(api_url, api_key, job_id)
loop do
sleep 5
uri = URI("#{api_url}/jobs/#{job_id}")
req = Net::HTTP::Get.new(uri)
req["x-api-key"] = api_key
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
data = JSON.parse(res.body)
return data["body"] if data["status"] == "completed"
raise "Job failed: #{data['error']}" if data["status"] == "failed"
end
end
end
