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

元气小坏坏 提交于 2020-01-24 01:22:49

问题


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)

(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?


回答1:


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.



来源:https://stackoverflow.com/questions/33630714/saving-pdf-to-blob-in-mssql-server-and-output-it-back-on-website-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!