php 实现批量的下载pdf (使用filedownload)


控制器部分

生成pdf 的方法 https://github.com/KnpLabs/snappy


public function actionExport()
{
    set_time_limit(120);
    $cache = Yii::$app->cache;
    $cache->keyPrefix = "report_";

    // init params
    $dir_store = Yii::getAlias('@runtime/htmlconverter');
    $params = json_decode($_GET['sid_list']);
    $count = count($params);
    $zip_name = $dir_store . '/运营商报告(' . $count . ')_' . date('YmdHis') . '.zip';
    $zip = new \ZipArchive();

    // debug log
    $file_log = $dir_store . '/log_export';
    $cid = isset($this->biz['id']) ? $this->biz['id'] : '没有登陆';
    file_put_contents($file_log, date('YmdHis') . ' CID:' . $cid . ' 开始导出' . $count . 'pdf文件' . PHP_EOL, FILE_APPEND);

    foreach ($params as $key => $val) {
        $val = is_object($val) ? get_object_vars($val) : $val;
        $sid = $val['sid'];
        $tel = $val['tel'] ?: '';

        // gen report
        if ((YII_ENV == 'prod') && $cache->exists($sid)) {
            $html = $cache->get($sid);
        } else {
            $html = $this->reportDetailV2($sid, true, $cache);
        }

        // gen pdf
        $file_name = "Report_" . $tel . "_" . $sid . ".pdf";
        Yii::$app->htmlToPdf->convert($html, ['file_name' => $file_name, 'file_exists' => true]);
        $file_path = $dir_store . '/' . $file_name;
        if (!file_exists($file_path)) {
            file_exists($zip_name) && @unlink($zip_name);
            return 'error';
        }

        // begin zip
        if ($zip->open($zip_name, \ZIPARCHIVE::CREATE) === true) {
            $zip->addFromString($file_name, file_get_contents($file_path));
        }
        @unlink($file_path);
    }
    $zip->close();

    // give zip pdf file to client
    header('Set-Cookie: fileDownload=true; path=/');
    header('Content-Description: File Transfer');
    header('Content-Type: application/octpdfet-stream');
    header('Content-Transfer-Encoding: binary');
    header('Cache-Control: must-revalidate');
    header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename=' . basename($zip_name));
    header('Content-Length: ' . filesize($zip_name));
    $pdf_info = readfile($zip_name);
    file_exists($zip_name) && @unlink($zip_name);

    file_put_contents($file_log, date('YmdHis') . ' CID:' . $cid . ' 导出完成' . PHP_EOL, FILE_APPEND);
    return $pdf_info;
}

html 部分:

<script src="/UI/js/jquery-ui.min.js"></script>
<script src="/UI/js/jquery.fileDownload.js"></script>
<link rel="stylesheet" type="text/css" href="/UI/report/css/jquery-ui.css?version=1.07"/>
<link type="text/css" rel="stylesheet" href="/UI/report/css/gritter.css?version=1.07"/>
<style>
    .ui-dialog .ui-dialog-titlebar-close {
        position: absolute;
        right: .3em;
        top: 50%;
        width: 51px;
        margin: -8px 0 0 0;
        padding: 0px;
        height: 20px;
    }
    .ui-widget-header {
        border: 1px solid #3c8dbc;
        background: #3c8dbc;
        color: #ffffff;
        font-weight: bold;
    }
    .ui-button-icon-only .ui-icon {
        display: none;
    }

</style>
<section class="content">
    <div class="box">
        <div class="box-body">
            <form class="form-inline" method="get">
                <button id="file_export" class="btn btn-success">批量导出PDF报告</button>
            </form>
        </div>
    </div>
    <div id="preparing-file-modal" title="报告合成中..." style="display: none;">
        报告合成中(50份需要1分钟左右), 请您耐心等待...
        <div class="ui-progressbar-value ui-corner-left ui-corner-right" style="width: 100%; height:22px; margin-top: 20px;"></div>
    </div>
    <div id="error-modal" title="Error" style="display: none;">
        报告合成失败,请稍后重新尝试...
    </div>
    <div class="box">
        <div class="box-body table-responsive no-padding">
            <table class="table table-hover" id="data_table">
                <thead>
                <tr>
                    <th>
                        <input type="checkbox" id="toggle_checkbox" onClick="toggle(this)"/>&nbsp;<sapn
                            id="toggle_show">本页全选
                        </sapn>
                        报告编码
                    </th>
                    <th>生成时间</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <?php if (!empty($models)): ?>
                    <?php foreach ($models as $list): ?>
                        <tr>
                            <td>
                                <?php if (isset($list['status_report']) && 0 == $list['status_report']) { ?>
                                    <input type="checkbox" name="export_pdf" class="item-checkbox" attr_tel="<?= $list['tel'] ;?>" value="<?= $list['sid']; ?>">
                                <?php } else { ?>
                                    &nbsp;&nbsp;&nbsp;
                                <?php } ?>
                                <?= $list['sid'] ?></td>
                            <td><?= (isset($list['report_create_time']) && isset($list['status_report']) && 0 == $list['status_report']) ? date('Y-m-d H:i:s', $list['report_create_time']) : '' ?></td>
                            <td align="">
                                <?php if (isset($list['status_report']) && 0 == $list['status_report']): ?>
                                    <a href="<?= \Yii::$app->urlManager->createUrl(['report/detail', 'no' => $list['sid']]); ?>"
                                       type="button" target="_blank" class="btn btn-info btn-sm">查看</a>
                                    <a href="<?= \Yii::$app->urlManager->createUrl(['report/detail', 'no' => $list['sid'], 'image_dow' => 1]); ?>"
                                       type="button" class="btn btn-primary btn-sm">下载</a>
                                <?php elseif ((2 == $list['status_report']) && $list['status'] == 0 && $need_report): ?>
                                    <a href="<?= \Yii::$app->urlManager->createUrl(['report/rebuild', 'no' => $list['sid']]); ?>"
                                       type="button" target="_self" class="btn btn-primary btn-sm">重新生成</a>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
        <div class="box-footer clearfix table_pagination">
            <div class="pull-left">
                <?= LinkPager::widget(['pagination' => $provider->pagination]) ?>
            </div>
        </div>
    </div>
</section>
<script type="text/javascript">
    $(function () {

        // checkbox click event
        $('input[type=checkbox].item-checkbox').click(function(){
            var length_total = $('input[type=checkbox].item-checkbox').length;
            var length_choosed = $('input[type=checkbox].item-checkbox:checked').length;
            var toggle_checkbox = $("#toggle_checkbox");

            if (length_total === length_choosed && !toggle_checkbox.prop('checked')) {
                toggle_checkbox.prop('checked', true);
            }

            if (length_total !== length_choosed && toggle_checkbox.prop('checked')) {
                toggle_checkbox.prop('checked', false);
            }
        });

        // export file
        $("#file_export").click(function () {
            // filter checkbox
            var check_box = $('input[type=checkbox].item-checkbox:checked');
            if (!check_box.length) {
                alert('请选择要导出的报告');
                return false;
            }

            //init params
            var sid_list_arr = [];
            check_box.map(function (key, val) {
                var sid = $(this).val();
                var tel = $(this).attr('attr_tel');
                var item = {sid: sid, tel:tel};
                sid_list_arr.push(item);
            });

            // fileDownload
            var sid_json_list = JSON.stringify(sid_list_arr, null, 2);
            var url_export_pdf = '/report/export?sid_list=' + sid_json_list;
            var preparingFileModal = $("#preparing-file-modal");

            // show waiting status with no close button
            var toggle_checkbox = $("#toggle_checkbox");
            preparingFileModal.dialog({modal: true});
            var close_button = $('[type=button].ui-button');
            close_button.css('display', 'none');

            $.fileDownload(url_export_pdf, {
                    successCallback: function (url) {
                        check_box.map(function (key, val) {
                            $(val).prop('checked', false);
                        });
                        toggle_checkbox.prop('checked', false);
                        preparingFileModal.dialog('close');
                    },
                    failCallback: function (responseHtml, url) {
                        // show error status with close button
                        preparingFileModal.dialog('close');
                        close_button.css('display', 'block');
                        $("#error-modal").dialog({modal: true});
                    }
                }
            );

            return false;
        });
    });

    function toggle(source) {
        var checkboxes = document.getElementsByName('export_pdf');
        for (var i = 0, n = checkboxes.length; i < n; i++) {
            checkboxes[i].checked = source.checked;
        }
    }
</script>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值