1

I'm going to modify the below php script such that it downloads the database as a .pdf file rather than in a .csv format. How should I do that? Currently when this script is called, the database will be downloaded as a .csv file. The database is defined in directadmin.

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

require 'db.php';
define("tableStuff", "stuff");
define("tableUser", "user");

define("ERR", '{"status":1}');
define("INVALID", '{"status":2}');

define("rowUserId", "user_id");
define("rowRegDate", "reg_date");
define("rowStuffName", "stuff_name");
define("rowPurchaseDate", "purchase_date");
define("rowStuffCount", "stuff_count");
define("rowStuffDescription", "stuff_description");
define("rowPicUrl", "pic_url");
define("rowUserName", "user_name");

//**********************************************************************
$mysqli = mysqli_connect(DBIP, DBUN, DBPW, DBNAME);
if ($mysqli->connect_errno) {
    echo ERR;
    die;
}
mysqli_set_charset($mysqli, "utf8");
$result = $mysqli->query("SELECT ".rowStuffName.",".rowStuffCount.",".rowStuffDescription.",".rowPurchaseDate.",".tableStuff.".".rowRegDate.",".rowUserName." FROM " . tableStuff .",".tableUser.
    " WHERE " . tableStuff.".".rowUserId . " = " . tableUser.".".rowUserId);
if ($result->num_rows > 0) {
    $array = array();
    while ($row = $result->fetch_array(MYSQL_ASSOC)) {
        $array[] = $row;
    }
    header('Content-Encoding: UTF-8');
    header('Content-Type: application/csv; charset=utf-8' );
    header(sprintf( 'Content-Disposition: attachment; filename=stuff.csv', date( 'dmY-His' ) ) );
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    //echo pack("CCC",0xef,0xbb,0xbf);
    $title = array("نام کالا","تعداد (مقدار)","توضیحات","زمان ثبت","نام فرد ثبت کننده");
    $out = fopen("php://output", 'w');
    //fputs($out,"\xEF\xBB\xBF");
    fputcsv($out, $title,"\t");
    foreach ($array as $data)
    {
        fputcsv($out, $data,"\t");
    }
    fclose($out);
} else {
    echo INVALID;
}
mysqli_close($mysqli);
HoOman
  • 455
  • 1
  • 7
  • 15
  • If you want generate report, first you should generate html table, then you could use some kind of html to pdf (google it) converter to create pdf. There is no simple way of generating pdf from csv. – Ernestas Stankevičius Aug 01 '17 at 08:15
  • Go with @ErnestasStankevičius way. As for converter I would suggest wkhtmltopdf – Pavel Galaton Aug 01 '17 at 08:28

1 Answers1

-1

I am late,but i am using FPDF to generate all PDF files,It includes a built in example of making PDF with tables from CSV file,I just changed the source of CSV file.It is super easy.