Covertapi.com pdf到php中的jpeg

时间:2012-11-09 08:27:28

标签: php convertapi

我正在尝试使用convertapi.com转换Rest Api with php将PDF文件转换为JPEG但它一直给出一个异常,说返回的内容不是jpeg。您可以在http://www.luova.fi/word2pdf/pdf2jpg.php查看我的代码 我已经在论坛上查了一下,但找不到任何问题的答案,任何人的想法。谢谢! (imagemagick和gs是不可能的)

大卫

<?php
 error_reporting(NULL);
 ini_set('display_errors', '0');
function ParseHeader($header='')
{
$resArr = array();
$headerArr = explode("\n",$header);
foreach ($headerArr as $key => $value) {
    $tmpArr=explode(": ",$value);
    if (count($tmpArr)<1) continue;
    $resArr = array_merge($resArr, array($tmpArr[0] => count($tmpArr) < 2 ? "" : $tmpArr[1]));
}
return $resArr;
}

function CallToApi($fileToConvert, $pathToSaveOutputFile, $apiKey, &$message)
{
    try
    {

        $rand=time();
        $fileName = $rand."MyFile.jpg";
        $apiKey = "XXXXXXX";
        $postdata =  array('OutputFileName' => 'MyFile.jpg', 'ApiKey' => $apiKey, 'file'=>"@".$fileToConvert);
        $ch = curl_init("http://do.convertapi.com/Pdf2Image");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        $result = curl_exec($ch); 
        $headers = curl_getinfo($ch);

        $header=ParseHeader(substr($result,0,$headers["header_size"]));
        $body=substr($result, $headers["header_size"]);

        curl_close($ch);
        if ( 0 < $headers['http_code'] && $headers['http_code'] < 400 ) 
        {
            // Check for Result = true

            if (in_array('Result',array_keys($header)) ?  !$header['Result']=="True" : true)
            {
                $message = "Something went wrong with request, did not reach ConvertApi service.<br />";
                return false;
            }
            // Check content type 
            if ($headers['content_type']<>"image/jpeg")
            {
                $message = "Exception Message : returned content is not jpeg file.<br />";
                return false;
            }
            $fp = fopen($pathToSaveOutputFile.$fileName, "wbx");

            fwrite($fp, $body);

            $message = "The conversion was successful! The pdf file $fileToConvert converted to JPEG and saved at $pathToSaveOutputFile$fileName";
            return true;
        }
        else 
        {
         $message = "Exception Message : ".$result .".<br />Status Code :".$headers['http_code'].".<br />";
         return false; 
        }
    }
    catch (Exception $e) 
    {   
        $message = "Exception Message :".$e.Message."</br>";
        return false; 
    }
}
    ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>
        Conversion PDF to JPEG
    </title>
</head>
<body>
<div style="width: 600px; margin: auto;">
    <h3>Conversion example of PDF to JPEG using Rest API <a href="http://www.convertapi.com" target="_blanks">http://www.convertapi.com</a></h3>
    <form method="post" action="" id="word2pdf_form" enctype="multipart/form-data">
        Please choose PDF document(pdf file) from your computer
        <br />
        <input type="file" name="FileUpload" id="FileUpload" style="width:600px;">
        <br />
        <input name="txtApiKey" type="hidden" id="txtApiKey" value="" style="width:600px;">
        <br />
        <br />
        <div style="text-align: center">
            <input type="submit" name="btnConvert" value="Convert" id="btnConvert">
        </div>

        </form>
        <br>
 <?php

if (isset($_FILES["FileUpload"]['name'])&&$_FILES['FileUpload']['size']>0&&$_FILES['FileUpload']['error']==0)
{
$physicalPath = dirname(__FILE__)."/files/";

if (!file_exists($physicalPath)) {
        mkdir($physicalPath,0777);
    }
$uploadedFile = $physicalPath.$_FILES["FileUpload"]['name'];

$apiKey = $_REQUEST["txtApiKey"];

if (!move_uploaded_file($_FILES["FileUpload"]["tmp_name"], $uploadedFile)) die("CANNOT MOVE {$_FILES['FileUpload']['name']}" . PHP_EOL);
$message = "";
chmod($uploadedFile,0755);
$result = CallToApi($uploadedFile, $physicalPath, $apiKey, &$message);
echo "<span id='lblStatus'".($result ? "" : "style='color:red'")." >" .$message."</span>";
  }
  else
  {
echo in_array("btnConvert", $_REQUEST) ? "<span id='lblStatus' style='color:Red;'>  Please select PDF document!</span>":"<span id='lblStatus'>Please select a PDF document and click Convert button.</span>";
}
     ?>
    </div>

    </body>
    </html>

2 个答案:

答案 0 :(得分:4)

试试此代码

<?php
error_reporting(NULL);
ini_set('display_errors', '1');

function ParseHeader($header = '') {
    $resArr = array();
    $headerArr = explode("\n", $header);
    foreach ($headerArr as $key => $value) {
        $tmpArr = explode(": ", $value);
        if (count($tmpArr) < 1)
            continue;
        $resArr = array_merge($resArr, array($tmpArr[0] => count($tmpArr) < 2 ? "" : $tmpArr[1]));
    }
    return $resArr;
}

function CallToApi($fileToConvert, $pathToSaveOutputFile, $apiKey, &$message) {
    try {
        $rand = time();
        $ext = ".jpg";
        $fileName = $rand . "MyFile";
        $apiKey = "";
        $postdata = array('OutputFileName' => 'MyFile.jpg', 'ApiKey' => $apiKey, 'file' => "@" . $fileToConvert);
        $ch = curl_init("http://do.convertapi.com/Pdf2Image");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        $result = curl_exec($ch);
        $headers = curl_getinfo($ch);

        $header = ParseHeader(substr($result, 0, $headers["header_size"]));
        $body = substr($result, $headers["header_size"]);

        curl_close($ch);
        if (0 < $headers['http_code'] && $headers['http_code'] < 400) {
            // Check for Result = true

            if (in_array('Result', array_keys($header)) ? !$header['Result'] == "True" : true) {
                $message = "Something went wrong with request, did not reach ConvertApi service.<br />";
                return false;
            }
            // Check content type 
            switch ($headers['content_type']) {
                case "image/jpeg":
                    $ext = ".jpg";
                    break;
                case "application/x-zip-compressed":
                    $ext = ".zip";
                    break;
                default :
                    $message = "Exception Message : returned content is not correct.<br />";
                    return false;
            }

            $fp = fopen($pathToSaveOutputFile . $fileName . $ext, "wbx");

            fwrite($fp, $body);

            $message = "The conversion was successful! The pdf file $fileToConvert converted to JPEG and saved at $pathToSaveOutputFile$fileName$ext";
            return true;
        } else {
            $message = "Exception Message : " . $result . ".<br />Status Code :" . $headers['http_code'] . ".<br />";
            echo $message;
            return false;
        }
    } catch (Exception $e) {
        $message = "Exception Message :" . $e . Message . "</br>";
        return false;
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>
            Conversion PDF to JPEG
        </title>
    </head>
    <body>
        <div style="width: 600px; margin: auto;">
            <h3>Conversion example of PDF to JPEG using Rest API <a href="http://www.convertapi.com" target="_blanks">http://www.convertapi.com</a></h3>
            <form method="post" action="" id="word2pdf_form" enctype="multipart/form-data">
                Please choose PDF document(pdf file) from your computer
                <br />
                <input type="file" name="FileUpload" id="FileUpload" style="width:600px;">
                    <br />
                    <input name="txtApiKey" type="hidden" id="txtApiKey" value="" style="width:600px;"/>
                    <br />
                    <div style="text-align: center">
                        <input type="submit" name="btnConvert" value="Convert" id="btnConvert" />
                     </div>
             </form>
              <br />
                <?php
                if (isset($_FILES["FileUpload"]['name']) && $_FILES['FileUpload']['size'] > 0 && $_FILES['FileUpload']['error'] == 0) {
                    $physicalPath = dirname(__FILE__) . "/files/";

                    if (!file_exists($physicalPath)) {
                        mkdir($physicalPath, 0777);
                    }
                    $uploadedFile = $physicalPath . $_FILES["FileUpload"]['name'];

                    $apiKey = $_REQUEST["txtApiKey"];

                    if (!move_uploaded_file($_FILES["FileUpload"]["tmp_name"], $uploadedFile))
                        die("CANNOT MOVE {$_FILES['FileUpload']['name']}" . PHP_EOL);
                    $message = "";
                    chmod($uploadedFile, 0755);
                    $result = CallToApi($uploadedFile, $physicalPath, $apiKey, &$message);
                    echo "<span id='lblStatus'" . ($result ? "" : "style='color:red'") . " >" . $message . "</span>";
                }
                else {
                    echo in_array("btnConvert", $_REQUEST) ? "<span id='lblStatus' style='color:Red;'>  Please select PDF document!</span>" : "<span id='lblStatus'>Please select a PDF document and click Convert button.</span>";
                }
                ?>
        </div>
    </body>
</html>

答案 1 :(得分:0)

好的,我发现它的ZIP文件实际上已被发回,这就是我收到错误的原因。