Archive · 2008
PDF 2 iPod Touch
A PDF splitter and packager in Ruby, to carry coding articles around on a first-generation iPod Touch, offline.
The idea
Christmas brought an iPod Touch, my first ever iPod. I really liked reading PDFs on it, so I could bring my coding articles around. The catch: it only opened a PDF while online, or while the document was still in the cache.
Googling around I found a great trick on insanely great news (opens in a new tab) (link to the Internet Archive copy). It works on a clean iPod, with no jailbreak:
- Encode the PDF in base64.
- Embed it in an HTML file as a
data:link. - Open the HTML file in Safari on the Mac and click the link.
- Bookmark the opened document (that is, the embedded data).
- Sync bookmarks to the iPod with iTunes, then read it from Safari's bookmarks, offline.
It works with any file Safari can read, not just PDFs. I translated the encoder to Ruby, to start playing with the language, and added a second script that splits a PDF into smaller documents so they don't fill the iPod's memory.
The scripts
pdfSplitter.rb
Splits a PDF into documents of at most N pages each (default 50). It needs RubyCocoa (opens in a new tab) for PDFKit, and uses the bundled readme.pdf as a template, so keep it in the script folder.
mkdir mypdfs
ruby pdfSplitter.rb mydoc.pdf mypdfs 20
# a 30-page mydoc.pdf becomes mypdfs/mydoc_1.pdf (20 pages) and mydoc_2.pdf (10 pages)
dataUri.rb
Creates one HTML file per document, each with the document embedded as a link.
ruby dataUri.rb mydoc mypdfs
# → mypdfs/mydoc_1.pdf.html and mypdfs/mydoc_2.pdf.html
# open each one, click the link, check the PDF loads in Safari, then bookmark it
Both scripts were only lightly tested, and only on Leopard. Do what you want with them, at your own risk.
- PDF 2 iPod Touch
Download
data = File.open( path + "/" + source, 'rb').read
out = Base64.encode64(data)
outFile = File.new( path + "/" + File.basename(source) + ".html", "w" )
# ...
outFile.puts "<html><head></head><body>"
outFile.puts "<a href=\"data:" + content_type + ";charset=utf-8;base64," + out +
"\">Embedded : " + File.basename(source) + "</a>"
outFile.puts "</body></html>"
From the archive
This project dates from the mid-2000s. Downloads are kept as they were, for history and for anyone still running those versions. They may not work with current software.
Credits: original idea from insanely great news. Thanks for sharing! The splitter uses RubyCocoa.