baron_bartek
baron_bartek

Reputation: 1127

Saving pdf to BLOB (in mssql server) and output it back on website (php)

I need to save a pdf file into BLOB (database is MsSql 2012, but I would need it work on 2008 too).

Here is compilation of what I have tried so far:

(File where I save pdf into database)

function preparePDF2String($filepath)
{
    $handle = @fopen($filepath, 'rb');
    if ($handle)
    {
        $content = @fread($handle, filesize($filepath));
        $content = bin2hex($content);
        @fclose($handle);
        return "0x".$content;
    }
}

$out = preparePDF2String('pdf/pdf.pdf');
$q_blob = "INSERT INTO HISTORIA_ARCHIWUM_test(PDFName, PDFData) VALUES('First test pdf', $out) ";

$r_blob = mssql_query($q_blob,$polacz);

Results (ok, I think)

enter image description here

(Now the php file where I try to output the pdf)

// header('Content-type: application/pdf');
// readfile('pdf/pdf.pdf'); - this works just fine, so pdf is ok


$q_blob = "select top 1 * from HISTORIA_ARCHIWUM_test";
$r_blob = mssql_query($q_blob,$polacz);
$w_blob = mssql_fetch_array($r_blob);

header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="the.pdf"');

echo $w_blob['PDFData'];
//echo hex2bin ($w_blob['PDFData']); - I also tried this - same problem

Problem: when I try to output the pdf in the browser I get error (this pdf is of not supported format). It won't open in Adobe reader also. My guess is that I output it wrong, but maybe it is the way I save it?

Upvotes: 0

Views: 5458

Answers (1)

Musa
Musa

Reputation: 97672

EDIT from comments
It seems php+mssql truncates string when you get it from db, but its manageable in php.ini. I set mssql.textlimit = 160000 and mssql.textsize = 160000 and it works fine with Hex conversion and varchar(max).


You are transforming the pdf data before you save it to the database, you have to undo the transformation before you output it.

header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="the.pdf"');

echo hex2bin(substr($w_blob['PDFData'], 2));

Also why are you transforming the data in the first place, just save it as binary.

Upvotes: 2

Related Questions