Home » Php » How to convert documents to PDF on a Linux/PHP stack?

How to convert documents to PDF on a Linux/PHP stack?

Posted by: admin July 12, 2020 Leave a comment


I want to display documents on my website. The server is hosted on a Debian machine. I was thinking I can allow the upload of support documents then use a Linux app or PHP app to convert the doc into PDF and display that in an HTML page. Are there any APIs or binaries that allow me to do this?

How to&Answers:

If it is an office document, one option would be to use openoffice in headless mode. See here for a python script that shows how: http://www.oooninja.com/2008/02/batch-command-line-file-conversion-with.html

If it is any other kind of document (e.g. your own XML document), then you would need to do a bit more work. I have had some success using XSL to define a translation to docbook format, then using docbook tools to generate the PDF (and various other formats). You could also use XSL to go straight to PDF if you need more precise control over how things look.


You can create a PDF print-to-file printer and send any number of documents to the printer via lpr.

  function lpr($STR,$PRN,$TITLE) {

    $prn=(isset($PRN) && strlen($PRN))?"$PRN":C_DEFAULTPRN ;
    $title=(isset($TITLE))?"$TITLE":"stdin" . rand() ;
    $CMDLINE="lpr -P $prn -T $title";
    $pipe=popen("$CMDLINE" , 'w');
    if (!$pipe) {print "pipe failed."; return ""; }

  } // lpr()

//open document...
//read into $source
lpr($source, "PDF", $title); //print to device

Also HTMLDOC can convert your HTML into a PDF.


A relatively new project, called phpLiveDocx can convert DOC to PDF (in addition to a number of other formats). It is a SOAP based service and can be used completely free of charge. For sample code to convert a DOC to PDF using phpLiveDocx, take a look at this recent blog post:


Of course, as it is SOAP based, it can be used on all operating systems that support PHP 🙂


An alternative method is to generate an HTML file that contains what you need in the pdf. Then use htmldoc to convert it to a PDF.


It actually is much easier than directly manipulating the objects in a PDF doc.


Pear has a PHP PDF class. See: