how to save StringIO (pdf) data into file
Asked Answered
A

1

8

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 ?

Afire answered 13/3, 2015 at 2:26 Comment(0)
V
16
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.

Valer answered 13/3, 2015 at 2:46 Comment(3)
doesn't worked. i got this Encoding::UndefinedConversionError: "\xB5" from ASCII-8BIT to UTF-8 errorAfire
@ParitoshPiplewar, 1) What line of code produced that error? 2) What encoding is your pdf file? 3)What encoding do you want to use to write to the file? It sounds like you have some binary data in your pdf file--in that case you can use File.open(..., 'wb').Valer
@ParitoshPiplewar, See the bottom of my answer for something else you can try. But you are giving incomplete information, so I am just guessing.Valer

© 2022 - 2024 — McMap. All rights reserved.