Having trouble with Image and Css not displaying correctly when using CodeIgniter 3 with DomPDF?

I'm currently utilizing CodeIgniter 3 and dompdf to convert an HTML view into a PDF. While I am able to successfully convert the HTML to PDF, the proper styling is not being applied. All necessary CSS files have been included as custom design in the view file.

What else do I need to do to properly include the CSS styles and images?

Here is the controller:

public function get_pdf_test($id)
  {
    //  print_r($_REQUEST);
    //   die;
      $data['incidents'] = $this->incidents_model->getById($id);
      $data['incidents_history'] = $this->incidents_model->getById_history($id); 
      $data['company_name'] = $this->incidents_model->getAllCompanyName();
     
      generate_pdf("admin/incidents/incidentsView.pdf", "admin/incidents/incidentsView.php", $data);
    
      }

incident_model.php

     function getById($id) 
    {
  
       return $this->db->get_where('incidents',array('id'=>$id))->row();
    }
 function getById_history($id)
    {
        $query=$this->db->query("SELECT incidents_id FROM incidents WHERE id = $id");
        $get_row = $query->row();
        $incident_id = $get_row->incidents_id;
        
        $this->db->select('*');
        $this->db->where(array('incidents.incidents_id'=>$incident_id));
        $this->db->join('incident_status', 'incidents.id = incident_status.incident_id');
        return $this->db->get('incidents')->result(); 
    } 
function getAllCompanyName()
    {
      $query = $this->db->get('company_details');
      $query = $this->db->query('SELECT company_name FROM company_details where delete_flag =0');
      return $query->result();
    }

Pdf.php file in library:

 <?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 *
 * Convert HTML to PDF in CodeIgniter applications.
 *
 * @package            CodeIgniter
 * @subpackage        Libraries
 * @category        Libraries
 * @author            Hostmystory
 * @link            https://www.hostmystory.com
 */

// Dompdf namespace
use Dompdf\Dompdf;

class Pdf
{
    public function __construct(){   
        // require_once autoloader 
        require_once dirname(__FILE__).'/dompdf/autoload.inc.php';
        $pdf = new DOMPDF();
        $CI =& get_instance();
        $CI->dompdf = $pdf;

    }
}
?>

new_helper.php in helper:

<?php defined('BASEPATH') OR exit('No direct script access allowed');
// generate pdf
function generate_pdf($name, $tpl, $data)
{
    $ci = &get_instance();
    $data['data'] = $data;
    $ci->load->view($tpl, $data);
    // Get output html
    $html = $ci->output->get_output();
// add external css library
    $html .= '<link href="' . base_url() . 'assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">';

    // Load pdf library
    $ci->load->library('pdf');
    $ci->dompdf->loadHtml($html);
    // setup size
    $ci->dompdf->setPaper('A4', 'portrait');
    // Render the HTML as PDF
    $ci->dompdf->render();
    // Output PDF (1 = download and 0 = preview)
    $ci->dompdf->stream($name, array("Attachment" => 0));
}
?>

here is the output of dompdf :

https://i.stack.imgur.com/ZmPZD.png

Answer №1

to address your inquiry

Issue with Image and Css not functioning in Codeigniter 3 dompdf

Following your lead, I decided to install CI 3.11.1 along with Dompdf 1.0.2 which led me to two solutions

Solution 1 - adjusting dompdf options:

When loading dompdf in your library, make sure to set the enable_remote option to true:

$pdf = new Dompdf(array('enable_remote' => true));

Image

To ensure images display correctly in your HTML, utilize base_url() to create an absolute path for the image, for example:

<img src="<?=base_url('assets/_img/logo.png')?>" />

CSS

Your approach should now work seamlessly.


Solution 2 - embedding:

Image: An alternative method to showcase images is by embedding them using the data URI scheme
and base64_encode():

To do this, you need to specify the absolute/path/to/your_image, easily achievable in CI through the base_url() function

$imgpath=base_url('assets/_img/logo.png');
$ext= pathinfo($imgpath, PATHINFO_EXTENSION);
$data = file_get_contents($imgpath);
$base64 = 'data:image/' . $ext. ';base64,' . base64_encode($data);

Stylesheet: To incorporate a CSS stylesheet, embed it within a <style></style> element, using an absolute path:

$path = base_url('assets/_css/dompdf.css');
$data = file_get_contents($path);
//$css = '<link type="text/css" href="'.$data.'" rel="stylesheet" />';  // couldn’t get this to work
$css="<style>$data</style>";

This is the stylesheet I implemented:

@charset "utf-8";
/* CSS Document */

.red{
    color:red; 
    width:100%; 
    margin-bottom:50px;
    font-family: sans-serif; 
    font-size:48px;
}
img{
    width:300px; 
    height:300px;
    margin-bottom:10px;
}

Hence, a potential HTML structure could resemble the following:

$html='<div class="red">Hello world!</div><img src="'.$base64.'"/><div>unformatted text</div>';

To generate the PDF, load the library and pass $css and $html for compilation:

$this->load->library('pdf');
$this->dompdf->loadHtml($css.$html);
$this->dompdf->setPaper('A4', 'landscape');
$this->dompdf->render();
$this->dompdf->stream("welcome.pdf", array("Attachment"=>0));

Potential Output:

https://i.stack.imgur.com/MUpJ9.jpg

Please note: Dompdf 1.0.1 primarily adheres to css2 standards (with some minor css3 exceptions), refer to: Dompdf Features

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm wondering why my element is aligning itself with its sibling. It seems that when the parent has overflow set to hidden, it causes the children's

Let me break down the diagram below for you: The main box is marked in yellow and serves as the parent element. Within this parent box, there are two child elements, one in black and one in cyan. To hide any excess content of the cyan box that overfl ...

Upgrade button-group to dropdown on small screens using Bootstrap 4

I am currently developing a web application and incorporating Bootstrap 4 for certain components such as forms and tables. Within the design, I have included buttons grouped together to display various actions. Below is an example code snippet: <li ...

Tips for ensuring that content doesn't shift down when clicking a drop-down menu

I currently have three dropdowns that function as an accordion. When I click on one dropdown, the rest of the content below shifts down, which is not the behavior I want. Is there a way to prevent the content below each dropdown from moving when a dropdow ...

Issue with CSS 3 gradient compatibility in Internet Explorer 8

My CSS3 gradient button is working perfectly on all browsers except for IE8. To make it work on IE8, I am utilizing CSS3 Pie. You can see the search button in action by visiting: Upon inspecting my console, I noticed an error on this line: PIE.htc, lin ...

Is it possible to create a fading effect on an image using a border-radius of 50%?

Struggling with fading out an image that's circular in shape due to the border-radius: 50%. <section id="main"> <h1>Non-Important-Text</h1> <h4> it's all fun and games until you can't find a damn sol ...

Styling the scrollbar for the PDF element on an HTML page

I have a div that contains an object "linked" to a .pdf file. Is it possible to customize the scrollbar style using CSS or JavaScript/jQuery? <div id="container"> <object data="document.pdf" type="application/pdf" ...

Adjust the height of the outer div automatically

Currently, I am attempting to dynamically set the height of div#container so that it adjusts based on its relative positioning and the absolute positioning of inner divs. Essentially, I want the inner divs to be centered within the container. <div id=" ...

The Challenge of a Chess Board that Adjusts to Different

Looking at the demonstration below, it's clear that the chessboard adjusts properly to a width of no more than 512px while adapting to different devices. The pieces also resize accordingly with the board. However, I'm encountering an issue when a ...

JavaScript: Selecting parent elements using getElementsByClassName

I am dealing with the following HTML code: <div class="item"> <img class="item-image" src="${item.getImage()}"/> <p>${item.getName()}</p> </div> and JavaScript: var classname = document.getElementsByClassName("item" ...

The left and right arrows maintain their visibility even when they are outside of the image

I am a beginner in the world of web development and I am trying to implement left and right navigation for images using arrows. My goal is to have the arrows fade in when the mouse hovers over the image and fade out when it's moved away. However, I am ...

CSS Flexbox - Choose all elements that appear at the start of a new line (Wrap)

Is there a CSS selector that can prevent content insertion on new lines when using the wrap feature in CSS-Flexbox? I am utilizing CSS-Flexbox for a layout with the wrap option, but I do not know the number of lines beforehand. I need a solution where the ...

Tips for showcasing MySQL JSON data

There is a table in my database called purchase, where I insert data in JSON format. The JSON format contains multiple sets of data, for example, "products" has 2 items. https://i.stack.imgur.com/NJ5qz.png [{"products":["Asulak Silver 7","Print Gum MAP N ...

Spacing between table cells is only applied to the first row and footer

In an attempt to add spacing between the first row, second row, and footer of a table, I have experimented with cell spacing combined with border-collapse. However, the spacing is being applied all over the table instead of in specific areas. I am utilizin ...

The left side of the page is anchored with text content while an engaging carousel occupies the right half

Looking to create a section on the website that remains fixed while a carousel scrolls vertically. Once you reach the final slide, scrolling will continue on the page rather than changing the carousel slide. Want it to function similarly to the Creative s ...

Expanding the padding within a box results in an increase in the overall height of the table row that encapsulates it

My goal is to create a table displaying marks with a box around each mark that expands slightly when hovered over to indicate activity. Below is the code I am using: .container { position: absolute; width: 80%; left: 50%; transform: translateX(-5 ...

Tips and tricks for implementing vuetify tooltips within a list component

Looking for help with my code: <div id='app'> <v-app> <v-list-tile-content> <v-list-tile v-for="(item, index) in items" :key="item.id" > <v-list-tile-action> {{index+1}}. </v-list-tile-action> < ...

Plupload - Resize image upon upload with minimum height and width requirements, rather than maximum requirements

I am currently using a Plupload uploader that creates both a thumbnail and a large size image for each upload. The issue I am facing is with resizing the thumbnail to fit into a 150x150px box. I have tried using some javascript to scale down the image, but ...

In order to enhance user experience, I would like the tabs of the dropdown in the below example to be activated by

function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } ...

A guide on restricting overflow in React Spring Parallax 'pages'

Currently, I have integrated React Spring Parallax () into my project found at this link: https://codesandbox.io/s/parallax-sticky-scroll-2zd58?file=/src/App.js Upon clicking the button to navigate to the next section, it is noticeable that the image over ...

Centering text using CSS Bootstrap

Hey everyone, I've been attempting to center my text using Bootstrap, but for some reason it's not working. Can someone help me figure out what's going on? <footer class="row p-1 mt-3 bg-primary text-white"> <p class= ...