2011-06-28

Convert HTML files to PDF using webkit rendering engine

An AppleScript to convert HTML files to PDFs.
It uses wkhtmltopdf for the actual conversion task.
Using the AppleScript Editor application, save the code below as an AppleScript application (AppName.app for example).
You need to download wkhtmltopdf separately and copy the executable to Contents/MacOS/ directory inside the application package.

on run
 set htmls to choose file with prompt "PDFに変換するHTMLファイルを指定してください。" of type {"public.html"} with multiple selections allowed
 my convertHtmlToPdfList(htmls)
end run

on open htmls
 my convertHtmlToPdfList(htmls)
end open

on convertHtmlToPdfList(htmls)
 tell application "Finder"
  set cmd to POSIX path of (path to me) & "Contents/MacOS/wkhtmltopdf"
  repeat with html in htmls
   if (name extension of html is "html") then
    my convertHtmlToPdf(cmd, html)
   end if
  end repeat
 end tell
end convertHtmlToPdfList

on convertHtmlToPdf(cmd, html)
 tell application "Finder"
  set htmlName to name of html
  set {dir, htmlUrl, pdfName} to {POSIX path of (container of html as alias), URL of html, text 1 thru -5 of htmlName & "pdf"}
 end tell
 do shell script "\"" & cmd & "\" \"" & htmlUrl & "\" \"" & dir & pdfName & "\""
end convertHtmlToPdf

No comments:

Post a Comment