我正在尝试在ruby中编写一个非常简单的降价转换器,然后将输出传递给PrinceXML(这很棒)。 Prince基本上将html转换为pdf。
这是我的代码:
#!/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]}'
但是这会将空文件转储到/tmp/sample.html
。当我排除调用王子时,转换就好了。
我做错了什么?
答案 0 :(得分:1)
由于您创建输出文件的方式,文件输出可能是缓冲的,而不是写入磁盘。试试这个:
# 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]}'
这是惯用的Ruby;我们将一个块传递给File.new
,当块退出时它将自动关闭。作为关闭文件的副产品,任何缓冲的输出都将刷新到磁盘,system
调用中的代码可以找到它。
答案 1 :(得分:0)
来自fine manual:
prince doc.html -o out.pdf
将doc.html转换为out.pdf。
我认为您的system
电话应该是这样的:
system "prince /tmp/sample.html -o #{ARGV[1]}"
另请注意切换为双引号,以便#{}
插值可以正常工作。如果没有双引号,shell将看到以下命令:
prince /tmp/sample.html #{ARGV[1]}
然后它会忽略#
之后的所有内容作为评论。我不确定为什么你最终得到一个空的/tmp/sample.html
,根据我对文档的阅读,我期待/tmp/sample.pdf
中的PDF。