Can I inject posted image files into PDF using dompdf? - php

I have a form where users can fill input boxes. In some cases, they're allowed to select images too.
The problem is, I don't want to save the image file somewhere on our server and give PDF the URL like this:
//Put uploaded file on public/uploads/ folder
<img src="{{ $imagePath }}" style="height: 50px; width: 50px;">
Instead, I'd like to inject uploaded image directly into PDF file. Something like this:
PDF::load($data, 'A4', 'portrait')->inject('image', Input::file('resim'))->output();
//So I can reference it as {{ $image }} on PDF template, but image will be injected into PDF file
I'm beginner on PDF files and I'm not even sure if this is possible.
If it's possible, can anyone give me some advices?
Ps. I use DOMPDF package for Laravel 4. https://github.com/thujohn/pdf-l4

You will need to be able to reference the image somehow in your document. There are a few ways you could do this.
Access the temporary file from the uploads.
In your HTML file just reference the temporary file created by the upload as your image source, e.g.
<img src="<?php echo $_FILES['userfile']['tmp_name']; ?>">
Capture the content of the image and write it into the HTML as a data-uri value
dompdf understands data-uris and so you could take the uploaded file, convert it to a data-uri, and insert that into your HTML.
You do have to detect the image format, which can require a bit more work depending on your version of PHP. With v5.3+ you can use the finfo_file method. If that extension isn't available you can perform some basic content-type detection by parsing the file extension.
In my example I'm just specifying PNG as the image type.
<?php
// detect mime type, but I'm forcing PNG
$mime = 'image/png';
?>
<img src="<?php echo 'data:' , $mime , ';base64,' , base64_encode( file_get_contents( $_FILES['userfile']['tmp_name'] ) ); ?>">

I have this in my HTML...
<body>
<img src="{{ URL::asset('img/my-image.png') }}" />
my route where i have my img
and this in my controller
public function getPdf($id){
$html = View::make("backend.PDF.batch")->with('batchs',$batchs)->with('ad',$ad)->render();
return PDF::load($html, 'A4', 'portrait')->show();
}
and in the view don't show me the img they say
DOMPDF_ENABLE_REMOTE is set to FALSE

Related

How do I set data:image/ filetype dynamically?

I have a database which contains images saved as BLOBs. I can successfully use the image on a page like so :
<img src="<?php echo 'data:image/jpeg;base64,'.base64_encode($image)?>" alt="Landing" width="150px">
However this requires setting the file extension manually in the actual statement at data:image/jpeg;. The problem is that I have lots of various images in various formats. I want to make sure that the filetype is set properly based on the actual file extension of the specific file for each image. I already have a nested array which contains all the file extensions for those files.
Nonetheless I am having trouble setting the extension dynamically. I've tried simply replacing the '' single quotes with "" to allow me to easily use a variable inside of the statement like so :
<img src="<?php echo "data:image/$images['monitor']['extension'];base64,".base64_encode($image)?>" alt="Landing" width="150px">
This doesn't work because the src tag itself contains double-quotes already I believe. My IDE tells me an error Cannot use '[]' for reading. I've also tried using concatinated single quotes instead :
<img src="<?php echo 'data:image/' . $images['monitor']['extension'] . ';base64,'.base64_encode($image)?>" alt="Monitor" width="150px">
Which also did not work. I was unable to find any solution to this online myself. Is there any way to dynamically set the file extension? Although setting jpeg for each image mostly works for instance doing so for the image/x-ico tab icon renders the image unable to load properly.
Assuming that the BLOB contains the actual binary data of the image.
Just make sure that the extensions match with the required syntax
jpg file : <img src="data:image/jpeg;base64,[base64_encoded_data]
png file : <img src="data:image/png;base64,[base64_encoded_data]
ico file : <img src="data:image/icon;base64,[base64_encoded_data]
So a sample example is like the following:
<?php
$image=file_get_contents("http://www.createchhk.com/SO/sample1.png");
$file_ext = 'png';
?>
Test for PNG<br>
<img src="data:image/<?php echo $file_ext; ?>;base64,<?php echo base64_encode($image)?>" alt="Landing" width="50px"><br>
<?php
$image2=file_get_contents("http://www.createchhk.com/SO/sample1.jpg");
$file_ext2 = 'jpeg';
?>
Test for JPG<br>
<img src="data:image/<?php echo $file_ext2; ?>;base64,<?php echo base64_encode($image2)?>" alt="Landing2" width="50px"><br>
<?php
$image3=file_get_contents("http://www.createchhk.com/SO/sample1.ico");
$file_ext3 = 'icon';
?>
Test for JPG<br>
<img src="data:image/<?php echo $file_ext3; ?>;base64,<?php echo base64_encode($image3)?>" alt="Landing3" width="50px"><br>
The result can be seen here:
http://www.createchhk.com/SO/testSO_18Nov2021.php

DOMPDF with laravel - cannot load images in html file

I'm trying to generate pdf file with laravel and dompdf lib. Here is my code from controller:
public function create(Request $request) {
$pdf = new Dompdf();
$html = Storage::disk('local')->get('public/pdf/template.html');
$pdf->loadHtml($html, 'UTF-8');
$pdf->setPaper('A4', 'portrait');
$pdf->render();
$filename = "Hi!";
return $pdf->stream($filename, ["Attachment" => false]);
}
And in template.html I got some html, somewhere there I got images like this:
<img src="img/logo.png" alt="BTS">
But dompdf cant write this image: Image not found or type unknown. My file system is:
.pdf
...img
......here is images
...template.html
...*some_fonts_files*
But at the same time, fonts are loading fine. What should I do to render images in template.html?
I believe that for dompdf you need to pass a properly accessable url rather than relative paths.
Try
<img src="{{ asset('img/logo.png')}}" alt="BTS">
Alternatively if asset doesn't work please try
<img src="{{ public_path('img/logo.png')}}" alt="BTS">
Also please note that asset uses the public directory as the base_url to calculate the 'asset' from.
Me too i struggled for the same error for 3 days. Also when i tried tricks mentioned above, none of them worked too. But when i changed the image file to .jpg file(extension) everything worked well.
<img src="{{ public_path('img/logo.jpg') }}" >
Laravel version: 5.8.38
PHP version: 7.3
barryvdh/laravel-dompdf version: 0.8.6
You can just print the image path as the src attribute of the <img> tag.
Suppose you have the path to the location of your image in a variable:
$img = asset($imgen);
Yust echo it out like this:
<img src="#php echo $img #endphp">
There seems to be a need to set the protocol and add an additional option:
$pdf->setOptions(['isRemoteEnabled' => true]);
$pdf->getDomPDF()->setProtocol($_SERVER['DOCUMENT_ROOT'])
Or:
$pdf->setProtocol($_SERVER['DOCUMENT_ROOT']);
After this src="/storage/myimage.png" will work.
I tried all tips!! The only one solution that works for me is:
header {
background-image: url("https://example.org/logo.jpg");
}
and
$pdf->setOptions(['isRemoteEnabled' => true]);
$pdf->getDomPDF()->setProtocol($_SERVER['DOCUMENT_ROOT'])

How to display most used file (pdf, doc, docx, xls, …) into a browser by using PHP?

I need to display a (pdf,doc,docx,txt) documents inside an php web form with the ability to select a part of the document content and do some processing on it in the right click (like saving the selected content to DB)?
I try this way :-
<iframe src="http://docs.google.com/viewer?url=<?=urlencode($docx)?>&embedded=true" width="600" height="780" style="border: none;"></iframe>
But is show me as html
PHP can set the header information for a file and so you can display anything as file.php, loading the file.php you can then specify what it should be handled as- for example you can generate an image and output it as a jpeg file :
header('Content-Type: image/jpeg');
$img = LoadJpeg('bogus.image');
imagejpeg($img);
imagedestroy($img);
from http://php.net/manual/en/function.imagecreatefromjpeg.php example.
Using a similar method for setting the header content-type you can output PDF contents or DOC or whatever, by setting the header to the correct file type and loading the contents of the file with PHPs file_get_contents() ( http://php.net/manual/en/function.file-get-contents.php ) function, and outputting that to the browser / iframe.
Two things you can do:
Just link to the .pdf/etc. location on your server
Save the image of it as a .jpg and display that then put a link to download the pdf/whatever

Image is not shown in PDF file using dompdf

I am using DOMPDF to convert the html into PDF and after converting I'm sending that PDF file to user mail id.
Everything is working perfectly but in PDF file I am not able to see the image of logo of my site. I also searched in stackoverflow for previous question such as :- error in pdf image using dompdf ,
dompdf and img tag, image wont show
I also set DOMPDF_ENABLE_REMOTE to TRUE and DOMPDF_PDF_BACKEND to CPDF
my image tag is :-
<img src="http://www.example.com/clients/myprojects/images/logo.png" alt="" /></a>
I'm giving full path of my website but still it does not show image in my PDF file.
Thanks in advance.
use full directory path with .jpg image
It works for me.
<img src="<?php echo $_SERVER["DOCUMENT_ROOT"].'/placeholder.jpg';?>"/>
<img src="<?php echo $_SERVER["DOCUMENT_ROOT"].'\placeholder.jpg';?>"/>
<img src="<?php echo $_SERVER["DOCUMENT_ROOT"].'./placeholder.jpg';?>"/>
Don't put full path of URL, just put foldername/filename.jpg
Example:
<img src="uploads/kuruvi.jpg">
I my case i spend 2 hour finally i got answer
img src not working with url or path you should covert it base64 format
<?php
$data = file_get_contents('https://teafloor.com/wp-content/themes/teafloor2-0/assets/images/logo.png');
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
?>
<?php echo '<div class="company-logo">
<img src="'.$base64.'" alt="base" />
</div>';
?>
or
<img src="<?php echo $base64; ?>" alt="base" />
if I recall it correctly you can put there a full system path to that image - absolute or relative to your script
Remove the alt attribute and changing it from a self-closing tag (/>) to a normal one (>). It worked for me.
Note: dompdf seems to have a bad response to any inline styles on img tags, so I suggest removing them if you´re using any.
//use full directory path something like this
$currentsite = getcwd();
$html = <<<HTML
<html>
<img src="{$currentsite}/sites/all/modules/certificate_handler/image002.png" alt="" /></a>
</html>
HTML;
I did this:
$imgurl = $graficas[$i];
$path_parts = pathinfo($imgurl);
$graficas[$i] = $path_parts['filename'].".jpg";
And works. I hope this would help you too
DOMPDF
working now with png,jpg.
here what I used.
I have index.php file in route folder and image in subfolder namely images.
$image ="images/".$_FILES['image_index_name']['name'];
$htm= '';
You just have to change the line def("DOMPDF_ENABLE_REMOTE", FALSE); to true in the file DOMPDF_CONFIG.INC
Now latest DOMPDF version another, but have the same problem on PHP v5.3
Upgrade to v5.4 or higher
The problem has solved.
I think you could add this
private function change_url_image($data,$url){
$str=$url; //for example "http://localhost/yoursite/";
$str2=str_replace($str,"",$data);
return $str2;
}
to change url for image it's very simple

Outputting raw image stream rather than jpeg, on-the-fly image resizing

I have a PHP function that does on-the-fly image resizing for thumbnail creation.
I am having trouble as it's just displaying raw image stream instead of the actual image.
My code is using a function called thumbnail:
$thumbnail = thumbnail($item['filename'], 209, 137);
imagejpeg($thumbnail);
I've tried putting in:
header("Content-type: image/jpeg");
However, this just expects the full page to be an image. I have absolutely no idea where to go from here, been working at it for a while. I'd rather not save the image to disk although it's looking like this might be necessary.
You either
Do it the normal way
This mean you point at one url, and serve the contents of one image:
<img src="myimage.php">
and myimage.php is a script that looks like:
header('Content-type: image/jpeg');
imagejpeg($thumbnail);
die;
This technique has the advantage of being.. the normal way of doing things.
OR
Output the image inline
Using data uris outputting the contents as a base64 encoded string
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">
This technique is most appropriate with small images.
It has the advantage of meaning all the images are in the main http request - at the (possibly sizable) disadvantage of making the page harder to edit/build and possibly negating the benefits of browser caching (unless the html page is itself cached).
Being normal is easier
Regarding this statement in the question:
However, this just expects the full page to be an image
That's right - if you do it the normal way you want to point at your php script with the src attribute of an image tag, and server only an image - i.e. the exact same response as if you were pointing at an image file with a browser.
Unless you have a good reason to do things a different way - the "normal" way is a good place to start.
You can point an html img tag to an php file.
<img src='thumbnail.php?file=<?php echo $item['filename']; ?>' />
Then on your php file you display the image and change the headers since all it is doing is displaying an image.
$thumbnail = thumbnail($_GET['filename'], 209, 137);
imagejpeg($thumbnail);
header("Content-type: image/jpeg");
You need to insert the image like you would a normal image in HTML and create the image in a separate PHP file:
image.php
<?php
$img = imagecreate(100,100); //Create an image 100px x 100px
imagecolorallocate($img, 255,0,0); //Fill the image red
header('Content-type: image/jpeg'); //Set the content type to image/jpg
imagejpeg($img); //Output the iamge
imagedestroy($img); //Destroy the image
?>
myWebpage.html
<img src="image.php" />

Categories