how to store Datamatrix QR code in mysql Database? - php

I want store Data-matrix library generate QR code Image into mysql database using php. i am trying this by using jpgraph library.
please provide solution..
<?php
require_once('jpgraph/datamatrix/datamatrix.inc.php');
$data = '1234567890';
$shape = DMAT_AUTO;
$encoding = ENCODING_AUTO;
$modulewidth = 3;
$quietzone = 10;
$color1 = 'black';
$color0 = 'white';
$colorq = 'white';
$outputfile = '';
// Create and set parameters for the encoder
$encoder = DatamatrixFactory::Create($shape);
$encoder->SetEncoding($encoding);
// Create the image backend (default)
$backend = DatamatrixBackendFactory::Create($encoder);
// By default the module width is 2 pixel so we increase it a bit
$backend->SetModuleWidth($modulewidth);
// Set Quiet zone
$backend->SetQuietZone($quietzone);
// Set other than default colors (one, zero, quiet zone/background)
$backend->SetColor($color1, $color0, $colorq);
// Create the barcode from the given data string and write to output file
try {
$backend->Stroke($data,$outputfile);
} catch (Exception $e) {
$errstr = $e->GetMessage();
echo "Datamatrix error message: $errstr\n";
}
?>

$data = '123456789';
$pdf = new Pdf(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetTitle('ECOMAL ');
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$pdf->SetMargins(2,2,2);
$pdf->SetHeaderMargin(0);
$pdf->SetFooterMargin(0);
$pdf->SetAutoPageBreak(TRUE, 0);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
if (#file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
$pdf->SetFont('helvetica', 'B', 18);
$pdf->SetFont('helvetica', '', 15);
$style = array(
'fgcolor' => array(0,0,0),
'bgcolor' => false,
);
foreach ($data as $value) {
$tbl = '<table border="1" cellpadding="1">
<tr><td>
<table cellpadding="1" cellspacing="6" nobr="true">
<tr><td colspan="3"><h1> Vishy Intertechnology Inc.</h1></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><td>Customer PN</td><td colspan="2" ><b>'. $value["customer_pin"].'</b></td></tr>
<tr><td>Customer PO</td><td colspan="2" ><b>'. $value["customer_po"] .'</b></td></tr>
<tr><td>Manfacture PN</td><td colspan="2" >'. $value["manufacture_pin"] .' </td></tr>
<tr><td>Quantity</td><td>'.$value["quantity"].'</td><td rowspan="4" width="35%"></td></tr>
<tr><td>Date Code</td><td>'.$value["date_of_code"] .'</td></tr>
<tr><td>Lot No</td><td>'.$value["lot_no"] .'</td></tr>
<tr><td>Serial No</td><td>'. $value["serial_no"].' </td></tr>
<tr><td>MSL</td><td>'.$value["msl"].'</td><td><br></td></tr>
</table>
</td></tr>
</table><br><br>
';
$pdf->AddPage('L','A6');
//$pdf->SetY(50);
$pdf->writeHTML($tbl, true, false, false, false, '');
$pdf->write2DBarcode($value['code_string'], 'DATAMATRIX', 105, 48, 35, 35, $style, 'N');
}
//ob_clean();
//Close and output PDF document
//$rand = rand();
$pdf->Output($_SERVER['DOCUMENT_ROOT']."/alcon/assets/ecomal.pdf", 'F');
$pdf->Output("ecomal.pdf", 'I');

Related

create PDF with emoji utf-8 character using php

I am trying to create pdf with text including emoji character.
using PHP > 7 and mysql
'char_set' => utf8mb4
'dbcollat' => utf8mb4_unicode_ci
I have create PDF from html, is echo html text all emoji shown good. but if its create pdf its not convert.
Please help to solve this problem
exampple : "One \ud83d\ude02"
thanks
Here is more explanation for simplify my question.
$fileName = $source_path.'example.pdf';
//using php codeignitor 3.1.2
$htmlContent = $this->load->view('view/view_pdf', $data, TRUE);
$htmlContent = <<<EOD
$htmlContent
EOD;
// call pdf create function
$this->createPDF($fileName, $htmlContent);
// these character working correct as echo output on browser and send in email subject n body.
echo decodeEmoticons("One \ud83d\ude02");
echo "One \u{1F602}";
/*******************************/
// helper functions
function checkJson($title){
if (json_decode($title, true) !== null) {
$title = str_replace('"', '', json_decode($title));
}else{
$title = str_replace('"', '', $title);
}
return $title;
}
function decodeEmoticons($src) {
$replaced = preg_replace("/\\\\u([0-9A-F]{1,4})/i", "&#x$1;", $src);
$result = mb_convert_encoding($replaced, "UTF-16", "HTML-ENTITIES");
$result = mb_convert_encoding($result, 'utf-8', 'utf-16');
$result = checkJson($result);
return $result;
}
/*******************************/
$htmlContent output html code as follows
<div class="row">
<div class="col-lg-12">
<table class="table dataTable" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td colspan="3"> </td>
</tr>
<tr>
<td width="60%"><b>Event Name:</b> <?php echo decodeEmoticons("One \ud83d\ude02"); ?> </td>
<td width="60%"><b>Event Name:</b> <?php echo "One \u{1F602}"; ?> </td>
<td><b>Start Time:</b> <?php echo date('F j, Y, g:i A', time()); ?></td>
</tr>
<tr>
<td colspan="3"></td>
</tr>
</tbody>
</table>
</div>
</div>
here is my php function call TCpdf library
public function createPDF($fileName, $htmlContent) {
/*
http://www.tcpdf.org
// File name : tcpdf.php
// Version : 6.2.13
// Begin : 2002-08-03
// Last Update : 2015-06-18
*/
ob_start();
// Include the main TCPDF library (search for installation path).
$this->load->library(array('Tcpdf'));
// create new PDF document
$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
//$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, false, 'ISO-8859-1', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('auth');
$pdf->SetTitle('Event ');
$pdf->SetSubject('Event ');
$pdf->SetKeywords('Event ');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
$pdf->SetPrintHeader(false);
$pdf->SetPrintFooter(false);
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, 10, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(10);
$pdf->SetFooterMargin(30);
// set auto page breaks
//$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$pdf->SetAutoPageBreak(TRUE, 30);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (#file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
$pdf->SetFont('dejavusans', '', 10);
//$pdf->SetFont('halvatica', '', 10); // this is also trying but fail
// add a page
$pdf->AddPage();
//$htmlContent = utf8_encode($htmlContent);// this is also trying but fail
// output the HTML content
$pdf->writeHTML($htmlContent, true, false, true, false, '');
// reset pointer to the last pagend output PDF document
$pdf->lastPage();
ob_end_clean();
//Close and output PDF document
$pdf->Output($fileName, 'F');
}
pdf output not showing correct with emoji character.

how to solve this error of geting undefined offset 0 using TCPDF in PHP

this is the part that I declare to generate pdf from table. I have watch the tutorial in youtube and followed all the steps and I still got error. Im new in programming field and this is one of my mini project.
the error that i got is :
Notice: Undefined offset: 0 in C:\xampp\htdocs\tcpdff\tcpdf.php on line 17162
function fetch_data()
{
$output ='';
$conn = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
$query = "SELECT * FROM borang_permohonan";
$results = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($results))
{
$output .='
<tr>
<td>'.$row["fullname"].' </td>
<td>'.$row["ic_no"].'</td>
<td>'.$row["email"].' </td>
</tr>
';
}
return $output;
}
if(isset($_POST["create_pdf"]))
{
require_once('tcpdf.php');
$obj_pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$obj_pdf->SetCreator(PDF_CREATOR);
$obj_pdf->SetTitle("Export HTML Table data to pdf using TCPDF in PHP");
$obj_pdf->SetHeaderData('', '', PDF_HEADER_TITLE, PDF_HEADER_STRING);
$obj_pdf->SetHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$obj_pdf->SetFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
$obj_pdf->SetDefaultMonospacedFont('helvetica');
$obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
$obj_pdf->SetMargins(PDF_MARGIN_LEFT, '5', PDF_MARGIN_RIGHT);
$obj_pdf->setPrintHeader(false);
$obj_pdf->setPrintFooter(false); //or true
$obj_pdf->SetAutoPAgeBreak(TRUE, 10);
$obj_pdf->SetFont('helvetica', '', 12);
$content = '';
$content .= '
<center><h2 >GSM 2019</h2></center>
<table align="center" border="1">
<thead>
<tr>
<th>fullname</th>
<th>ic no</th>
<th>email</th>
</tr>
</thead>
';
$content .= fetch_data();
$content .= '</table>';
$obj_pdf->writeHTML($content);
$obj_pdf->Output("sample.pdf", "I");
}
?>
Any answer will be appreciated! Thank you!
You need to call the AddPage method before you start your WriteHtml
Good spot would probably be, right after SetFont
$obj_pdf->SetFont('helvetica', '', 12);
$obj_pdf->AddPage();
Instead of:
$obj_pdf->writeHTML($content);
Use this:
$obj_pdf->writeHTMLCell(0, 0 , '' , '' , $content);

Hindi is not displaying properly in TCPDF

I am trying to generate PDF using TCPDF with Hindi Unicode characters. I tried Mangal, Noto Sans, Arial Unicode fonts but all give the same output. If there is a "Matra" or "Half character" then it does not display properly.
See this output:
<?php
error_reporting(E_ALL);
ini_set("display_errors", "On");
require_once 'vendor/autoload.php';
$hindi_str = "राष्ट्रपति प्रणव मुखर्जी। ";
$hindi_str2 = "देश हमें देता है सब कुछ";
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
//$fontname_kannada = TCPDF_FONTS::addTTFfont('NotoSansKannada-Regular.ttf', 'TrueTypeUnicode', '', 96);
$fontname_hindi1 = TCPDF_FONTS::addTTFfont('NotoSansDevanagari-Regular.ttf', 'TrueTypeUnicode', '', 96);
$fontname_hindi2 = TCPDF_FONTS::addTTFfont('mangal.ttf', 'TrueTypeUnicode', '', 96);
$fontname_hindi3 = TCPDF_FONTS::addTTFfont("ARIALUNI.TTF", 'TrueTypeUnicode', '', 96);
// use the font
$pdf->AddPage();
$pdf->SetFont($fontname_hindi3, '', 14, '', false);
$pdf->writeHTML("<h1>Hindi $hindi_str $hindi_str2</h1>",true, false, true, false, '');
$pdf->Ln();
$pdf->writeHTML("<h1>Kannada ಖುತುಬ್ ಮಿನಾರ್ ಸಮೀಪವಿರುವ ಪ್ರಸಿದ್ಧ ಕಬ್ಬಿಣದ ಕಂಬ ಯಾರಿಗೆ ಸೇರಿದೆ</h1>",true, false, true, false, '');
// output the HTML content
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example.pdf', 'I');
Please help.
I know it's a little late, but I had the same problem for nepali (which also uses devanagari). I solved it like this:
// SOME FONTS DOES NOT SUPPORT DEVANAGARI, BUT FREESANS DOES
$pdf->SetFont('freesans', '', 10);
// MAKE ARRAY WITH UTF LANGUAGE IDENTIFIER
$lg = Array();
$lg['a_meta_charset'] = 'UTF-8';
$lg['a_meta_dir'] = 'ltr';
$lg['a_meta_language'] = 'np'; // I think you can change this to HI or IN for hindi
$lg['w_page'] = 'page';
// CHANGE SETTINGS IN TCPDF
$pdf->setLanguageArray($lg);
// MAKE SURE TO USE WriteHTML() function
$pdf->WriteHTML($yourhtml, true, 0, true, 0);
You can use this if Hindi is not showing on TCPDF
$pdf->SetFont('freesans', '', 10);
$lang = Array();
$lang['a_meta_charset'] = 'UTF-8';
$lang['a_meta_dir'] = 'ltr';
$lang['a_meta_language'] = 'IN';
$lang['w_page'] = 'page';
$pdf->setLanguageArray($lang);
$pdf->WriteHTML($html, true, 0, true, 0);

How to handle returning PDF file to be able to display in browser

I have ExtJS application that is querying database and showing the results in grid which is working properly.
Users can select any record from the grid by checkbox then send to server to print out. The server side code generate PDF file ( by TCPDF ) and return result the browser, it also works properly.
My problem is, client side doesn't show PDF file in browser window, instead of view just showing binary form of the PDF page.
So, could you please help me, how can I handle returning PDF file to show client screen?
CLIENT SIDE
{
xtype: 'button',
width: 90,
text: 'GÖNDER',
cls: 'x-btn-gonder',
handler: function(){
var ppt = Ext.getCmp('labelType').getValue();
var sb = Ext.getCmp('basic-statusbar');
var count = Ext.getCmp('labelGrids').getSelectionModel().getCount();
var rows = Ext.getCmp('labelGrids').getSelectionModel().getSelection();
if(ppt == null) {
dialog.show();
} else {
if(count > 0) {
var paper = {};
paper.PAPER = ppt;
var prints = new Array();
for (var i = 0; i < count; i++)
{
prints[i] = {'LABEL_ID': rows[i].data.LABEL_ID, 'LABEL_TYPE':rows[i].data.LABEL_TYPE}
}
paper.LABELS = prints;
Ext.Ajax.request({
url: 'lib/labels/print_label.php',
timeout: 60000,
success: function()
{
Ext.Msg.alert('İşlem Başarılı', 'Etiketler yazıcıya gönderildi.');
// set statusbar text after print
sb.setStatus({
text: 'Etiketler yazıcıya gönderildi..!',
iconCls: 'x-status-saved',
clear: true
});
// remove checked items
Ext.select('.x-grid-row-selected').each(function (element) {
Ext.getCmp('labelGrids').getSelectionModel().deselectAll();
});
},
failure: function() { Ext.Msg.alert('Yazdırma Hatası', 'Etiketler yazdırılamadı..!')},
jsonData: Ext.JSON.encode(paper)
});
// clear combobox selected value after send to printer
Ext.getCmp('labelType').reset();
// console.log(Ext.JSON.encode(prints));
} else if(count == 0) {
sb.setStatus({
iconCls: 'x-status-error',
text: 'Lütfen yazdırmak istediğiniz etiketleri seçiniz!'
});
}
winPaper.hide();
}
}
}
SERVER SIDE
<?php
require_once('../tcpdf/config/lang/eng.php');
require_once('../tcpdf/tcpdf.php');
$db = new mysqli("10.10.10.10","blabla","blablabla","label");
$db->query("SET NAMES UTF8");
$db->query("SET SQL_MODE='NO_AUTO_VALUE_ON_ZERO'");
$db->query("SET lc_time_names = 'tr_TR'");
$datas = json_decode(file_get_contents("php://input"));
// get paper type from json array
$paper = $datas->PAPER;
foreach($datas->LABELS as $data)
{
$lblids[] = $data->LABEL_ID;
}
$ids = implode(",", $lblids);
// get labels from db
$sql = "SELECT LABEL_ID, SUBSYS_ART_NO, ARTICLE_DESC, END_DATE, PRODUCT_PRICE, SHELF_PRICE, LABEL_TEXT, LABEL_TYPE, LABEL_SIGN, PROMO FROM labels WHERE LABEL_ID IN (".$ids.")";
$result = $db->query($sql);
while($row = $result->fetch_assoc())
{
$labels[] = $row;
}
switch($paper)
{
case "SF":
print_shelf($labels);
break;
}
function print_shelf($labels)
{
# defining PDF variables
$width = 100;
$height = 55;
$pageSize = array($width, $height);
# create new BMPL PDF price label
$pdf = new TCPDF('L', PDF_UNIT, $pageSize, true, 'UTF-8', false);
# set PDF document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Oğuz Çelikdemir, Metro Systems Turkey');
$pdf->SetTitle('BMPL Price Label');
# disable pdf document header and footer
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
# set PDF default font
$pdf->setDefaultMonospacedFont('PDF_FONT_MONOSPACED');
# set auto page breaks
$pdf->SetAutoPageBreak(true, 2);
$crs = array('width' => 0.5);
$style = array('width' => 0.25, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0));
for($i = 0; $i < count($labels); $i++)
{
# add PDF page
$pdf->addPage();
# split the price values
$prdPrice = explode(".", $labels[$i]['PRODUCT_PRICE']);
$shfPrice = explode(".", $labels[$i]['SHELF_PRICE']);
$prcLeft = $prdPrice[0];
$prcRight = $prdPrice[1];
$shfLeft = $shfPrice[0];
$shfRight = $shfPrice[1];
# Label variables
$priceLeft = '<span style="color:#b4b4b4;">'.$prcLeft.'</span>';
$priceLeftCent = '<span style="color:#b4b4b4;">'.$prcRight.'</span';
$priceRight = '<span style="color:#b4b4b4;">'.$shfLeft.'</span>';
$priceRightCent = '<span style="color:#000;">'.$shfRight.'</span>';
$taxLabelLeft = '<span style="color:#b4b4b4;">KDV\'Lİ</span>';
$taxLabelRight = 'KDV\'Lİ';
$articleDesc = '\''.$labels[$i]['ARTICLE_DESC'].'\'';
$articleNumber = $labels[$i]['SUBSYS_ART_NO'];
$labelText = '\''.$labels[$i]['LABEL_TEXT'].'\'';
$promoDate = $labels[$i]['END_DATE'];
$promoLabel = $labels[$i]['PROMO'];
////////////// PREPARE THE LABELS \\\\\\\\\\\\\\
# LABEL BOTTOM
$pdf->SetFont('dinpro', '', 6);
$pdf->writeHTMLCell(20, 0, 5, 50, $articleNumber, '', 1, 0, true, 'L');
$pdf->writeHTMLCell(20, 0, 28, 50, $promoDate, '', 1, 0, true, 'L');
if(is_null($promoLabel)) {
$pdf->writeHTMLCell(20, 0, 42, 50, '', '', 1, 0, true, 'R');
} else {
$pdf->writeHTMLCell(20, 0, 42, 50, 'FIRSAT', '', 1, 0, true, 'R');
}
# LABEL LEFT
$pdf->SetFont('dinprob', 'B', 10);
$pdf->MultiCell(90, 20, $articleDesc, 0, 'L', false, 1, 5, 5.50);
$pdf->SetFont('dinprob', '', 8);
$pdf->writeHTMLCell(45, 10, 5, 17, 'SATIŞ FİYATI', '', 1, 0, true, 'F');
$pdf->SetFont('dinprob', 'B', 44);
$pdf->writeHTMLCell(30, 27, 5, 24, $priceLeft, '', 1, 0, true, 'R', true);
$pdf->SetFont('dinprob', 'B', 20);
$pdf->writeHTMLCell(15, 10, 26.5, 28.5, $priceLeftCent, '', 1, 0, true, 'R', true);
$pdf->SetFont('dinpro', '', 6);
$pdf->writeHTMLCell(15, 10, 29.2, 37.3, $taxLabelLeft, '', 1, 0, 'L', true);
if(!is_null($labels[$i]['LABEL_SIGN']))
{
$pdf->Line(7, 41, 38, 22, $crs);
}
# LABEL RIGHT
$pdf->SetFont('dinprob','',8);
$pdf->writeHTMLCell(45, 10, 50, 17, $labelText, '', 1, 0, true, 'C');
$pdf->SetFont('dinprob', 'B', 58);
$pdf->writeHTMLCell(45, 30, 42, 21, $priceRight, '', 1, 0, true, 'R', true);
$pdf->SetFont('dinprob', 'B', 24);
$pdf->writeHTMLCell(15, 10, 79.5, 28, $priceRightCent, '', 1, 0, true, 'R', true);
$pdf->SetFont('dinpro', '', 6);
$pdf->writeHTMLCell(15, 10, 81, 38.5, $taxLabelRight, '', 1, 0, 'L', true);
$js .= 'print(true);';
$pdf->IncludeJS($js);
ob_end_clean();
return $pdf->Output('bpml_label.pdf', 'I');
}
}
?>
When you return the the PDF to the client, send it with the correct content type. Add this header before sending back the response
header('Content-Type: application/pdf');
Then the client can properly decide, what to do with the document.
I tried above suggestions but no success so that I did alternate way as belows :
First of all, some browsers doesn't support response object like PDF, therefore, I did postback to PDF file url then handle with an iframe inside the Ext window object.
success: function(response)
{
var _url = response.responseText;
new Ext.Window({
title: 'Labels',
id: 'pdfWindow',
layout: 'fit',
width: 600,
height: 500,
closeAction: 'destroy', // take notice that 'hide' action doesn't work
items: [{
xtype: 'component',
autoEl: {
tag: 'iframe', // we need iframes 'src' parameter to handle PDF
style: 'height:100%; width:100%; border:none',
// here we used special style to get rid of iframe title
src: _url
}
}]
}).show();
},
SERVER SIDE
// we need an unique ID to be able set unique file name
$uniqeid = uniqid(); # if you want add true parameter to extend sensibility
$filename = '/var/www/label/print/'.$uniqeid.'.pdf';
# F parameter creating the file in specified directory, don't forget to set security 777 for folder ortherwise you might take an error
$pdf->Output($filename, 'F');
echo('/print/'.$uniqeid.'.pdf');
Add target _blank to the printing button. Your browser will open it in a new window with PDF content generated by server.
Add content header as others advise:
header('Content-Type: application/pdf');

Generate PDF using TCPDF on ajax call

I'm using TCPDF class to generate PDF. First I send some data in json format (jquery) then I would like to generate PDF with these data.
Could you tell me if I am right. I should generate pdf, save it on the server and then if ajax call returns success, redirect the user to this pdf. Is a good way?
I have:
$.ajax({
url: '/pdf/fiele_to_generate_pdf.php',
type: 'POST',
contentType: "application/json; charset=utf-8",
data: $.toJSON(jsonObj),
processData: false,
dataType: 'html',
async: false,
success: function(html) {
window.location.href = '/pdf/example.pdf';
}
});
Thanks for any advice.
Edit: So I have sent a request to make the pdf via Ajax to the server, then the pdf file was generated and saved on the server. Then I have used window.location.href to redirect the user to this pdf. Everything works but I would like to avoid saving file on the server. Any ideas?
Ok this script will save the file and also display in the browser
the trick is in using the output method with the 'F' or 'I':
$pdf->Output("your path", 'F'); //save pdf
$pdf->Output('file.pdf', 'I'); // show pdf
CODE
<?php
class PDF extends TCPDF {
public function Header (){
$this->SetFont('dejavusans', '', 14);
$title = utf8_encode('title');
$subtitle = utf8_encode('sub title');
$this->SetHeaderMargin(40);
$this->Line(15,23,405,23);
}
public function Footer() {
$this->SetFont('dejavusans', '', 8);
$this-> Cell (0, 5, 'Pag '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'R', 0, '', 0, false, 'T', 'M');
}
public static function makeHTML ($json){
$html = '<table border="0.5" cellspacing="0" cellpadding="4">
<tr>
<th bgcolor="#DAB926" style="width:3%; text-align:left"><strong>you th</strong></th>
</tr>';
for ($i=0; $i<count($json); $i++)
{
$a= $i+1;
$html .= '<tr>
<td style="width:15%; text-align:left">'.$json[$i]->Name.'</td>
</tr>';
}
$html .= '</table>';
return $html;
}
}
function printReport ($json )
{
set_time_limit(0);
$pdf = new PDF("L", PDF_UNIT, "A3",true, 'UTF-8', false);
$pdf->SetMargins (15, 27, 15, true);
$pdf->SetFont('dejavusans', '', 8);
$pdf->SetAutoPageBreak(TRUE,50);
$pdf->AddPage();
//create html
$html = $pdf->makeHTML($json);
$pdf->writeHTML($html, false, false, false, false, '');
if (!file_exists("your path"))
mkdir("your path");
$pdf->Output("your path", 'F'); //save pdf
$pdf->Output('file.pdf', 'I'); // show pdf
return true;
}
$json = json_decode("your json");
printReport($json);
?>

Categories