开发者

Help with Ruby & PrinceXML

开发者 https://www.devze.com 2023-03-10 13:47 出处:网络
I\'m trying to write a very simple markdown-like converter in ruby, then pass the output to PrinceXML (which is 开发者_JS百科awesome). Prince basically converts html to pdf.

I'm trying to write a very simple markdown-like converter in ruby, then pass the output to PrinceXML (which is 开发者_JS百科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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消