1

我正在尝试用 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. 当我排除打电话给王子时,转换发生得很好。

我究竟做错了什么?

4

2 回答 2

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调用中的代码可以在其中找到它。

于 2011-06-04T04:10:33.007 回答
0

来自精美手册

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,我希望得到一个 PDF 。/tmp/sample.pdf

于 2011-06-04T03:06:29.737 回答