Ruby,CSV和pdf的

时间:2016-06-30 06:55:10

标签: ruby csv pdf

所以我将网址转换为图片并将其下载到文档中。该文件可以是.jpg或.pdf。我可以成功下载pdf并且pdf上有一些内容(以内存的形式),但是当我尝试打开pdf时,adobe reader无法识别它并认为它已损坏。

以下是指向其中一个网址的链接 - http://www.finfo.se/www.artdb.finfo.se/cgi-bin/lankkod.dll/lev?knr=7770566&art=001317514&typ=PI

这是代码=>

require 'open-uri'
require 'tempfile'
require 'uri'
require 'csv'

DOWNLOAD_DIR = "#{Dir.pwd}/PI/"
CSV_FILE = "#{Dir.pwd}/konvertera4.csv"

def downloadFile(id, url, format)

  begin
    open("#{DOWNLOAD_DIR}#{id}.#{format}", "w") do |file|
      file << open(url).read
      puts "Successfully downloaded #{url} to #{DOWNLOAD_DIR}#{id}.#{format}"
    end
  rescue Exception => e
    puts "#{e} #{url}"
  end
end


CSV.foreach(CSV_FILE, headers: true, col_sep: ";") do |row|
  puts row
  next unless row[0] && row[1]
  id = row[0]
  format = row[1].match(/PI\.(.+)$/)&.captures.first
  puts format
  #format = "pdf"
  #format = row[1].match(/BD\.(.+)$/)&.captures.first
  url = row[1].gsub ".pdf", ""
  downloadFile(id, url, format)
end

1 个答案:

答案 0 :(得分:0)

尝试使用wb而不是w:

open("#{DOWNLOAD_DIR}#{id}.#{format}", "wb")