Wednesday, December 28, 2011

Kindle conversion

I got a Kindle for Christmas! (thanks Granny). However like many people I ran into the problem with converting .epub to .mobi where the converted files have huge margins on the left hand side of the screen. After some research I found a series of forum post suggesting various solutions but all of them were very manual processes and I wanted something that would just do it for me.

So what I've got here is a simple shell script that does it all for you. You will need to install calibre since it uses the command line tools from that to do the actual conversion but it will automatically convert and sort the formatting out for you.

I'll probably end up redoing it all in python so that it will work on windows.

mkdir _temp
mkdir converted

for file in "$@"
do
echo "Converting \"$file\""

cp -f "$file" _temp/.

filename=$( echo "$file" | sed 's/^.*\///' )
file_type=$( echo "$filename" | sed 's/^.*\.//' )
new_file=$( echo "$filename" | sed 's/[^.]*$/mobi/' )

# if .epub
if [[ $file_type == "epub" ]]
then
# if the metadata is lacking language information then set it to en
lang_meta=$( ebook-meta "_temp/$filename" | egrep "^Language" )
if [[ !( -n "$lang_meta" ) ]]
then
echo "Changing metadata language"
ebook-meta -l en "_temp/$file" >/dev/null 2>&1
fi

# edit the stylesheet to get rid of the massive gap on the left
unzip -f "_temp/$filename" stylesheet.css >/dev/null 2>&1
sed -i 's/margin-left:.*;/margin-left: 0;/g' stylesheet.css
zip "_temp/$filename" stylesheet.css >/dev/null 2>&1
fi

ebook-convert "_temp/$filename" "_temp/$new_file" > /dev/null
#wine kindlegen "_temp/$filename"

mv -f "_temp/$new_file" converted/.
done

rm -r _temp