RubyPDF Blog PDF,tutorial How to Let Python Send Binary data to stdout under Windows

How to Let Python Send Binary data to stdout under Windows

recently I successfully compile jbig2enc under windows, but when I tested pdf.py, I got incorrect PDF document, after asked to the author,

because of the bug of python under windows, file(p).read() can not read all content of output.0000, so the pdf created is not correct, I modify file(p,’rb’).read(), but the pdf created is still not correct, is some bigger than it create under linux, I have send you the two pdf files as attachment.

I got the following answer,

My only guess would be that Windows is performing newline conversion. Keep your current change to use file(p, ‘rb’).read() and alter line 137 to read:
file(‘output.pdf’, ‘wb’).write(str(doc))
and see if output.pdf is any more valid.

in this way, I can get the correct PDF, but it is not the stdout way, and after some search, I got the following answer, and now it works as I want.

You want to send binary data, such as for an image, to stdout under Windows.

import sys

if sys.platform == "win32":
import os, msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

note:
If you are reading or writing binary data under Windows, such as for an image, then the file must specifically be opened in binary mode (Unix doesn’t make a distinction between text and binary modes). But this is a problem for a program that wants to write binary data to standard output (as a web CGI program would be expected to do), since the ‘sys’ module opens the ‘stdout’ file object on your behalf and normally does so in text mode. You could have ‘sys’ open ‘stdout’ in binary mode instead by supplying the ‘-u’ command-line option to the Python interpreter. But if you want to control this mode from within a program, then (as shown in the code sample) you can use the ‘setmode’ function provided by the Windows-specific ‘msvcrt’ module to change the mode of stdout’s underlying file descriptor.

reference,
http://code.activestate.com/recipes/65443/
issue: pdf.py can not create correct pdf under windows
Convert JBIG2 to PDF with free and open source software agl’s jbig2enc
Windows Version Jbig2enc(Jbig2 Encoder)

1 thought on “How to Let Python Send Binary data to stdout under Windows”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.