Skip to content

Commit

Permalink
use DocRaptor
Browse files Browse the repository at this point in the history
  • Loading branch information
yshmarov committed Dec 2, 2023
1 parent 7d90a78 commit 0cce2a5
Show file tree
Hide file tree
Showing 13 changed files with 218 additions and 2 deletions.
4 changes: 3 additions & 1 deletion Gemfile
Expand Up @@ -42,7 +42,7 @@ gem "tzinfo-data", platforms: %i[ windows jruby ]
gem "bootsnap", require: false

# Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images]
# gem "image_processing", "~> 1.2"
gem "image_processing", "~> 1.2"

group :development, :test do
# See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem
Expand All @@ -66,3 +66,5 @@ group :test do
gem "capybara"
gem "selenium-webdriver"
end

gem "docraptor"
15 changes: 15 additions & 0 deletions Gemfile.lock
Expand Up @@ -98,13 +98,21 @@ GEM
debug (1.8.0)
irb (>= 1.5.0)
reline (>= 0.3.1)
docraptor (3.1.0)
typhoeus (~> 1.0, >= 1.0.1)
drb (2.1.1)
ruby2_keywords
erubi (1.12.0)
ethon (0.16.0)
ffi (>= 1.15.0)
ffi (1.16.3)
globalid (1.2.1)
activesupport (>= 6.1)
i18n (1.14.1)
concurrent-ruby (~> 1.0)
image_processing (1.12.2)
mini_magick (>= 4.9.5, < 5)
ruby-vips (>= 2.0.17, < 3)
importmap-rails (1.2.1)
actionpack (>= 6.0.0)
railties (>= 6.0.0)
Expand All @@ -125,6 +133,7 @@ GEM
net-smtp
marcel (1.0.2)
matrix (0.4.2)
mini_magick (4.12.0)
mini_mime (1.1.5)
minitest (5.20.0)
msgpack (1.7.2)
Expand Down Expand Up @@ -200,6 +209,8 @@ GEM
reline (0.3.9)
io-console (~> 0.5)
rexml (3.2.6)
ruby-vips (2.2.0)
ffi (~> 1.12)
ruby2_keywords (0.0.5)
rubyzip (2.3.2)
selenium-webdriver (4.14.0)
Expand All @@ -222,6 +233,8 @@ GEM
actionpack (>= 6.0.0)
activejob (>= 6.0.0)
railties (>= 6.0.0)
typhoeus (1.4.0)
ethon (>= 0.9.0)
tzinfo (2.0.6)
concurrent-ruby (~> 1.0)
web-console (4.2.1)
Expand All @@ -247,6 +260,8 @@ DEPENDENCIES
bootsnap
capybara
debug
docraptor
image_processing (~> 1.2)
importmap-rails
jbuilder
pg (~> 1.1)
Expand Down
1 change: 1 addition & 0 deletions app/controllers/invoices_controller.rb
Expand Up @@ -16,6 +16,7 @@ def create

respond_to do |format|
if @invoice.save
InvoicePdfJob.perform_now(@invoice)
format.html { redirect_to invoice_url(@invoice), notice: "Invoice was successfully created." }
else
format.html { render :new, status: :unprocessable_entity }
Expand Down
55 changes: 55 additions & 0 deletions app/jobs/invoice_pdf_job.rb
@@ -0,0 +1,55 @@
DocRaptor.configure do |config|
config.username = "YOUR_API_KEY_HERE"
# config.debugging = true
end

class InvoicePdfJob < ApplicationJob
queue_as :default

def perform(invoice)
docraptor = DocRaptor::DocApi.new

document_content = ApplicationController.render(
template: "invoices/show",
layout: "layouts/pdf",
assigns: { invoice: invoice }
)

begin
response = docraptor.create_doc(
test: true, # test documents are free but watermarked
document_type: "pdf",
document_content: document_content,
# document_content: "<html><body>Hello World!</body></html>",
# document_url: "https://docraptor.com/examples/invoice.html",
# javascript: true,
# prince_options: {
# media: "print", # @media 'screen' or 'print' CSS
# baseurl: "https://yoursite.com", # the base URL for any relative URLs
# }
)

# hosted_document_url = docraptor.create_hosted_doc(
# test: true, # test documents are free but watermarked
# document_type: "pdf",
# document_content: document_content,
# )
# invoice.update(docraptor_document_url: hosted_document_url.download_url)

# ActiveStorage
invoice.pdf_document.attach(io: StringIO.new(response), filename: "invoice#{invoice.id}.pdf", content_type: "application/pdf")
# ActionMailer
InvoiceMailer.created(invoice).deliver_later if invoice.pdf_document.attached?

# store it locally
File.write("docraptor-hello.pdf", response, mode: "wb")
puts "Successfully created docraptor-hello.pdf!"
rescue DocRaptor::ApiError => error
puts "#{error.class}: #{error.message}"
puts error.code
puts error.response_body
puts error.backtrace[0..3].join("\n")
end
# Do something later
end
end
9 changes: 9 additions & 0 deletions app/mailers/invoice_mailer.rb
@@ -0,0 +1,9 @@
class InvoiceMailer < ApplicationMailer
def created(invoice)
@invoice = invoice
@greeting = "Hi"

attachments["invoice.pdf"] = @invoice.pdf_document.download if @invoice.pdf_document.attached?
mail to: invoice.email, subject: "Invoice #{@invoice.id}"
end
end
1 change: 1 addition & 0 deletions app/models/invoice.rb
Expand Up @@ -2,6 +2,7 @@ class Invoice < ApplicationRecord
validates :email, :product, :price, :quantity, :total, presence: true

before_validation :calculate_total
has_one_attached :pdf_document

private

Expand Down
5 changes: 5 additions & 0 deletions app/views/invoice_mailer/created.html.erb
@@ -0,0 +1,5 @@
<h1>Invoice#created</h1>

<p>
<%= @greeting %>, find me in app/views/invoice_mailer/created.html.erb
</p>
10 changes: 10 additions & 0 deletions app/views/invoices/show.html.erb
@@ -1 +1,11 @@
<%= render @invoice %>
<% if @invoice.pdf_document.attached? %>
<% if @invoice.pdf_document.representable? %>
<%= image_tag @invoice.pdf_document.representation(resize_to_limit: [200, 200]) %>
<% end %>
<%= @invoice.pdf_document.blob.filename %>
<%= number_to_human_size @invoice.pdf_document.blob.byte_size %>
<%= link_to 'Open in new tab', rails_blob_path(@invoice.pdf_document, disposition: "inline"), target: :_blank %>
<%= link_to 'Download', rails_blob_path(@invoice.pdf_document, disposition: "attachment") %>
<% end %>
16 changes: 16 additions & 0 deletions app/views/layouts/pdf.html.erb
@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html>
<head>
<title>DocraptorHtmlToPdf</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%#= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
<%#= javascript_importmap_tags %>
</head>

<body>
<%= yield %>
</body>
</html>
@@ -0,0 +1,57 @@
# This migration comes from active_storage (originally 20170806125915)
class CreateActiveStorageTables < ActiveRecord::Migration[7.0]
def change
# Use Active Record's configured type for primary and foreign keys
primary_key_type, foreign_key_type = primary_and_foreign_key_types

create_table :active_storage_blobs, id: primary_key_type do |t|
t.string :key, null: false
t.string :filename, null: false
t.string :content_type
t.text :metadata
t.string :service_name, null: false
t.bigint :byte_size, null: false
t.string :checksum

if connection.supports_datetime_with_precision?
t.datetime :created_at, precision: 6, null: false
else
t.datetime :created_at, null: false
end

t.index [ :key ], unique: true
end

create_table :active_storage_attachments, id: primary_key_type do |t|
t.string :name, null: false
t.references :record, null: false, polymorphic: true, index: false, type: foreign_key_type
t.references :blob, null: false, type: foreign_key_type

if connection.supports_datetime_with_precision?
t.datetime :created_at, precision: 6, null: false
else
t.datetime :created_at, null: false
end

t.index [ :record_type, :record_id, :name, :blob_id ], name: :index_active_storage_attachments_uniqueness, unique: true
t.foreign_key :active_storage_blobs, column: :blob_id
end

create_table :active_storage_variant_records, id: primary_key_type do |t|
t.belongs_to :blob, null: false, index: false, type: foreign_key_type
t.string :variation_digest, null: false

t.index [ :blob_id, :variation_digest ], name: :index_active_storage_variant_records_uniqueness, unique: true
t.foreign_key :active_storage_blobs, column: :blob_id
end
end

private
def primary_and_foreign_key_types
config = Rails.configuration.generators
setting = config.options[config.orm][:primary_key_type]
primary_key_type = setting || :primary_key
foreign_key_type = setting || :bigint
[primary_key_type, foreign_key_type]
end
end
@@ -0,0 +1,5 @@
class AddDocraptorDocumentUrlToInvoices < ActiveRecord::Migration[7.1]
def change
add_column :invoices, :docraptor_document_url, :text
end
end
33 changes: 32 additions & 1 deletion db/schema.rb

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions test/mailers/previews/invoice_mailer_preview.rb
@@ -0,0 +1,9 @@
# Preview all emails at http://localhost:3000/rails/mailers/invoice_mailer
class InvoiceMailerPreview < ActionMailer::Preview

# Preview this email at http://localhost:3000/rails/mailers/invoice_mailer/created
def created
InvoiceMailer.created(Invoice.last)
end

end

0 comments on commit 0cce2a5

Please sign in to comment.