DOMPDF only showing image watermark on the last page - php

I'm trying to display an image watermark using DomPdf, but it only appears on the last page. I've looked on some sites, but I haven't found anything related.
That's my code:
<?php
require_once 'dompdf/autoload.inc.php';
//referenciar o DomPDF com namespace
use Dompdf\Dompdf;
//Referenciar o NameSpace Options
use Dompdf\Options;
//Definir Options para habilitar PHP incorporado.
$options = new Options();
$options->set('isPhpEnabled', 'true');
//Criando a Instancia
$dompdf = new Dompdf($options);
// Carrega seu HTML
$dompdf->loadhtml("<h3>https://www.TutorialsWebsite.com</h3><center><h1>Welcome to Tutorials Website</h1><div class="wpb_wrapper">
<p><strong>Tutorialswebsite</strong> is a leading online education portal that helps technologies, software, business and creative skills readers to learn new skills at their own place from the comforts of their drawing rooms. Individual, corporate and academic members have access to learn anything on tutorialswebsite.com likes video tutorials, blogs content etc.</p>
<p>From 5 years, we worked our way to adding new fresh articles on topics ranging from programming languages that helps students, leaders, IT and design professionals, project managers or anyone who is working with software development, creatives and business skills.</p>
<h2 style="text-align: center;">Mission</h2>
<p>Our mission is to deliver easy and best online resources on programming and web development to encourage our readers acquire as many skills as they would like to. We offer the useful and best tutorials for web professionals-developers, programmers, freelancer free of cost. We don’t force our readers to sign up with us or submit their details.</p>
 
</div><h2 style="font-size: 24px;text-align: center;font-family:Roboto;font-weight:700;font-style:normal" class="vc_custom_heading">About Author</h2>
<p>
<strong>Pradeep Maurya</strong> is the Professional Web Developer and Founder of “Tutorialswebsite”. He lives in Delhi and loves to be a self dependent person. As an author, he is trying his best to improve this platform day by day.
You can contact him <strong>#facebook</strong><strong>Website:</strong> https://www.pradeepmaurya.in</p></center>
'");
$dompdf->setPaper('A4', 'portrait');
//Renderizar o html
$dompdf->render();
//Instanciar o Canvas
$canvas = $dompdf->getCanvas();
//Recuperar Altura e Largura da página
$width = $canvas->get_width();
$height = $canvas->get_height();
//Especifica a Imagem de Marca D'Água
$imageURL = 'img/forper.png';
$imgHeight = 511;
$imgWidth = 250;
//Define a Opacidade da Imagem
$canvas->set_opacity(.3);
//Especifica as posições horizontal e vertical
$x = (($width - $imgWidth) / 2);
$y = (($height - $imgHeight) / 2);
//Adiciona a Imagem ao PDF
$canvas->image($imageURL, $x, $y, $imgWidth, $imgHeight);
//Exibibir a página
$dompdf->stream(
"$nip.pdf",
array(
'Attachment' => false //Para realizar o download somente alterar para true
)
);
?>
I changed the HTML because the old one was too big.
If there is only one page, the watermark will appear correctly, but if there are two or more pages, the image will only appear on the last one.
I've tried to add the code below to add the watermark in the first page, but the image is in front of the text.
// Dirty fix for images and lines
$canvas->page_script('
$image = \'img/image.png\';
// $pdf is the variable containing a reference to the canvas object provided by dompdf
$pdf->image($image, ' . $x . ', ' . $y . ', ' . $imgWidth . ', ' . $imgHeight . ');
');

You have to use page_script function (like you did) but you need to edit the canvas inside too.
To avoid formatting error and keeping a good syntax for maintaining, I suggest adding a new file with the canvas code only.
canvasScript.php
$canvas = $dompdf->getCanvas();
$width = $canvas->get_width();
$height = $canvas->get_height();
$imageURL = 'img/forper.png';
$imgHeight = 511;
$imgWidth = 250;
$canvas->set_opacity(.3);
$x = (($width - $imgWidth) / 2);
$y = (($height - $imgHeight) / 2);
$canvas->image($imageURL, $x, $y, $imgWidth, $imgHeight);
Your code
// [...]
// Renderize HTML
$dompdf->render();
// Add watermark to all pages
$canvasScript = file_get_contents('/canvasScript.php');
$canvas->page_script($canvasScript);
$dompdf->stream("your_pdf.pdf");
dompdf has no documentation and lack this kind of use, I recommend using mpdf/mpdf next time.

Related

Upload Large Image & Crop Easier

I want to allow users to upload large photos of their home and crop it to fit properly into a slideshow. So I set it up that when the user uploads their large home photo it will store that and copy it and re-size the new copy to be a more manageable size. (ex. resizing a 5000x3333px image to 600x400px) Then this new image is displayed to the user to allow them to crop that image. After the image has been cropped 4 values are returned: x, y, w, and h. These are the values of the cropped area on the smaller image, but now we want to crop the original image not this smaller one. This means the w & h have to be increased and the x & y got to stay in correct position but this is the part that I'm so confused about. How do I properly scale up the w & h and keep x & y in right place to match the crop from the small image to the original large one?
Here is a code snippet of the final function that crops. This is using some of my homemade function, understand they are just there for convenience.
//User inputs from the crop area on the small image
$user_input_x = $_POST['x'];
$user_input_y = $_POST['y'];
$user_input_w = $_POST['w'];
$user_input_h = $_POST['h'];
//Grab original, small, and final image locations
$original_image_src = '/tmp/original_image';
$small_image_src = '/tmp/small_image';
$final_image_location = '/final/image';
//Return the extension for both the original and small image
if(($image_ext = imageCheck($original_image_src)) === false) die('Could not find original image source!');
$original_image_src .= $image_ext;
$small_image_src .= $image_ext;
$final_image_location .= $image_ext;
//Get the width and height of both the original and small image
list($original_image_width, $original_image_height) = getimagesize($original_image_src);
list($small_image_width, $small_image_height) = getimagesize($small_image_src);
//Converts string location of image into php resource
//This function helps determine the type of image and create the resource
$src_image = createImage($original_image_src);
//This is the area where I am having trouble
//I need to scale up the users input x,y,w,h because they are from small image and need to match to original
//These are the vars to go into all the final fields
$src_x = $user_input_x;
$src_y = $user_input_y;
$src_w = 0;
$src_h = 0;
$crop_x = 0;
$crop_y = 0;
$crop_w = 0;
$crop_h = 0;
$final_image = imagecreatetruecolor($crop_w, $crop_h);
if(!imagecopyresampled($final_image, $src_image, $crop_x, $crop_y, $src_x, $src_y, $crop_w, $crop_h, $src_w, $src_h)) die('Could not resmaple image!');
//Saves image to final location retains the extension and destroys the resource
if(imageSave($final_image, $final_image_location, $image_ext) === false) die('Count not save image!');
Oh and if it help any, this crop is being done by jCrop which is pretty much providing the x, y, w & h.
As far as I understand x and w, and y and h scale at the same ratio.
$crop_y = $original_image_height/$small_image_height*$user_input_y;
$crop_h = $original_image_height/$small_image_height*$user_input_h;
$crop_w = $original_image_width/$small_image_width*$user_input_w;
$crop_x = $original_image_width/$small_image_width*$user_input_x;
I drew this to try and visualise it.
http://i58.tinypic.com/32zm0it.jpg

How to resize an image like facebook cover

What basically I am trying to do is to create a cover page for my personal website, just like facebook. Basically I am after the same layout of the cover as on facebook, so that user can get the same result while using the same cover on my site as well as on facebook.
The part I am stucked at is the "Drag image to position cover" thing.
The Facebook uses some algorithm to convert the cover image size to something different during dragging thing. For example, if the original image dimensions are 920x720, the dimensions of same image while it is on facebook setting-cover page(drag image to position cover thing), the dimensions of the image are 851x638.
I just wanted to know what algorithm facebook uses to set the image dimensions(from 720 to 638)
NOTE: The cover has to be the pixel perfect
I know that the cover dimension of facebook is 851x315, so here is what I am doing:
//$x = X origin cordinate variable obtained by dragging image
//$y = Y origin cordinate variable obtained by dragging image
list($k, $l) = getimagesize($src); // $src == image source
//$w = Needs to be calculated
//$h = Needs to be calculated
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor( 854,316 );
imagecopyresampled($dst_r,$img_r,0,0,$x,$y,$w,$h,$k,$l);
imagejpeg($dst_r,$src,$jpeg_quality);
$img_name = writeToImage($src, $des); //writeToImage() is just a demo function created by me to do some other things with them which do not affect this part of code
echo $img_name;
I need to figure out how facebook calculates the new dimension of the image from previous one. Is it dependent of the actual(original) size of the image or is it dependent on some other factors?
The formulas for scaling images are quite simple.
$aspect_ratio = $original_width / $original_height;
$new_width = $new_height * $aspect_ratio;
or
$new_height = $new_width / $aspect_ratio;

PHP GD2 Images not printing

Recently we launched a in store activation that has you take a photo with a Galaxy Tab 2 and then feeds it to our central server. This is Done with Phonegap. On the server we use PHP and GD2 to generate the images. Everything works on the server and the images are created perfectly, the problem comes when we want to print these photos out with a printer. Currently we are using a HITI Photo Printer, but the same issue occurs on our normal in house printer, on the in house printer it does print the photo but its comes out so small no bigger than 4mm X 2mm on the page.
Below is the code I am using for generating the JPEG on the sever with PHP:
//define image name
$image_name = $this->genUID() .'.jpg';
//get image attributes
list($curWidth, $curHeight, $type, $attr) = getimagesize($files['my_picture']['tmp_name']);
//create image in today's directory
$nI = imagecreatefromjpeg($files['my_picture']['tmp_name']);
$nP = imagecreatetruecolor($this->minimum_image_width, $this->minimum_image_height);
$widthResizeRatio = ($this->minimum_image_width / $curWidth);
$newWidth = $this->minimum_image_width;
$newHeight = round(($curHeight * $widthResizeRatio),0);
$offsetX = 0;
$offsetY = 180;
imagecopyresampled($nP, $nI, 0, 0, $offsetX, $offsetY, $newWidth, $newHeight, $curWidth, $curHeight);
imageinterlace($nP, true);
imagejpeg($nP, $this->image_directory .'/'. $this->curDate .'/'. $image_name, 100);
imagedestroy($nI);
imagedestroy($nP);
Your help will be greatly appreciated.
You said all the images on the server are created perfectly...I would test this claim more carefully. If it is indeed true, the issue lies with how you send the images to your printer or how the printer handles the images once it receives them. In either situation I don't think you are going to get much help here.....I could be wrong. GL.

How to maintain image quality with FPDF and PHP?

I'm using FPDF with PHP to add an image to a PDF. But the image quality in the PDF is much worse than the original image, as you can see here:
Relevant code:
$image_height = 40;
$image_width = 40;
$pdf = new FPDF();
$pdf->AddPage();
$start_x = $pdf->GetX();
$start_y = $pdf->GetY();
$pdf->Image('./images/ds_pexeso_ros_0_17.jpg', $pdf->GetX(), $pdf->GetY(), $image_height, $image_width);
$pdf->Output("pexeso".date("Y-m-d"),"I");
The original image is 150x150 pixels.
I faced the same problem in projects for customers.
Blurry pictures in a generated pdf document even with hires images.
It took me a couple of hours, but this is what worked for me.
I have a taken a look at the code and saw that there was a scale factor being set in the constructor of the pdf document:
//Scale factor
if($unit=='pt')
$this->k=1;
elseif($unit=='mm')
$this->k=72/25.4;
elseif($unit=='cm')
$this->k=72/2.54;
elseif($unit=='in')
$this->k=72;
else
$this->Error('Incorrect unit: '.$unit);
The scalefactor is depending on the value given in the constructor of the pdf document:
function FPDF($orientation='P',$unit='mm',$format='A4')
The default is 'mm'. In most of my documents I initiate a pdf document like:
$pdf = new PDF('P');
This means that there will be a scalefactor of 72/25.4 = 2.83 used.
When I placed an image before I just used:
$this->Image('path/to/file', 0, 0);
This way I got the blurry images.
It is also possible to give the width of the image in the command
$this->Image('path/to/file', 0, 0, 200); // for a image width 200
This gave me an image that was far too large. But - and here comes the trick - when you divide the real width by the scalefactor (in my case 2.83) and put this in this statement it gives a perfectly sharp image:
$this->Image('path/to/file', 0, 0, 71); // for a image width 200 / 2.83 = app 71
I hope this works for you too!
I think the problem could be related to:
$image_height = 40;
$image_width = 40;
With these two instructions your are setting the dimensions the image will have in the pdf.
But if the original image is bigger than 40x40 the scaling of the image can cause quality problem.
So what i suggest:
Do a correct resize of the image (php provides GD library). Resize it to 40x40. The GD function imagecopyresampled is your friend: resize and resample the image! Complete reference: http://www.php.net/manual/en/function.imagecopyresampled.php
Insert now the image in the pdf
FPDF with a statement like this to set the user unit to mm
$pdf=new FPDF('P','mm','Letter');
<?php
require_once('fpdf.php');
$image_height = 40;
$image_width = 40;
$pdf = new FPDF('P','mm','Letter');
$pdf->AddPage();
$start_x = $pdf->GetX();
$start_y = $pdf->GetY();
$pdf->Image('./images/ds_pexeso_ros_0_17.jpg',$start_x+0,$start_y-2,40);
$pdf->Output("pexeso".date("Y-m-d"),"I");
?>
FPDF made a very good looking result.

How to crop and image before adding an overlay? (GD) (PHP)

My code so far (it creates an overlay to a youtube thumbnail):
<?php
header("Content-type:image/png");
$background=imagecreatefromjpeg("http://img.youtube.com/vi/".$_GET['v']."/default.jpg");
$insert=imagecreatefrompng("play.png");
imagecolortransparent($insert,imagecolorat($insert,0,0));
$insert_x=imagesx($insert);
$insert_y=imagesy($insert);
imagecopymerge($background,$insert,5,57,0,0,$insert_x,$insert_y,100);
imagepng($background,NULL);
The output image is 120x90px, but i need it to have 90x90px.
Anyone knows how this is possible?
Thanks in advance!
http://www.johnconde.net/blog/cropping-an-image-with-php-and-the-gd-library/
<?php
header("Content-type:image/png");
$background = imagecreatefromjpeg("http://img.youtube.com/vi/".$_GET['v']."/default.jpg");
$insert = imagecreatefrompng("play.png");
imagecolortransparent($insert,imagecolorat($insert,0,0));
list($current_width, $current_height) = getimagesize($background);
$left = 0;
$top = 0;
$crop_width = 90;
$crop_height = 90;
$canvas = imagecreatetruecolor($crop_width, $crop_height);
$current_image = $background;
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
imagecopymerge($canvas,$insert,5,57,0,0,$current_width,$current_height,100);
imagepng($canvas);
?>
try that it should work if not comment as to otherwise.
This is taken from a function I wrote to create square thumbnails. You may find the commentary I wrote for myself helpful. Depending on your needs (i.e if you can't afford to make assumptions about the type and dimensions of incoming images) you may need to add additional checks. To avoid smashed or stretched thumbnails we take a central part of the image which is most likely to contain something distinguishable as source co-ordinates.
The basic idea is: Since imagecopyresampled or imagecopyresized also allow you to specify destination and source coordinates, you can copy only part of your original image to a new canvas and save that (or directly output to browser). To avoid smashed or stretched dimensions we take a central part of the original image which is most likely to contain distinguishable content.
//assuming you have already merged your $background image with your overlay at this point
//original dimensions
$original_width = imagesx($background);
$original_height = imagesy($background);
//new dimensions
$new_width = 90;
$new_height = 90;
//the center of the rectangular image
$center = $original_width/2, $original_height/2
//the coordinates from where to start on the original image
//assuming you want to crop the center part
$src_x = floor(($original_width/2) - ($new_width/2));
$src_y = floor(($original_height/2) - ($new_height/2));
//create a new canvas with the new desired width, height
$temp = imagecreatetruecolor(90,90);
//copy the large image to this new canvas
imagecopyresampled($temp,$background,0,0,$src_x,$src_y,$new_width,$new_height,$original_width,$original_height);
//from right to left: source image, destination image, dest x, dest y,
//source x, source y, new width, new height, original width, original height
//save the canvas as an image
imagepng($temp);
This could be improved to handle larger images by first taking a central part relative to it's size and then scaling it down to the new canvas.

Categories