1

I'm trying to write a very simple markdown-like converter in ruby, then pass the output to PrinceXML (which is awesome). Prince basically converts html to pdf.

Here's my code:

#!/usr/bin/ruby
# USAGE: command source-file.txt target-file.pdf

# read argument 1 as input
text = File.read(ARGV[0])

# wrap paragraphs in paragraph tags
text = text.gsub(/^(.+)/, '<p>\1</p>')

# create a new temp file for processing
htmlFile = File.new('/tmp/sample.html', "w+")

# place the transformed text in the new file
htmlFile.puts text

# run prince
system 'prince /tmp/sample.html #{ARGV[1]}'

But this dumps an empty file to /tmp/sample.html. When I exclude calling prince, the conversion happens just fine.

What am I doing wrong?

2 Answers2

1

It's possible that the file output is being buffered, and not written to disk, because of how you are creating the output file. Try this instead:

# create a new temp file for processing
File.open('/tmp/sample.html', "w+") do |htmlFile|

  # place the transformed text in the new file
  htmlFile.puts text

end

# run prince
system 'prince /tmp/sample.html #{ARGV[1]}'

This is idiomatic Ruby; We pass a block to File.new and it will automatically be closed when the block exits. As a by-product of closing the file, any buffered output will be flushed to disk, where your code in your system call can find it.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
0

From the fine manual:

prince doc.html -o out.pdf
Convert doc.html to out.pdf.

I think your system call should look like this:

system "prince /tmp/sample.html -o #{ARGV[1]}"

Also note the switch to double quotes so that #{} interpolation will work. Without the double quotes, the shell will see this command:

prince /tmp/sample.html #{ARGV[1]}

and then it will ignore everything after # as a comment. I'm not sure why you end up with an empty /tmp/sample.html, I'd expect a PDF in /tmp/sample.pdf based on my reading of the documentation.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • Hmmm... I've been using Prince for years and I've never once used the `-o` flag. It seems to have no effect. And, yes, the big problem is that with the `system` call the script creates an empty file, but without it the script processes the file as expected. –  Jun 04 '11 at 05:39
  • @Oliver: Does using double quotes on your `system` call make a difference? And what if you flush or close `htmlFile` before `system` as Tin Man suggests? – mu is too short Jun 04 '11 at 05:44
  • I changed it to doubles, and no, it didn't make a difference. And, yes, what @theTinMan suggested worked perfectly. –  Jun 04 '11 at 05:48
  • @Oliver: But does it pay attention to `ARGV[1]` without the double quotes or does it just produce `/tmp/sample.pdf`? – mu is too short Jun 04 '11 at 06:27