In codeigniter how to get tcpdf custom header and footer - codeigniter

My controller to generate pdf is as folloe
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class C_test extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->library("Pdf");
}
public function create_pdf() {
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Vijay Kumar');
$pdf->SetTitle('TCPDF Example 001');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 001', PDF_HEADER_STRING, array(0,64,255), array(0,64,128));
$pdf->setFooterData(array(0,64,0), array(0,64,128));
// 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));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// 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);
}
// set default font subsetting mode
$pdf->setFontSubsetting(true);
$pdf->SetFont('dejavusans', '', 14, '', true);
$pdf->AddPage();
// set text shadow effect
$pdf->setTextShadow(array('enabled'=>true, 'depth_w'=>0.2, 'depth_h'=>0.2, 'color'=>array(196,196,196), 'opacity'=>1, 'blend_mode'=>'Normal'));
// Set some content to print
$html = <<<EOD
<h1>Welcome to pdf gen</h1>
EOD;
// Print text using writeHTMLCell()
$pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
$pdf->Output('example_001.pdf', 'I');
}
}
pdf.php library
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once dirname(__FILE__) . '/tcpdf/tcpdf.php';
class Pdf extends TCPDF
{
function __construct()
{
parent::__construct();
}
}
I want to generate a pdf with custom header and footer, header is image and footer is dynamic name and need page number
In controller how to do this to work with custom pdf header and footer

You need extend TCPDF in order to use custom header and footer
class PDF extends TCPDF {
//Page header
public function Header() {
// Logo
$image_file = K_PATH_IMAGES.'logo_example.jpg';
$this->Image($image_file, 10, 10, 15, '', 'JPG', '', 'T', false, 300, '', false, false, 0, false, false, false);
// Set font
$this->SetFont('helvetica', 'B', 20);
// Title
$this->Cell(0, 15, '<< TCPDF Example 003 >>', 0, false, 'C', 0, '', 0, false, 'M', 'M');
}
// Page footer
public function Footer() {
// Position at 15 mm from bottom
$this->SetY(-15);
// Set font
$this->SetFont('helvetica', 'I', 8);
// Page number
$this->Cell(0, 10, 'Page '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
}
}
Even I did like this and got my result.
reference: https://tcpdf.org/examples/example_003/

Related

Codeigniter 4 dropzone upload after redirect url

I am uploading files with Codeigniter 4. I want the page to refresh after loading but my code is not working. Here is the controller I use.
At the bottom I have the code for the redirect but this code is not working.
<?php namespace App\Controllers;
use App\Models\Hizmetmodels;
use App\Models\Dosyamodels;
class Dosyacontroller extends BaseController
{
protected $helpers = ['form' ,'url'];
protected $Dosyamodels;
public function index($sap = null)
{
$Hizmetmodels= new Hizmetmodels();
$data['hizmetsat'] = $Hizmetmodels->where('sap', $sap)->first();
$Dosyamodels= new Dosyamodels();
$where = "sap='$sap'";
$data['dosya'] = $Dosyamodels->orderBy('id', 'ASC')->where($where)->findAll();
return view('Admin/Dosyalar/index', $data);
}
public function form()
{
$sap = $this->request->getPost('sap');
$Dosyamodels= new Dosyamodels();
helper(['text','inflector']);
$file = $this->request->getFile('file');
$size = $file->getSize();
$kilobytes = $file->getSizeByUnit('kb');
$path = 'public/uploads';
$name = convert_accented_characters(underscore($file->getName()));
$newname = "$sap-$name";
$file->move(ROOTPATH . $path, $newname);
$ext = $file->getClientExtension();
$data = [
'adi' => $newname,
'yol' => $path . '/' . $name,
'sap' => $sap,
'boyut' => $kilobytes,
'uzt' => $ext,
];
$save = $Dosyamodels->insert($data);
return redirect()->to('/Dosyalar/index/'. $sap)->with('success', 'Tebrikler! <br> Dosyalar başarı ile yüklendi.');
}
}
The issue could be with the redirect URL that you are trying to redirect to. In this case, the URL is /Dosyalar/index/'. $sap which is missing the base URL. To resolve the issue, you can use the base URL in the redirect URL, like this:
return redirect()->to(base_url('Dosyalar/index/'. $sap))->with('success', 'Tebrikler! <br> Dosyalar başarı ile yüklendi.');
Try to change
this.on('queuecomplete', function (file) { location.reload(); }); to this.on('success', function (file, responseText) { location.reload(); });
With dropzone the document is uploaded to the correct folder. saved to the database. no problems so far. the only problem is i can't refresh the page no matter what i do after it loads.here is my java script code:
$(function() {
Dropzone.options.dropzoneform = {
paramName: 'file',
maxFilesize: 2, // MB
maxFiles: 5,
init: function () {
this.on('queuecomplete', function (file) {
location.reload();
});
}
}
});

How to fix Paypal Checkout Order Creation Error

I am using Laravel 8 framework for PHP and I am trying to integrate paypal into my the local web.
However I am stuck on `create_order_error` even though I have strictly followed some sample snippets provided by paypal I still encounter this pro
References:
https://developer.paypal.com/demo/checkout/#/pattern/server
https://github.com/paypal/Checkout-PHP-SDK#code
https://developer.paypal.com/docs/checkout/reference/server-integration/
Error:
SyntaxError: Unexpected token < in JSON at positio…1kLoyti46gxJY-Rl1PH23n49yWhf&currency=PHP:2:79380"
Code:
<script>
// Render the PayPal button into #paypal-button-container
paypal.Buttons({
style: {
shape: 'pill',
layout: 'horizontal',
color: 'blue',
height: 35
},
// Call your server to set up the transaction
createOrder: function(data, actions) {
return fetch('/billing/createOrder', {
method: 'post',
headers: {
'content-type': 'application/json'
}
}).then(function(res) {
return res.json();
}).then(function(orderData) {
return orderData.id;
});
},
}).render('#paypal-button-container');
</script>
Note: I have removed the onApprove function since I'm stuck on createOrder
Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\SandboxEnvironment;
use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
use PayPalHttp\HttpException;
class PaypalCheckoutController extends Controller
{
private $environment;
private $client;
public function __construct()
{
$this->environment = new SandboxEnvironment(config('paypal.client_id'), config('paypal.secret'));
$this->client = new PayPalHttpClient($this->environment);
}
public function index(Request $request)
{
return view('payment.checkout');
}
public function createOrder(Request $request)
{
$order = new OrdersCreateRequest();
$order->prefer('return=representation');
$order->body = array(
'intent' => 'CAPTURE',
'application_context' =>
array(
'return_url' => 'http://dummyweb.test/billing/checkout',
'cancel_url' => 'http://dummyweb.test/billing/checkout'
),
'purchase_units' =>
array(
0 =>
array(
'amount' =>
array(
'currency_code' => 'PHP',
'value' => '420.00'
)
)
)
);
try {
$result = $this->client->execute($order);
return $result;
}
catch(HttpException $ex) {
print_r($ex->getMessage());
}
}
}
SyntaxError: Unexpected token < in JSON at positio…
You are returning things other than JSON when the browser calls /billing/createOrder. You must only return JSON.
Use the Network tab in your browser's Developer Tools, or load the path in a new tab, to inspect the Response Body of what you are actually returning.
It will clearly be something other than JSON. Based on that error message it will start with some HTML (the < character)
Only return JSON. You need to be able to copy the entire Response Body into a JSON validator and have it be OK.
try
return response()->json($result);
and in the fetch request add header
Accept: 'application/json'

Laravel display "FPDF error: No page has been added yet"

I am using the fpdf library for my laravel project. I create a class for the header and footer function. Then call thess functions on my pdf controller. I encounter this error "FPDF error: No page has been added yet" and I have no idea where this error came from. Can you teach me on how to fix this bug/error. Thanks in advance.
Codes from my controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Codedge\Fpdf\Fpdf\Fpdf;
use App\Personnel;
use App\Classes\PDFClass;
class PFTReportController extends Controller
{
public function postPFTReport(Request $request)
{
$pdf = new FPDF();
$pdf->AddPage('P', 'A4');
$pdf->Ln(4);
$pdf->SetFont('Arial', '', 12);
// Call the header for this report
$pdfClass = new PDFClass();
$header = $pdfClass->Header();
$pdf->Cell(0, 4, 'Sample Report', 0, 1, 'C');
$pdf->Ln(2);
$pdf->Output();
exit;
}
}
Code of the class
namespace App\Classes;
use Codedge\Fpdf\Fpdf\Fpdf;
class PDFClass extends Fpdf
{
protected $B = 0;
protected $I = 0;
protected $U = 0;
protected $HREF = '';
// Page header
function Header()
{
$this->SetFont('Arial', '', 11);
$this->Cell(0, 2, 'Line 1', 0, 1, 'C');
$this->Cell(0, 8, 'Line 2', 0, 1, 'C');
$this->SetFont('Arial', 'B', 12);
$this->Cell(0, 1, 'Line 3', 0, 1, 'C');
$this->Cell(0, 8, 'Line 4', 0, 1, 'C');
$this->SetFont('Arial', '', 12);
$this->Cell(0, 1, 'Line 5', 0, 1, 'C');
$this->Ln(8);
}
}
You create 2 class instances. The first is FPDF where you add a page:
$pdf = new FPDF();
$pdf->AddPage('P', 'A4');
$pdf->Ln(4);
$pdf->SetFont('Arial', '', 12);
...then you create a new one and simply call your Header() method manually:
$pdfClass = new PDFClass();
$header = $pdfClass->Header();
This doesn't make sense and at this point the error is thrown, because you call several methods in Header() which should output content to a page but you didn't added one before.
You should only use PDFClass and you also should not call the Header() method manually because it is called internally automatically.
public function postPFTReport(Request $request)
{
$pdf = new PDFClass();
$pdf->AddPage('P', 'A4'); // NOW THE HEADER() METHOD IS INVOKED AUTOMATICALLY IN THIS CALL
$pdf->Ln(4);
$pdf->SetFont('Arial', '', 12);
$pdf->Cell(0, 4, 'Sample Report', 0, 1, 'C');
$pdf->Ln(2);
$pdf->Output();
exit;
}

How to change url of back button in grid form in admin of magento?

I am working Magento community edition 1.7 version.
I have a grid in admin panel.
Now when I click on this URL it open a form with two tabs in left sidebar.
When I click on second tab it show a grid in its right side.
Then I click on a row of this grid it opens a form on another page.
In this form there is back button.
How can I change its URL to previous page?
Add your custom back button and remove default one in your Form Container class constructor.
$data = array(
'label' => 'Back',
'onclick' => 'setLocation(\'' . $this->getUrl('*/*/*') . '\')',
'class' => 'back'
);
$this->addButton ('my_back', $data, 0, 100, 'header');
...
parent::__construct();
...
$this->_removeButton('back');
Just need to override getBackUrl function:
class [Namespace]_[Module]_Block_Adminhtml_[CustomBlock] extends Mage_Adminhtml_Block_Widget_Form_Container
{
/** code **/
public function getBackUrl()
{
parent::getBackUrl();
return $this->getUrl('[New URL]');
}
/** code **/
}
Note: Tested in Magento ver. 1.9.1.0
simply override the default back button:
parent::__construct();
$data = array(
'label' => 'Back',
'onclick' => 'setLocation(\'' . $this->getUrl('*/*/*') . '\')',
'class' => 'back'
);
$this->addButton ('back', $data, 0, 100, 'header');
Notice the placement of parrent::__construct();
Here is simplest way to change url of back button.
protected function _construct()
{
$this->_objectId = 'row_id';
$this->_blockGroup = 'Namespace_Modulename';
$this->_controller = 'adminhtml_grid';
parent::_construct();
if ($this->_isAllowedAction('Namespace_Modulename::add_row')) {
$this->buttonList->update('save', 'label', __('Save'));
} else {
$this->buttonList->remove('save');
}
/**
* Below line to change your back url of grid
*/
$this->buttonList->update('back', 'onclick', 'setLocation(\'' . $this->getUrl('*/*/index') . '\')');
}

Passing parameters when initializing a library in Codeigniter

I am really new to Codeigniter, and just learning from scratch. In the CI docs it says:
$params = array('type' => 'large', 'color' => 'red');
$this->load->library('Someclass', $params);
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Someclass {
public function __construct($params)
{
// Do something with $params
}
}
Can you give me simple example how to pass data from controller to external library using array as parameters? I'd like to see a simple example.
All Codeigniter "library" constructors expect a single argument: an array of parameters, which are usually passed while loading the class with CI's loader, as in your example:
$params = array('type' => 'large', 'color' => 'red');
$this->load->library('Someclass', $params);
I'm guessing you're confused about the "Do something with $params" part. It's not necessary to pass in any params, but if you do you might use them like this:
class Someclass {
public $color = 'blue'; //default color
public $size = 'small'; //default size
public function __construct($params)
{
foreach ($params as $property => $value)
{
$this->$property = $value;
}
// Size is now "large", color is "red"
}
}
You can always re-initialize later like so, if you need to:
$this->load->library('Someclass');
$this->Someclass->__construct($params);
Another thing to note is that if you have a config file that matches the name of your class, that configuration will be loaded automatically. So for example, if you have the file application/config/someclass.php:
$config['size'] = 'medium';
$config['color'] = 'green';
// etc.
This config will be automatically passed to the class constructor of "someclass" when it is loaded.
In libraries directory create one file Someclass_lib.php
Here is your Library code
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Someclass_lib
{
public $type = '';
public $color = '';
function Someclass_lib($params)
{
$this->CI =& get_instance();
$this->type = $params['type'];
$this->color = $params['color'];
}
}
Use this code when you want to load library
$params = array('type' => 'large', 'color' => 'red');
$this->load->library('Someclass_lib', $params);

Resources