Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to save StringIO (pdf) data into file

Tags:

ruby

nokogiri

I want to save pdf file which is located in external remote server with ruby. The pdf file is coming in StringIO. I tried saving the data with File.write but it is not working. I received the below error .

ArgumentError: string contains null byte

How to save now ?

like image 617
Paritosh Piplewar Avatar asked Mar 13 '15 02:03

Paritosh Piplewar


1 Answers

require 'stringio'

sio = StringIO.new("he\x00llo")

File.open('data.txt', 'w') do |f|
  f.puts(sio.read)
end


$ cat data.txt
hello

Response to comment:

Okay, try this:

require 'stringio'

sio = StringIO.new("\c2\xb5") 
sio.set_encoding('ASCII-8BIT')  #Apparently, this is what you have.

File.open('data.txt', 'w:utf-8') do |f|
  f.puts(sio.read)
end

--output:--
1.rb:7:in `write': "\xB5" from ASCII-8BIT to UTF-8 (Encoding::UndefinedConversionError)

To get rid of that error, you can set the encoding of the StringIO to UTF-8:

require 'stringio'

sio = StringIO.new("\c2\xb5") 
sio.set_encoding('ASCII-8BIT')  #Apparently, this is what you have.

sio.set_encoding('UTF-8')  #Change the encoding to what it should be.

File.open('data.txt', 'w:UTF-8') do |f|
  f.puts(sio.read)
end

Or, you can use the File.open modes:

require 'stringio'

sio = StringIO.new("\c2\xb5") 
sio.set_encoding('ASCII-8BIT')  #Apparently, this is what you have.

File.open('data.txt', 'w:UTF-8:ASCII-8BIT') do |f|
  f.puts(sio.read)
end

But, that assumes the data is encoded in UTF-8. If you actually have binary data, i.e. data that isn't encoded because it represents a .jpg file for instance, then that won't work.

like image 165
7stud Avatar answered Oct 14 '22 08:10

7stud