How to change the size of the pdf in prestashop using TPDF - pdf

I want the size of the paper to be increased to A3 OR OR C4 (width to be increased)
I tried below but no change is there anyway to change the size of the pdf generated?
public function generatePDF($object, $template)
{
switch($template) {
case PDF::TEMPLATE_ETICKET:
$format = 'C3'; // Replace with your desired size
break;
default:
$format = 'A4'; // Replace with normal size
}
$pdf = new PDF($object, $template, Context::getContext()->smarty,'P', $format);
//d($pdf);
$pdf->render();
}

Create a file PDFGenerator.php in override/classes/pdf.
in to PDFGenerator.php insert:
<?php
class PDFGenerator extends PDFGeneratorCore
{
public function __construct($use_cache = false, $orientation = 'P')
{
parent::__construct($orientation, 'mm', 'A3', true, 'UTF-8', $use_cache, false); /*Replace A3 with the size you prefer */
$this->setRTL(Context::getContext()->language->is_rtl);
}
}
delete cache/class_index.php

Related

Can I resize an image on upload in symfony 5?

I am trying to figure out how to resize an image on upload with symfony 5. Actually my fileupload is working perfectly, but it would be such a relief not to resize all my pics before I have to upload them.
Is there a way I can do this?
Here is my upload code:
if($form->isSubmitted() && $form->isValid()){
$imageFile = $form->get('file')->getData();
if($imageFile) {
#CAN'T RESIZE HERE BEFORE UPLOAD ???
$imageFileName = $fileUploader->upload($imageFile);
$image->setFilename($imageFileName);
}
#.....persist - flush etc.
}
First this is my controller with a method to upload an image from a form:
/**
* #Route("/admin/image/new", name="admin_image_new")
*/
public function newImage(Request $request, EntityManagerInterface $manager, FileUploader $fileUploader, ImageResizeService $imageResize)
{
$image = new Image();
$form = $this->createForm(ImageType::class, $image);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$imageFile = $form->get('file')->getData();
if($imageFile) {
$imageFileName = $fileUploader->upload($imageFile);
$image->setFilename($imageFileName);
}
$manager->persist($image);
$manager->flush();
$this->addFlash('success', 'Image added successfully !');
$imageName = $image->getFilename();
$fullSizeImgWebPath = $fileUploader->getTargetDirectory().'/'.$imageName;
[$width,$height] = getimagesize($fullSizeImgWebPath);
if($width > $height){
$width = 1500;
$height = 1000;
// $imageResize->writeThumbnail($fullSizeImgWebPath, 1500, 1000);
} else if($width == $height){
$width = 300;
$height = 300;
//$imageResize->writeThumbnail($fullSizeImgWebPath, 300, 300);
} else {
$width = 1500;
$height = 2254;
//$imageResize->writeThumbnail($fullSizeImgWebPath,1000,1600);
}
$imageResize->writeThumbnail($fullSizeImgWebPath, $width, $height);
return $this->redirectToRoute('admin_image');
}
return $this->render('admin/image/new_image.html.twig', [
'controller_name' => 'AdminImageController',
'form'=> $form->createView()
]);
}
I created a service to resize the uploaded image:
class ImageResizeService {
/**
* Write a thumbnail image using Imagine
*
* #param string $thumbAbsPath full absolute path to attachment directory e.g. /var/www/project1/images/thumbs/
*/
public function writeThumbnail($thumbAbsPath, $width, $height) {
$imagine = new Imagine;
$image = $imagine->open($thumbAbsPath);
$size = new Box($width, $height);
$image->thumbnail($size,ImageInterface::THUMBNAIL_OUTBOUND)
->save($thumbAbsPath);
}
}

How to resize image yii2 when uploading

This is my post controller function. I always upload images less then 200x200, and those images are stored in the 'upload' folder. After uploading the image, the id number is changed to something like 4546464.png. But I want to change the image size to 60x60 when uploading and store it after changing the size and quality to 60x60x30. This code uploads fine but not changing size and quality.
public function actionCreate() {
$model = new Monitor();
if ($model->load(Yii::$app->request->post())) {
if ($model->payment_processor) {
$model->payment_processor = implode(',', $model>payment_processor);
}
$model->file = UploadedFile::getInstance($model, 'file');
if ($model->file != '') {
$model->image = time() . '.' . $model->file->extension;
}
$model->update_at = date('Y-m-d h:i:s');
$model->save();
if ($model->file != '') {
$model->file->saveAs('upload/' . $model->image);
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', ['model' => $model]);
}
}
, you have to first upload the image in your server then resize it to what size you want , another way is before you
$model->file->saveAs('upload/' . $model->image);
resize it , but i recommend to you save the Original file and then resize it as a copy.
here is function to resize and crop image from center :
public static function resize_crop_image($max_width, $max_height, $source_file, $dst_dir, $quality = 100){
$quality = 10;
$imgsize = getimagesize($source_file);
$width = $imgsize[0];
$height = $imgsize[1];
$mime = $imgsize['mime'];
switch($mime){
case 'image/gif':
$image_create = "imagecreatefromgif";
$image = "imagegif";
break;
case 'image/png':
$image_create = "imagecreatefrompng";
$image = "imagepng";
$quality = 9;
break;
case 'image/jpeg':
$image_create = "imagecreatefromjpeg";
$image = "imagejpeg";
$quality = 100;
break;
default:
return false;
break;
}
$dst_img = imagecreatetruecolor($max_width, $max_height);
$src_img = $image_create($source_file);
$width_new = $height * $max_width / $max_height;
$height_new = $width * $max_height / $max_width;
//if the new width is greater than the actual width of the image, then the height is too large and the rest cut off, or vice versa
if($width_new > $width){
//cut point by height
$h_point = (($height - $height_new) / 2);
//copy image
imagecopyresampled($dst_img, $src_img, 0, 0, 0, $h_point, $max_width, $max_height, $width, $height_new);
}else{
//cut point by width
$w_point = (($width - $width_new) / 2);
imagecopyresampled($dst_img, $src_img, 0, 0, $w_point, 0, $max_width, $max_height, $width_new, $height);
}
$image($dst_img, $dst_dir, $quality);
if($dst_img)imagedestroy($dst_img);
if($src_img)imagedestroy($src_img);
}
use this function as easy you can :
yourModel::resize_crop_image(150,150, $path, 'upload/'.$name_you_want_or_random_string.'.jpg',$q);
the $path is a path of the original file that uploaded .
you have to create a upload folder in your web app directory or change destination to where you want .
I am using the imageprocessor extension and I'm very happy with it. You just have to add confgurations to the imageprocessor component and on save you have to call the save method of the component. It will create a new image with the size you've configured. It has a nice documentation. Give it a try.

how to add an image to product in prestashop

i have a pragmatically added product in my code , the product is added to presta correctly but not about its image .
here is some part of my code that i used :
$url= "localhost\prestashop\admin7988\Hydrangeas.jpg" ;
$id_productt = $object->id;
$shops = Shop::getShops(true, null, true);
$image = new Image();
$image->id_product = $id_productt ;
$image->position = Image::getHighestPosition($id_productt) + 1 ;
$image->cover = true; // or false;echo($godyes[$dt][0]['image']);
if (($image->validateFields(false, true)) === true &&
($image->validateFieldsLang(false, true)) === true && $image->add())
{
$image->associateTo($shops);
if (! self::copyImg($id_productt, $image->id, $url, 'products', false))
{
$image->delete();
}
}
but my product have not any image yet
the problem is in copyImg method ...
here is my copyImg function :
function copyImg($id_entity, $id_image = null, $url, $entity = 'products')
{
$tmpfile = tempnam(_PS_TMP_IMG_DIR_, 'ps_import');
$watermark_types = explode(',', Configuration::get('WATERMARK_TYPES'));
switch ($entity)
{
default:
case 'products':
$image_obj = new Image($id_image);
$path = $image_obj->getPathForCreation();
break;
case 'categories':
$path = _PS_CAT_IMG_DIR_.(int)$id_entity;
break;
}
$url = str_replace(' ' , '%20', trim($url));
// Evaluate the memory required to resize the image: if it's too much, you can't resize it.
if (!ImageManager::checkImageMemoryLimit($url))
return false;
// 'file_exists' doesn't work on distant file, and getimagesize make the import slower.
// Just hide the warning, the traitment will be the same.
if (#copy($url, $tmpfile))
{
ImageManager::resize($tmpfile, $path.'.jpg');
$images_types = ImageType::getImagesTypes($entity);
foreach ($images_types as $image_type)
ImageManager::resize($tmpfile, $path.'-'.stripslashes($image_type['name']).'.jpg', $image_type['width'],
$image_type['height']);
if (in_array($image_type['id_image_type'], $watermark_types))
Hook::exec('actionWatermark', array('id_image' => $id_image, 'id_product' => $id_entity));
}
else
{
unlink($tmpfile);
return false;
}
unlink($tmpfile);
return true;
}
can anybody help me ?
You have 2 issues:
You are passing 5th parameter (with value) to copyImg, while the function does not have such.
Your foreach ($images_types as $image_type) loop must include the Hook as well (add open/close curly braces).
foreach ($images_types as $image_type)
{
ImageManager::resize($tmpfile, $path.'-'.stripslashes($image_type['name']).'.jpg', $image_type['width'], $image_type['height']);
if (in_array($image_type['id_image_type'], $watermark_types))
Hook::exec('actionWatermark', array('id_image' => $id_image, 'id_product' => $id_entity));
}
You should also check if the product is imported correctly, expecially the "link_rewrite" and if the image is phisically uploaded in the /img/ folder.

How to resize a image while uploading in ZF2

I'm new to Zend Frame work and I need to implement image resize while uploading in zend framework 2. I try to use the method in image resize zf2 but it didnot work for me.
please help?
public function addAction(){
$form = new ProfileForm();
$request = $this->getRequest();
if ($request->isPost()) {
$profile = new Profile();
$form->setInputFilter($profile->getInputFilter());
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('fileupload');
$width = $this->params('width', 30); // #todo: apply validation!
$height = $this->params('height', 30); // #todo: apply validation!
$imagine = $this->getServiceLocator()->get('my_image_service');
$image = $imagine->open($File['tmp_name']);
$transformation = new \Imagine\Filter\Transformation();
$transformation->thumbnail(new \Imagine\Image\Box($width, $height));
$transformation->apply($image);
$response = $this->getResponse();
$response->setContent($image->get('png'));
$response
->getHeaders()
->addHeaderLine('Content-Transfer-Encoding', 'binary')
->addHeaderLine('Content-Type', 'image/png')
->addHeaderLine('Content-Length', mb_strlen($imageContent));
return $response;
$data = array_merge(
$nonFile,
array('fileupload'=> $File['name'])
);
$form->setData($data);
if ($form->isValid()) {
$size = new Size(array('min'=>100000)); //minimum bytes filesize
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setValidators(array($size), $File['name']);
if (!$adapter->isValid()){
$dataError = $adapter->getMessages();
$error = array();
foreach($dataError as $key=>$row)
{
$error[] = $row;
}
$form->setMessages(array('fileupload'=>$error ));
} else {
$adapter->setDestination('./data/tmpuploads/');
if ($adapter->receive($File['name'])) { //identify the uploaded errors
$profile->exchangeArray($form->getData());
echo 'Profile Name '.$profile->profilename.' upload '.$profile->fileupload;
}
}
}
}
return array('form' => $form);
}
Related to :-image resize zf2
I get answer for this question by adding external library to zend module.It is a easy way for me. i used http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/ class as external library.this is my controller class.
class ProfileController extends AbstractActionController{
public function addAction()
{
$form = new ProfileForm();
$request = $this->getRequest();
if ($request->isPost()) {
$profile = new Profile();
$form->setInputFilter($profile->getInputFilter());
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('fileupload');
$data = array_merge(
$nonFile,
array('fileupload'=> $File['name'])
);
//set data post and file ...
$form->setData($data);
if ($form->isValid()) {
$size = new Size(array('min'=>100000)); //minimum bytes filesize
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setValidators(array($size), $File['name']);
if (!$adapter->isValid()){
$dataError = $adapter->getMessages();
$error = array();
foreach($dataError as $key=>$row)
{
$error[] = $row;
}
$form->setMessages(array('fileupload'=>$error ));
} else {
$adapter->setDestination('//destination for upload the file');
if ($adapter->receive($File['name'])) {
$profile->exchangeArray($form->getData());
//print_r($profile);
echo 'Profile Name '.$profile->profilename.' upload '.$profile->fileupload;
$image = new SimpleImage();
$image->load('//destination of the uploaded file');
$image->resizeToHeight(500);
$image->save('//destination for where the resized file to be uploaded');
}
}
}
}
return array('form' => $form);
}
}
Related:-Zend Framework 2 - How to use an external library
http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/

How to let the user choose the upload directory?

I have a form used to upload images in my blog engine. The files are uploaded to web/uploads, but I'd like to add a "choice" widget to let the users pick from a list of folders, for instance 'photos', 'cliparts', 'logos'.
Here's my form
class ImageForm extends BaseForm
{
public function configure()
{
$this->widgetSchema->setNameFormat('image[%s]');
$this->setWidget('file', new sfWidgetFormInputFileEditable(
array(
'edit_mode'=>false,
'with_delete' => false,
'file_src' => '',
)
));
$this->setValidator('file', new mysfValidatorFile(
array(
'max_size' => 500000,
'mime_types' => 'web_images',
'path' => 'uploads',
'required' => true
)
));
$this->setWidget('folder', new sfWidgetFormChoice(array(
'expanded' => false,
'multiple' => false,
'choices' => array('photos', 'cliparts', 'logos')
)
));
$this->setValidator('folder', new sfValidatorChoice(array(
'choices' => array(0,1,2)
)));
}
}
and here is my action :
public function executeAjout(sfWebRequest $request)
{
$this->form = new ImageForm();
if ($request->isMethod('post'))
{
$this->form->bind(
$request->getParameter($this->form->getName()),
$request->getFiles($this->form->getName())
);
if ($this->form->isValid())
{
$this->form->getValue('file')->save();
$this->image = $this->form->getValue('file');
}
}
I'm using a custom file validator :
class mySfValidatorFile extends sfValidatorFile
{
protected function configure($options = array(), $messages =
array())
{
parent::configure();
$this->addOption('validated_file_class',
'sfValidatedFileFab');
}
}
class sfValidatedFileFab extends sfValidatedFile
{
public function generateFilename()
{
return $this->getOriginalName();
}
}
So how do I tell the file upload widget to save the image in a different folder ?
You can concatenate the directory names you said ('photos', 'cliparts', 'logos') to the sf_upload_dir as the code below shows, you will need to create those directories of course.
$this->validatorSchema['file'] = new sfValidatorFile(
array('path' => sfConfig::get('sf_upload_dir' . '/' . $path)
));
Also, you can have those directories detailes in the app.yml configuration file and get them calling to sfConfig::get() method.
I got it to work with the following code :
public function executeAdd(sfWebRequest $request)
{
$this->form = new ImageForm();
if ($request->isMethod('post'))
{
$this->form->bind(
$request->getParameter($this->form->getName()),
$request->getFiles($this->form->getName())
);
if ($this->form->isValid())
{
//quel est le dossier ?
switch($this->form->getValue('folder'))
{
case 0:
$this->folder = '/images/clipart/';
break;
case 1:
$this->folder = '/images/test/';
break;
case 2:
$this->folder = '/images/program/';
break;
case 3:
$this->folder = '/images/smilies/';
break;
}
$filename = $this->form->getValue('file')->getOriginalName();
$this->form->getValue('file')->save(sfConfig::get('sf_web_dir').$this->folder.$filename);
//path :
$this->image = $this->folder.$filename;
}
}