I have a method in which I'm trying to print a pdf directly from! As you can see here
I have to use system(lpr) command.This solutions works fine but in ubuntu not in windows or any other OSs. Do you know how to do it in windows ?
and this is my method:
def general_receipt_export
if params[:official_id].present?
#ids = params[:official_id].split(',')
#officials = Official.find(#ids)
pdf = render_to_string pdf: "#{#ids.map(&:inspect).join(',').to_s + '_receipt.pdf'}", :template => 'officials/general_receipt_export.html.erb', encoding: 'utf8',orientation: 'Landscape',page_size: 'A4'
render layout: false
save_path = Rails.root.join('public','pdfs', "#{#ids.map(&:inspect).join(',').to_s + '_receipt.pdf'}")
File.open(save_path, 'wb') do |file|
file << pdf
end
system("lpr", "public/pdfs/#{#ids.map(&:inspect).join(',').to_s + '_receipt.pdf'}")
else
render json:{messege: 'No letter to export'},status: 404
end
end
I've found an easier solution which is not related to the OS you are using!
This for Ruby:
<%= link_to 'print', 'your_link_here', :onclick => 'window.print();return false;'%>
And it equivalence in HTML:
<a onclick="window.print();return false;" href="your_link">print</a>
Thank you all for putting your time on this.
See this page for reference: https://technet.microsoft.com/en-us/library/cc731926(v=ws.11).aspx you would need a Line Printer Daemon (LPD) running on the Windows Machine. And would then be able to issue the command. You might need to change some of your security settings. I have not used Rails in a Windows machine in a long time so I am not too sure if the security settings affect it.
Are you sure the machine where you are printing has a Line Printer Daemon running?
From the page I linked above:
This example shows how to print the "Document.txt" text file to the
LaserPrinter1 printer queue on an LPD host at 10.0.0.45:
Lpr -S 10.0.0.45 -P LaserPrinter1 -o Document.txt
Hope that helps or guides you in the right direction.
Related
Ok - I have the following in my test/test_helper.rb:
def read_pdf_from_response(response)
file = Tempfile.new
file.write response.body.force_encoding('UTF-8')
begin
reader = PDF::Reader.new(file)
reader.pages.map(&:text).join.squeeze("\n")
ensure
file.close
file.unlink
end
end
I use it like this in an integration test:
get project_path(project, format: 'pdf')
read_response_from_pdf(#response).tap do |pdf|
assert_match(/whatever/, pdf)
end
This works fine as long as I run a test singly or when running all tests with only one worker, e.g. PARALLEL_WORKERS=1. But tests that use this method will fail intermittently when I run my suite with more than 1 parallel worker. My laptop has 8 cores, so that's normally what it's running with.
Here's the error:
PDF::Reader::MalformedPDFError: PDF malformed, expected 5 but found 96 instead
or sometimes: PDF::Reader::MalformedPDFError: PDF file is empty
The PDF reader is https://github.com/yob/pdf-reader which hasn't given any problems.
The controller that sends the PDF returns like so:
send_file out_file,
filename: "#{#project.name}.pdf",
type: 'application/pdf',
disposition: (params[:download] ? 'attachment' : 'inline')
I can't see why this isn't working. No files should ever have the same name at the same time, since I'm using Tempfile, right? How can I make all this run with parallel tests?
While I cannot confirm why this is happening the issue may be that:
You are forcing the encoding to "UTF-8" but PDF documents are binary files so this conversion could be damaging the PDF.
Some of the responses you are receiving are truly empty or malformed.
Maybe try this instead:
def read_pdf_from_response(response)
doc = StringIO.new(response.body.to_s)
begin
PDF::Reader.new(doc)
.pages
.map(&:text)
.join
.squeeze("\n")
rescue PDF::Reader::MalformedPDFError => e
# handle issues with the pdf itself
end
end
This will avoid the file system altogether while still using a compatible IO object and will make sure that the response is read as binary to avoid any conversion conflicts.
Whenever I try to generate a pdf using to_file, the process will just hang, and when I stop the development server I get Errno::ENOENT (No such file or directory - path/to/pdf). However, I am able to render a pdf inline using to_pdf. I'm also able to generate PDFs from the command line in the same folder that I'm trying to generate them in with to_file.
I'm using Rails 3.2.12 and pdfkit 0.8.2. I've tried using wkhtmltopdf versions 0.9.6 through 0.12.4. I'm on Ubuntu 14.04.
Example from controller:
html = render_to_string(:action => "show.html.erb", :formats => :html)
kit.stylesheets << "{Rails.root}/app/assets/stylesheets/stylesheet1.css"
kit.stylesheets << "#{Rails.root}/vendor/assets/stylesheets/stylesheet2.css"
kit.to_file("#{Rails.root}/folder_to_write_to/generated_pdf.pdf")
Turns out the issue was the asset pipeline conflicting with wkhtmltopdf. Added config.threadsafe! to development.rb and it started working.
Another issue can be the default options passed. For example, when I left the default print_media_type option in place, found this message in the log:
The switch --print-media-type, is not support using unpatched qt, and will be ignored."
Only when I override that does it work for me, either in the initializer or like so:
PDFKit.new(html, {print_media_type: false})
The message says it'll be ignored, but it wasn't. It was causing the file to not get generated.
I want to read only the first line of a file using Ruby in the fastest, simplest, most idiomatic way possible. What's the best approach?
(Specifically: I want to read the git commit UUID out of the REVISION file in my latest Capistrano-deployed Rails directory, and then output that to my tag. This will let me see at an http-glance what version is deployed to my server. If there's an entirely different & better way to do this, please let me know.)
This will read exactly one line and ensure that the file is properly closed immediately after.
strVar = File.open('somefile.txt') {|f| f.readline}
# or, in Ruby 1.8.7 and above: #
strVar = File.open('somefile.txt', &:readline)
puts strVar
Here's a concise idiomatic way to do it that properly opens the file for reading and closes it afterwards.
File.open('path.txt', &:gets)
If you want an empty file to cause an exception use this instead.
File.open('path.txt', &:readline)
Also, here's a quick & dirty implementation of head that would work for your purposes and in many other instances where you want to read a few more lines.
# Reads a set number of lines from the top.
# Usage: File.head('path.txt')
class File
def self.head(path, n = 1)
open(path) do |f|
lines = []
n.times do
line = f.gets || break
lines << line
end
lines
end
end
end
You can try this:
File.foreach('path_to_file').first
How to read the first line in a ruby file:
commit_hash = File.open("filename.txt").first
Alternatively you could just do a git-log from inside your application:
commit_hash = `git log -1 --pretty=format:"%H"`
The %H tells the format to print the full commit hash. There are also modules which allow you to access your local git repo from inside a Rails app in a more ruby-ish manner although I have never used them.
first_line = open("filename").gets
I think the jkupferman suggestion of investigating the git --pretty options makes the most sense, however yet another approach would be the head command e.g.
ruby -e 'puts `head -n 1 filename`' #(backtick before `head` and after `filename`)
Improving on the answer posted by #Chuck, I think it might be worthwhile to point out that if the file you are reading is empty, an EOFError exception will be thrown. Catch and ignore the exception:
def readit(filename)
text = ""
begin
text = File.open(filename, &:readline)
rescue EOFError
end
text
end
first_line = File.readlines('file_path').first.chomp
Does anyone know how to make assert_select not output all those nasty html warnings during a rake test? You know, like this stuff:
.ignoring attempt to close body with div
opened at byte 1036, line 5
closed at byte 5342, line 42
attributes at open: {"class"=>"inner02"}
text around open: "</script>\r\t</head>\r\t<body class=\"inner02"
text around close: "\t</div>\r\t\t\t</div>\r\t\t</div>\r\t</body>\r</ht"
Thanks
It's rather that your code is generating invalid HTML. I suggest running it through a validator and fixing all the validation errors.
You can find out which test ran into the problem by using the TESTOPTS v flag:
(bundle exec) rake test TESTOPTS="-v"
This will give:
test: Request the homepage should have a node list. (PresentControllerTest): .
test: Request the homepage should have the correct title. (PresentControllerTest): ignoring attempt to close div with body
opened at byte 4378, line 89
closed at byte 17745, line 393
attributes at open: {"class"=>"colleft"}
text around open: "class=\"colmid\"> \n\t\t\t<div class=\"colleft\""
text around close: "x2.js\" ></script>\n </body>\n</html>\n\n"
ignoring attempt to close div with html
opened at byte 4378, line 89
closed at byte 17753, line 394
attributes at open: {"class"=>"colleft"}
text around open: "class=\"colmid\"> \n\t\t\t<div class=\"colleft\""
text around close: "</script>\n </body>\n</html>\n\n"
.
test: Request the homepage should not set the flash. (PresentControllerTest): .
test: Request the homepage should respond with 200. (PresentControllerTest): .
Rails's HTML scanner expects XHTML, if you're using HTML4 where tags don't have explicit closing tags, you may get this warning... doesn't look like solved issue
http://dev.rubyonrails.org/ticket/1937
http://gilesbowkett.blogspot.com/2009/10/ignoring-attempt-to-close-foo-with-bar.html
What I'd want is to know where the warning is coming from. The fact it doesn't specify the test or the controller/action which generates the invalid HTML is the big problem for me.
I had some problems after an update to rails 3.0.9 and HAML 3.1.2
What I did was silence those ugly outputs with the following code in *test_helper.rb*
# Wrap up the method assert_select because after updating to Rails 3.0.9 and HAML 3.1.2,
# I don't know why but it was raising warnings like this:
# ignoring attempt to close section with body
# opened at byte 6157, line 128
# closed at byte 16614, line 391
# attributes at open: {"class"=>"left-column"}
# text around open: "->\n\n\n</span>\n</div>\n<section class='left"
# text around close: "'1'>\n</noscript>\n</body>\n</html>\n"
# But the HTML seems to be valid (in this aspects) using a HTML validator.
ActionDispatch::Assertions::SelectorAssertions.class_eval do
alias_method :assert_select_original, :assert_select
def assert_select(*args, &block)
original_verbosity = $-v # store original output value
$-v = nil # set to nil
assert_select_original(*args, &block)
$-v = original_verbosity # and restore after execute assert_select
end
end
Anyway, I don't recommend using a solution like this. Use only if you are in hurry, and give it a good comment to explain other developers why is that estrange piece of code there.
For me, the cause was valid but poorly formed HAML.
This is what I had:
%ul
%li
= link_to "Help", help_url
- if current_user
%li
= link_to "Users", users_url
= link_to "Logout", logout_url
- else
= link_to "Login", login_url
This is what is correct for what I'd wanted to do:
%ul
%li
= link_to "Help", help_url
%li
- if current_user
= link_to "Users", users_url
= link_to "Logout", logout_url
- else
= link_to "Login", login_url
The best way to track this down is to look very carefully at the "text around open" and "text around close" and try to track down where in your template the open occurs.
Even if you do rake test TESTOPTS="-v" and the error appears to be coming from your view templates, DON'T forget to check the application layout html. This happened to me and it took a few minutes longer than I'd like to admit going back and forth between a couple index.html.erb files before I finally figured it out. Same goes for any rendered partials.
I am trying to check if a file exists in my rails application.
I am running ruby 1.8.6 and rails 2.1.2 with windows XP.
So, the problem is that the FileTest.exists? method doesn't seem to be working. I have simplified the code to this point :
if FileTest.exists?("/images/header.jpg")
render :text => "yes"
else
render :text => "no <img src='/images/header.jpg' />"
end
If I do that the system displays "no" and then includes the image that displays correctly because /images/header.jpg exists.
I tried FileTest.exists?, FileTest.exist?, File.exists?, File.exist? and nothing seems to be working.
What am I doing wrong ?
Thanks
I'm guessing it's because you're asking whether a file "header.jpg" exists in a directory "images" off of the root directory for your system (which on Windows I'd assume is "c:\"). Try putting the full path (from the filesystem root) to the "/images" directory rather than the URL path.
In particular, as pointed out by #Brian, you should use:
FileTest.exists?(RAILS_ROOT + "/images/header.jpg") # < rails 3.0
FileTest.exists?(Rails.root + "/images/header.jpg") # >= rails 3.0
Add RAILS_ROOT to the filename that you're checking before calling exists?