convert embedded ruby file to PDF file instead of only HTML file using Rails 3 - ruby

I want to convert my embedded ruby file to PDF file after clicking on a link using Rails 3.I became able to convert simple html file to PDF file using pdfkit gem.I am explaining my code below.
users_controller.rb:
class UsersController < ApplicationController
def index
end
def download_pdf
#html = render_to_string(:action => "/users/download_pdf.html.erb")
#kit = PDFKit.new('http://google.com')
#kit = PDFKit.new(html)
#send_data(kit.to_pdf, :filename => 'report.pdf', :type => 'application/pdf', :disposition => 'inline')
kit = PDFKit.new("<h1>Hello</h1><p>This is PDF!!!</p>", :page_size => "A4")
send_data(kit.to_pdf, :filename => 'report.pdf', :type => 'application/pdf', :disposition => 'inline')
#file = kit.to_file('my_file_name.pdf')
end
end
In this controller page i did and got success to convert from HTML to PDF.
users/index.html.erb:
<p>
<%= link_to "Download pdf",download_pdf_path(:format => 'pdf') %>
</p>
When user will click on the above "download_pdf" link the download.html.erb will convert to PDF file and it should display as well as download in specified folder.The download.html.erb file is given below.
users/download.html.erb:
<h1>Hello Rails</h1>
The above file should convert into PDF file with proper css .If i have css for this like below.
application.css:
h1{
width:100px;
height:100px;
background-color:red;
}
How can i include this CSS in that PDF file.My other files are given below.
pdfkit.rb:
PDFKit.configure do |config|
#config.wkhtmltopdf =Rails.root.join('bin', 'wkhtmltopdf-i386').to_s
config.wkhtmltopdf='C:/wkhtmltopdf/bin/wkhtmltopdf.exe'
#config.default_options[:ignore_load_errors] = true
end
Please help me to resolve this issue and make this successfully.
By using wicked_pdf gem i am getting the following error.
error:
RuntimeError in UsersController#download_pdf
Error: Failed to execute:
["C:/wkhtmltopdf/bin/wkhtmltopdf.exe", "file://C:/DOCUME~1/SUBHRA~1/LOCALS~1/Temp/wicked_pdf20150527-3204-calx6j.html", "C:/DOCUME~1/SUBHRA~1/LOCALS~1/Temp/wicked_pdf_generated_file20150527-3204-59mbli.pdf"]
Error: PDF could not be generated!
Command Error: Loading pages (1/6)
[> ] 0%
[======> ] 10%
Error: Failed loading page file://c/DOCUME~1/SUBHRA~1/LOCALS~1/Temp/wicked_pdf20150527-3204-calx6j.html (sometimes it will work just to ignore this error with --load-error-handling ignore)
Exit with code 1 due to network error: ContentNotFoundError
check the below code for this gem.
users/users_controller.rb:
class UsersController < ApplicationController
def index
end
def download_pdf
render pdf: 'test',
layout: '/layouts/test',
template: '/users/test',
handlers: [:erb],
formats: [:pdf],
:save_to_file => Rails.root.join('public', "test.pdf")
end
end
wicked_pdf.rb:
WickedPdf.config = {
#:wkhtmltopdf => '/usr/local/bin/wkhtmltopdf',
#:layout => "pdf.html",
:exe_path => 'C:/wkhtmltopdf/bin/wkhtmltopdf.exe'
}

You can include your stylesheets by following:
def download_pdf
kit = PDFKit.new(File.open(Rails.root.join('app', 'views', 'users', 'download.html.erb')))
kit.stylesheets << Rails.root.join("app","assets","application.css")
send_data(kit.to_pdf, :filename => 'report.pdf', :type => 'application/pdf', :disposition => 'inline')
end

Related

Using model attribute as :filename when using paperclip gem

I'm getting an error when attempting to change the :filename of my paperclip attachment to equal an attribute on the class I'm attaching the paperclip file to.
When I use "#{self.company_name}" it errors out. Apparently in this scope, "self" is not Company. When I wrote this line I assumed that self is the instance of Company that I'm uploading this attachment to. Any idea how I can fix this? The Paperclip docs say to use ":filename" but I'd like to use the value of Company.company_name instead.
class Company < ActiveRecord::Base
include AliasAttrs
has_attached_file :company_logo, {
:storage => :ftp,
:path => "/logos/#{self.company_name}",
:url => FTP_CONFIG[:access_host]+"logos/:filename",
:ftp_servers => [
{
:host => FTP_CONFIG[:host],
:user => FTP_CONFIG[:user],
:password => FTP_CONFIG[:pass],
:port => 21 # optional, 21 by default
}
]
}
end
Update
I tried using the advice found in this post: https://robots.thoughtbot.com/paperclip-tips-and-updates
But now I am getting the following error when starting my server:
undefined method `interpolations' for Paperclip::Attachment:Class (NoMethodError)
It looks like the syntax for interpolations has changed. Updated it and it worked. Add the following to your model or create a paperclip.rb file in config/initializers
Paperclip.interpolates :company_name do |attachment, style|
attachment.instance.company_name
end

Export data to a .csv file on ruby app

I got an error
undefined method `form_for_results_path'
in my code to Export the data to a .csv file. Really don't know if I missed something. Here what I have:
item_controller
def export
CSV.open("result_data.csv", "w") do |csv|
csv << ["cod", "genre", "den_cont"]
end
end
In the view
<%= link_to 'Download CSV', form_for_results_path(#form), :method => :export %>
Thanks
Change it to this and read some more about rails basics.
<%= link_to 'Download CSV', controller: :item, action: :export%>
in your controller, you should do something like this, using rails send_data method:
def export
data = # your data in csv format
options = {
:filename => "some_name.csv",
:type => 'text/csv'
}
send_data(data, options)
end
you can also change your download link using a route_helper. add an entry in your routes file
get 'items/export', :as 'download_items_data"
then your link_to can look like this:
link_to 'Download CSV', download_items_data_path

redmine settings tab project

I want to put a new tab in the setting project on a Redmine plugin and I don't find how to do it.
I get the code of CCUL Project Managment plugin by ISITROL S.A.(www.isitrol.com) and replace de funcionlity with my funcionality, but I still can't change the name of the config_controller to my controller.
the helperpatch has this estructure:
require 'redmine'
require_dependency 'projects_helper'
module CCULProjectsHelperPatch
def self.included(base)
base.send(:include, ProjectsHelperMethodsCCUL)
base.class_eval do
unloadable
alias_method_chain :project_settings_tabs, :coste
end
end
end
module ProjectsHelperMethodsCCUL
def project_settings_tabs_with_coste
#tabs = project_settings_tabs_without_coste
#action = {:name => 'coste', :controller => 'coste_config', :action => :index, :partial => 'coste_config/index', :label => :tab_ccul}
Rails.logger.info "old_tabs: #{#tabs}"
Rails.logger.info "action: #{#action}"
#tabs << #action #if User.current.allowed_to?(action, #project)
#tabs
end
end
ProjectsHelper.send(:include, CCULProjectsHelperPatch) unless ProjectsHelper.included_modules.include? CCULProjectsHelperPatch
I've changed the name of the controller(and controller file's name), the view's folder and the name of the controller in the init file (I change pm_config to coste_pm)
This is the init file:
Rails.configuration.to_prepare do
require_dependency 'coste_project_helper_patch'
end
Redmine::Plugin.register :redmine_coste do
name 'Costes'
author 'Me'
description 'Plugin para calculo coste proyecto. Compatible con Redmine 2.3.x '
version '0.1.4'
project_module :coste do
permission :cost_manager, {:coste_config => [:index, :create], :coste_project => [:show]}
end
menu :project_menu, :coste, { :controller => 'coste_project', :action => 'show' }, :caption => :coste, :param => :project_id
menu :admin_menu, :coste, { :controller => 'coste_admin', :action => 'show' }, :caption => :coste
end
The error is "404 The page you were trying to acess doesn't exist or has been removed" when I try to access Settings of one project
I don't know what I need to change
I hope you can help me
I've found the problem, in the views templates of the settings the form had the old controller's name.
For who is looking for a way to put the setting project tab like me: I need take the database information in the view. Redmine doesn't call the controller when it creates the project settings tabs
And the code above is the basic to do it

send_data or send_file(ruby) not working in safari browser?

I used following code to send or downlaod file at client's browser.
That is perfectly working in all browser BUT in safari after clicking on link when i refresh the page it makes my session nil.
def export_csv
csv = CSV.generate(:force_quotes => true) do |line|
line <<["Employee Code", "Name", "Status", "Skills"]
end
send_data csv,
:type => 'text/csv; charset=iso-8859-1; header=present',
:disposition => "attachment; filename=EmployeeSkillsData-#{Time.now.strftime('%d-%m-%y--%H-%M')}.csv"
end
I tried this code with some other application also but result is same.
Please help to resolve this.
Thanks.
send_data csv,
:type => 'text/csv; charset=iso-8859-1; header=present',
:disposition => "inline", # optional
:filename=>"EmployeeSkillsData-#{Time.now.strftime('%d-%m-%y--%H-%M')}.csv"

error to customize error 404 rails 3.1 with hight_voltage gem

Hi guys I remove /page from high_voltage gem with this answer.
Remove page/ of High Voltage for statics page rails
I have in my routes for high_voltage this:
match '/:id' => 'high_voltage/pages#show', :as => :static, :via => :get
For maintenance page 404 in rails 3.1 I follow this fix http://techoctave.com/c7/posts/36-rails-3-0-rescue-from-routing-error-solution with errors_controller.rb with the next code:
def routing
render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false
end
Then I add to routes.rb the next code for maintenance page 404 in rails
match '*a', :to => 'errors#routing'
The problem is that if I put in browser www.mydomain.com/sdfs dont working 404 system error and show No such page: sdfs
but however if I put www.mydomain.com/a_controller/action/sdfs yes working fine the fix for error 404 page.
I think that problem is my routes.rb
I solved this problem by extending the HighVoltage::PagesController and modifying the error catching:
class PagesController < HighVoltage::PagesController
rescue_from ActionView::MissingTemplate do |exception|
render_not_found
end
end
In my case though, my 404 function resides in my application controller so that it can easily be called from any location. If you make the same change, you will also need to update your route:
match '/:id' => 'pages#show', :as => :static, :via => :get
Thank you kevinthopson for mi this dont working fine :(.
I have in my routes.rb:
match '/:id' => 'pages#show', :as => :static, :via => :get
I have added this in pages_controller.rb
class PagesController < HighVoltage::PagesController
rescue_from ActionView::MissingTemplate do |exception|
render_not_found
end
end
I have added this code to aplication_controller.rb:
def render_not_found
render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false
end
Working fine if you put now:
localhost:3000/dfadsfadsf
The problem now is that if you put for example that routes in navigation bar:
localhost:3000/users_or_static_page/asdfadfadfa
Dont working for me :(.

Resources