Wicked pdf, failed to load PDF document - ruby-on-rails

I am trying to implement the gem wicked_pdf . After initial difficulties (fatal error (exception reentered)), I managed to start the server. I set up a pdf with the content "Hello world" for the test, but every time I want to open it, I get a "failed to load PDF document" notification
Controller
def index
respond_to do |format|
format.html
format.pdf do
render pdf: "index.pdf.haml",
layout: 'pdf.html.haml',
page_size: 'A4',
disposition: 'inline'
end
end
end
index.pdf.haml
Hello world
config/initializers/wicked_pdf.rb
# WickedPDF Global Configuration
#
# Use this to set up shared configuration options for your entire application.
# Any of the configuration options shown here can also be applied to single
# models by passing arguments to the `render :pdf` call.
#
# To learn more, check out the README:
#
# https://github.com/mileszs/wicked_pdf/blob/master/README.md
class WickedPdf
module PdfHelper
remove_method(:render)
end
end
WickedPdf.config = {
# Path to the wkhtmltopdf executable: This usually isn't needed if using
# one of the wkhtmltopdf-binary family of gems.
# exe_path: '/usr/local/bin/wkhtmltopdf',
# or
# exe_path: Gem.bin_path('wkhtmltopdf-binary', 'wkhtmltopdf')
# Layout file to be used for all PDFs
# (but can be overridden in `render :pdf` calls)
# layout: 'pdf.haml',
# Using wkhtmltopdf without an X server can be achieved by enabling the
# 'use_xvfb' flag. This will wrap all wkhtmltopdf commands around the
# 'xvfb-run' #command, in order to simulate an X server.
# use_xvfb: true,
}
config/initializers/mime_types.rb
# frozen_string_literal: true
# Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
Mime::Type.register "application/pdf", :pdf
Link to Screenshot: https://drive.google.com/file/d/1ujt8ANq16SrmSHJk45APMXXxm1l5q5ic/view?usp=sharing

Ok, so I downgraded wicked_pdf to version 1.4.0 and I removed:
class WickedPdf
module PdfHelper
remove_method(:render)
end
end
From config/initializers/wicked_pdf.rb, and now it works.

Related

Rails 6.1.4 Wicked PDF

I am attempting to implement Wicked PDF (https://github.com/mileszs/wicked_pdf/) in a Rails 6.1.4 project and am continually getting the following error messages on the console.
My configuration is as simple as it gets. The controller looks like:
class Api::V1::ProductsController < Api::V1::BaseController
def datasheet
#product = Product.active.friendly.find params[:id]
respond_to do |format|
format.pdf {
render "products/datasheet", pdf: "datasheet-#{#product.name}"
}
end
end
end
and the datasheet.haml file looks like:
%html
%head
%body
= "This and that"
The file encoding for the datasheet.haml is UTF-8, but this shouldn't matter because the text contains no special characters.
The Gemfile has both wicked_pdf and wkhtmltopdf-binary.
gem 'wicked_pdf'
gem 'wkhtmltopdf-binary'
I have executed the command rails generate wicked_pdf and it did generate the wicked_pdf.rb initializer, as expected.
I have tried putting Mime::Type.register "application/pdf", :pdf into the mime_types.rb file, but expect that this wouldn't matter because I am running Rails 6.
The response generated is:
We have another application running Rails 6.1.4 using wicked_pdf in, "ahem...", the exact same way successfully. Obviously something is different, I just cannot find out what...
Any suggestions on what I am overlooking? Your help is much appreciated!

Save xlsx file to disk in Sidekiq as background

I am trying to generate excel file in background by using axlsx and save it (Rails4.2). In GitHub page of axlsx, it says As of Rails 4.1 you must use render_to_string to render a mail attachment. However, it throws me a error NoMethodError: undefined method 'render_to_string' for #<CreateExcelSheetWorker:0x007fbccf51db30>
My worker class:
class CreateExcelSheetWorker
include Sidekiq::Worker
include Sidetiq::Schedulable
recurrence { daily }
def perform()
model = SomeModel.where(wanted: true).order(started_at: :desc)
xlsx = render_to_string handlers: [:axlsx], formats: [:xlsx], template: "template/file", locals: {model: model}
path = "/tmp/a.xlsx"
File.open(path, "w+") do |f|
f.write(xlsx)
end
end
end
I cannot figure out how to fix this, any help appreciated.
That render_to_string comment is for usage of the gem in actionmailers. Outside of any kind of view context, you'll have to use xlsx builder api directly. Something like this:
package = Axlsx::Package.new do |p|
p.workbook.add_worksheet(name: "Summary") do |sheet|
sheet.add_row ["foo", 1]
end
end
File.write(filename, package.to_stream.read)
Sergio's answer is fine. But, if you are wanting to use the axlsx_rails template, you can use this example, which builds a fake view context to render the template:
require 'abstract_controller'
require 'action_controller'
require 'action_view'
require 'active_record'
# require any helpers
require './app/helpers/application_helper'
# active record only if data is here
require './app/models/widget'
ActiveRecord::Base.establish_connection(
adapter: 'sqlite3',
database: 'db/development.sqlite3'
)
ActionController::Base.prepend_view_path "./app/views/"
# place data in view_assigns
view_assigns = {widgets: Widget.all}
av = ActionView::Base.new(ActionController::Base.view_paths, view_assigns)
av.class_eval do
# include any needed helpers (for the view)
include ApplicationHelper
end
# normal render statement
content = av.render template: 'widgets/index.xlsx.axlsx'
# do something with content, such as:
File.open("/tmp/with_runner.xlsx","w+b") {|f| f.puts content }
https://gist.github.com/straydogstudio/dceb775ead81470cea70

Rails - Serve static CSV file as assets in Development with Thin

I'm simply trying to write to a CSV file in dev with thin, but I am continually getting an error that says
No such file or directory - http://localhost:3000/assets/tplan_log.csv
However, my config looks like this:
development.rb
config.serve_static_assets = true
And my controller looks like this:
def csv
#this returns a valid path
log_path = view_context.asset_path 'plan_log.csv'
#error occurs here
CSV.open(log_path) do |csv|
csv << ["row","row1","row2"]
end
respond_to do |format|
format.js {render json: #diaggroup.errors, status: :unprocessable_entity}
end
end
Rails 3.2.12
Edit: To clarify, I'm looking for an answer on how to serve this file in development so that it is accessible. I know it's being served with asset pipeline, but there is no get method associated with it, so it's not able to be accessed.
This ended up being an issue with reference.
I was using a reference such as:
http://path/to/file.jpg
Rails wants:
/path/to/file.jpg

Where should I configure rails gems?

For example, I use mobylette gem and it's documentation says that I can configure it like this.
mobylette_config do |config|
config[:fallback_chains] = { mobile: [:mobile, :html] }
config[:skip_xhr_requests] = false
config[:mobile_user_agents] = proc { %r{iphone}i }
end
Only problem is that, I don't know where to put that code. I tried creating new file config/initializers/mobylette.rb, but I got no method 'mobylette_config' error when starting rails server.
So where should I put these gem configurations and specifically in this case mobylette configuration?
That would be the conventional place to put it -- config/initializers
You can also check that its being loaded by putting in a logger.debug in the initializer
logger.debug 'LOADED mobylette configuration'
You can quickly test if there's another problem by putting the config in your environment.rb file (which is not where I'd leave it)
Both of those should give you some more info to debug
This had me pulling my hair out too. But digging around in the source on github:
https://github.com/tscolari/mobylette/blob/master/lib/mobylette/respond_to_mobile_requests.rb
I found this in the comments:
# Example Usage:
#
# class ApplicationController...
# include Mobylette::RespondToMobileRequests
# ...
# mobylette_config do |config|
# config[:fall_back] = :html
# config[:skip_xhr_requests] = false
# config[:mobile_user_agents] = proc { %r{iphone|android}i }
# config[:devices] = {cool_phone: %r{cool\s+phone} }
# end
# ...
# end

How generate pdf in rake task using cron job rails 3

Hi i am using rails 3 and wicked pdf gem to generate pdf in my controllers.But now i want to
generate pdf in rake task which will run through cron jobs.After creating this PDF i will send
it in email.
this is my normal controller method to generate pdf
def generate_invoice_pdf
begin
#trunk_groups_orig = TrunkGroupSubscriber.all
render :pdf => "GenerateInvoice", :layout => false, :template => "/accountings/generate_invoice_pdf"
rescue => client
puts client.inspect
end
end
But how i can generate pdf in rake task
Many many thanks for any help
If you are using pdfkit or wicked_pdf then you can try this,see if it works.
Updating code
class PdfInvoice
def generate_invoice
#trunk_groups_orig = TrunkGroupSubscriber.all
content = File.read('#{Rails.root}/app/views/accountings/generate_invoice_pdf.erb')
template = ERB.new(content)
# THis will generate html content
html_content = template.result(binding)
# now you have html content
pdf= WickedPdf.new.pdf_from_string(html_content)
# then save to a file
save_path = Rails.root.join('pdfs','filename.pdf')
File.open(save_path, 'wb') do |file|
file << pdf
end
end
end
PdfInvoice.new.generate_pdf
#You can customize method based on your requirement,

Resources