Mathematica, currently, does not have built-in technology for generating PDF, so external tools are required. The steps for generating PDF involve generating a Mathematica notebook, converting the notebook to PostScript, and converting the PostScript to PDF. These steps are discussed in the following sections.

MakeNotebook[] := UseFrontEnd[ Module[ {nb, nbobj}, nb = NotebookCreate[] ; NotebookWrite[ nb, Cell[ "A Dynamically Created Notebook", "Title"]] ; NotebookWrite[ nb, Cell[ "Converted to " <> $$button, "Subtitle"]] ; NotebookWrite[ nb, Cell[ "The date is " <> ToString[ Date[]], "Text"]] ; nbobj = NotebookGet[ nb] ; NotebookClose[ nb] ; nbobj]]

This sample shows how a notebook object is created with NotebookCreate, and then how the content is added with NotebookWrite. When the notebook is complete, a Mathematica expression holding the notebook is obtained with NotebookGet, and this is returned. In a real life situation, the document could contain graphics, more text, and some computations. The Mathematica documentation has much more information on the commands for generating notebooks.

A major advantage of working with Mathematica notebooks like this is that they will take care of details such as font selection, graphics, and mathematics without the author having to be very involved.

This code loads a couple of packages for creating notebooks and converting to PDF. It calls the function MakeNotebook, which generates a very simple notebook. It then passes the notebook object that was created into the function NotebookToPDF. If this returns a string, then this is returned to the client using MSPReturn.

Here is the Mathematica source for the function NotebookToPDF.

$PStillCommand = "/usr/local/pstill_dist/pstill"

PDFCommand[ out_, in_] := $PStillCommand <> " -o " <> out <> " " <> in

Note that this requires a definition to point to the location of the conversion tools. In this case it is set to use PStill, but it could easily be modified to use ps2pdf. Note also that the command is suitable for a Unix file system. On Windows it could be set as shown below; note the double-quotes around the command and note the doubling of the back-slashes.

The code first creates some temporary files and then sends PostScript to one of the files with the command NotebookPrint. It then uses the Run command to invoke the PDF conversion on the PostScript, and finally reads the PDF into a Mathematica string and returns this as the result.

There are all sorts of further extensions to these simple functions that interface with the PostScript to PDF conversion tools. For example, they could be extended to pass various options to the converter.