Search code examples
phppdffpdf

How can I sanitize PHP data for writing to PDF file?


I'm having a lot of issues writing database results to a PDF using FPDF, it seems there is either unsupported data or characters or ~something~ in the data being returned from the database.

  • the PDF file gets written and downloaded with no errors, but occasuionally I get a page that looks like:

enter image description here

The asterisks are missing pages. now, I'm trying to sanitize the data by running each item through a function:

public function cleanPDFData($data){

        $data = utf8_decode($data);
        $data = trim($data);
        $data = preg_replace( "/\r|\n/", "", $data);

        return $data;

    }

But I am still getting broken pages.

  • If I replace the query results with a string, the PDF is generated perfectly [i.e. return "test"; ] the error is in the data itself

  • if I view the record in the database, nothing appears out of sorts, correct data types, no funny characters, no missing data. I don't know what else to look for.

  • if I start deleting records before the blank pages, the PDF will again generate itself perfectly.

  • no errors are thrown

I am out of ideas, my best guess is that my php script is trying to pass some sort of unsupported character or data to the FPDF - but I have no idea what it might be!

here is the actual PDF : sample-pdf.pdf

UPDATE

ok - I think I found part of the problem, here is the updated cleaning function:

public function cleanPDFData($data){

        if(strlen($data) <= 0){$data = '-';}

        $data = trim($data);
        $data = str_replace('/', '-', $data);
        $data = iconv('UTF-8', 'ISO-8859-1', $data);
        $data = preg_replace( "/\r|\n/", "", $data);

        return $data;

    }

So once the "/" characters are removed, the PDF will generate properly, but now I am left without the [sometimes] needed slashes (/). How can I generate the PDF ensuring that all the special characters are correctly displayed?


Solution

  • the problem turned out to be compression.

    You can disable compression via:

    $pdf->setCompression(false);
    

    Thanks to Olivier on the FPDF forums.