Aristona Aristona - 2 years ago 115
PHP Question

Can I inject posted image files into PDF using dompdf?

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.

Answer Source

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.

// 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'] ) ); ?>">
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download