This is a website by Willem van Zyl

I'm a project manager, software developer, Apple evangelist and geek from South Africa. I'm passionate about web and mobile application development, usability, productivity, physics, astronomy, science fiction and fantasy.

If you would like to contact me, message me on Twitter or send me an email.

How to bulk convert HTML, RTF, etc. documents to PDF on the command line

07 Feb 2009

OS X has PDF printing support built into all applications, and this PDF support can be used from the command line or in an AppleScript script / application to convert virtually any kind of document to the PDF format.

In the example below there are five HTML files (file1.html, file2.html, ..., file5.html) that have to be converted to a single PDF (all.pdf). To accomplish this on the command line, open up a new Terminal window, go to the folder the HTML files are stored in, and optionally execute this command to merge them into one file:

cat * > all.html

Next, call Apple's 'convert' utility (this is not the 'convert' utility related to ImageMagick) and specify the input and output filenames:

/System/Library/Printers/Libraries/convert -f all.html
  -o all.pdf

The 'convert' utility will build the output file and write it to the folder your Terminal shell is currently focused on. The command to convert to / from other filetypes is similar, except that you can't 'cat' the input files if they’re not text-based.

This functionality can be automated by writing an AppleScript application that makes use of the command line tool. Enter the following code into Script Editor (found in the Utilities folder in your Applications folder):

on open input_documents
  repeat with this_document in input_documents.
    set this_document_path to POSIX path of this_document
    --display dialog this_document_path
    do shell script "/System/Library/Printers/Libraries/convert -f " & quoted form of this_document_path & " -o " & quoted form of this_document_path & ".pdf"
  end repeat
end open

Click 'File->Save' to save the script's source code, then 'File->Save As...' and change the File Format to Application to save an executeable (application) version of the script. If you drop documents on this application, it will automatically launch and create PDF copies of the documents in their source folder.

Do you like this? Share it:

Copyright © Geekology 2011. All Rights Reserved.

Hosted by Code. Like. Clockwork.