【问题标题】:PHPExcel showing garbage in main pagePHPExcel在主页显示垃圾
【发布时间】:2012-07-23 19:08:14
【问题描述】:

我需要使用从数据库中获得的一些信息生成一个 PDF 文件,我正在使用 PHPExcel 来执行此操作,但事情是这样的,当我单击“报告”按钮时,我会获取所有信息并将其放入进入 PDF,我的页面中有很多“垃圾”,这些垃圾就像您尝试用记事本打开 PDF 时一样,它只显示随机符号。

这是我的做法

我正在使用$.ajax 调用将所有信息显示在一个表单中:

$.ajax({
    // gets all the information and puts them into the form and several tables
});

然后我将一个事件处理程序添加到按钮report,以便我将请求 ID 发送到一个 php 脚本,该脚本将收集必要的信息来填写报告

report.on('click',function(){       
    $.ajax({
        url  : '../../php/reports/requestReport.php',
        type : 'post',
        data : {'idRequest' : id },
        dataType : 'json',
        success : function(response){
            console.log(response);
        },
        error : function(response){
            if(response.responseText != undefined)
                $('body').append(response.responseText);            
            console.warn(response);
        }
    }); 
});

在我的 php 文件中,我有这样的内容:

<?php
    require '../functions.php';
    require '../classes/PHPExcel.php';

    if(isset($_POST['idRequest']))
        $idRequest = $_POST['idRequest'];
    else{
        $idRequest = false;
        echo json_encode(array("ExitCode"=>1,"Message"=>"idRequest Not Received","Location"=>"requestReport.php"));
    }


if($idRequest){
try{
    // get all the data
    // save the request and send it to the report
    $excel = new PHPExcel();
    //Initializing
    $excel->getProperties()->setCreator("TTMS")
                         ->setLastModifiedBy("TTMS")
                         ->setTitle("Request update $idRequest");

    $excel->setActiveSheetIndex(0)
                ->setCellValue('C1', 'Request For Q.A. / Q.C. / Testing');

    // Rename worksheet
    $excel->getActiveSheet()->setTitle("$idRequest");


    // Set active sheet index to the first sheet, so Excel opens this as the first sheet
    $excel->setActiveSheetIndex(0);


    // Redirect output to a client’s web browser (PDF)
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment;filename="Update_Request_'.$idRequest.'.pdf"');
    header('Cache-Control: max-age=0');

    $objWriter = PHPExcel_IOFactory::createWriter($excel, 'PDF');
    $objWriter->save('php://output');
} catch(PDOException $ex){
    echo json_encode(array("ExitCode"=>2,"Message"=>$ex->getMessage(),"Location"=>"requestReport.php PDOException"));
}

长话短说,我在表单所在的页面上得到了垃圾。我认为这与我通过ajax 执行此操作的事实有关,但我需要这样做,所以echo 我必须在我的代码中报告错误。

【问题讨论】:

  • 我很困惑。您正在生成 Excel 电子表格,但将其命名为 PDF? PDF 不是,从来都不是,也永远不会是 Excel 电子表格,所以难怪你会扔垃圾。这就像将 .jpg 图像重命名为“cutekittens.txt”并期望记事本能够显示图像。
  • PHPExcel 允许我创建一个 excel 文件,但最后只需将其保存为 PDF,其中大部分内容我只是从 PHPExcel 文档中的教程中复制的

标签: php jquery ajax pdf phpexcel


【解决方案1】:

您正在现有的 HTML 页面中编写 PDF 输出

$('body').append(response.responseText);             

浏览器假定 HTML 页面中显示的所有内容都是 HTML 标记,而不是二进制数据流。

如果成功,将输出定向到新的浏览器窗口。

【讨论】:

  • 如何从 javascript 打开另一个窗口?
【解决方案2】:

将所有输出写入 HTML 文件,然后使用 wkhtmltopdf -> http://code.google.com/p/wkhtmltopdf/ 将其转换为 PDF。效果很棒!

这是您将用来创建 html 文件的代码:

if (!$handle = fopen('/path/to/folder/your_file.html', 'w')) {
     die("Cannot open file for write");
}

$data_string = "<html><body></body></html>"; //all your html output goes here, formatted correctly, etc

// Write somecontent to our opened file.
if (fwrite($handle, $data_string) === FALSE) {
    die("Cannot write to file");
}

然后,一旦成功,您将其转换为 PDF,然后删除旧的 html 文件

   // convert to PDF
    $output = shell_exec('wkhtmltopdf --page-size Letter /path/to/folder/your_file.html /path/to/folder/your_file.pdf');
    if (strpos($output,'Error') == false){
        $output = shell_exec('rm /path/to/folder/your_file.html');
    }else{
        die("error creating pdf, please contact IT administrator.");
    }

现在您的 PDF 位于该位置 -> /path/to/folder/your_file.pdf,您可以让用户下载它。

【讨论】:

  • 我看到这使用了 webkit 引擎,我必须确保它 100% 与 firefox 一起工作,这不会造成问题吗?
  • 除了我认为强迫我的用户使用命令行是不可行的
  • 这都是服务器端的。您在 Web 服务器(而不是客户端计算机)上输出到 html 文件,然后使用 PHP 将 HTML 文件转换为 PDF。然后让客户端下载PDF。我将使用示例脚本更新我的答案。
  • 哦,好的,但这里仍然是 Windows 环境 - 编辑没关系,我看到他们有 Windows 安装程序,打算检查一下
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-10
  • 2016-07-08
  • 1970-01-01
  • 2014-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多