Monday, October 19, 2009

Dynamic JavaScript Text-To-Speech using Acrobat Reader

Adobe Acrobat includes a text-to-speech engine which you can access through the JavaScript functionality built into PDF. However as you can post data between the browser and embedded PDFs, it is possible to use an embedded PDF as a text-to-speech engine to read text aloud, dynamically in the browser. Try it below!


TTS Example





How does it work? A combination of  JavaScript in the browser and in an embedded PDF. To use this method of your site do the following:

First you need to embed the pdf :
<object id="PdfHost" name="PdfHost" type="application/pdf" width="0" height="0" data="http://sites.google.com/site/aplacetostorethings/tts.pdf">
</object>

The browser script below initialises the message handler and creates the bridge between the browser and acrobat:
  <script type="text/javascript">
    <!--
       
        function sayIt(msg)
        {
            var pdf = document.getElementById('PdfHost');
            if(pdf==null)
                init();
            pdf.postMessage(["speak",msg]);
        }
       
        function init(){
            var pdf = document.getElementById('PdfHost');
            if (!pdf.messageHandler)
                pdf.messageHandler = {};
            pdf.messageHandler.onMessage = onPdfMsg;
          
        }
        setTimeout("init()",1000);
    // -->
    </script>

The setTimeout is used to attempt to setup the message handler, which has to happen after the pdf has finished loading. Then you can just call it using script like:
javascript:sayIt("read this text");

If you are interested in the source of the PDF, I have posted the JavaScript it contains here: tts.js

For this page I used the origami framework to inject the script into valid PDF.