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

Does this extensive combination of pseudo classes hold true?

Here's the code snippet I am working with: .fontmenu .fontlist{ position: absolute; bottom:30px; display:none; } .fontbutton button:hover .fontmenu .fontlist{ display:block; } <div class="fontmenu"> ...

Tips for incorporating transitions into CSS styling

After successfully adding a picture over an element when hovering over it, I decided to include a transition: 0.2s; property but unfortunately the transition effect is not working as expected. Why is this happening? My intention is for the picture to smoot ...

No modifications to the CSS can be made within the "alterations" section of the Console drawer in Chrome

Is there a way to easily track and summarize all of my live CSS changes in the Chrome browser? I've searched on Stack Overflow, but haven't found a solution that works for me. This specific answer seems like it could be the most helpful for achie ...

Validating the similarity of classes with JQuery

Currently, I am working on creating a quiz game using HTML, CSS, JQuery, and potentially JavaScript. I am looking to implement an if statement to check if a dropped element is placed in the correct div (city). My approach involves utilizing classes to comp ...

What causes certain components in ReactJs to not respond to the `:focus` pseudo-class?

Currently, I am in the process of implementing a straightforward Emoji-Rating system where 5 emojis are displayed on the screen and upon hovering over them, their appearance changes. This functionality is achieved using the :hover pseudo-class. My goal is ...

Changing the selection in the Angular Mat-Select dropdown causes the dropdown's position to shift

Issue with dropdown position: The dropdown should display below the select element, but when selecting the second value, it appears on top of the select element. I have removed any relevant CSS to troubleshoot, but the problem persists. See screenshots for ...

What is the most effective way to implement a CSS stylesheet on a particular individual element?

Just starting out in web development and I recently experimented with a CSS stylesheet on a basic HTML element. It worked great when I targeted the element by name like this: label { color: green; } However, I wondered if there was a way to apply sty ...

Utilizing margins in CSS for various div elements

Update: I have included Javascript and Masonry tags in my project. Despite having modules of the same size, I am exploring how masonry can assist me. However, I find it a bit puzzling at the moment as I am not aiming to align elements of different sizes. I ...

Enhancing user experience with dynamically resized Jumbotron images based on screen sizes in HTML

I am experiencing an issue with the jumbotron images on my website where they become increasingly zoomed in as the screen size decreases, and are extremely zoomed in on mobile devices. Is this a normal behavior of jumbotrons? I do understand that the image ...

Why is the file_exists method not functioning properly in CodeIgniter?

New Code: <?php $imagePath = FCPATH.'resources/img/college_logo/'.trim($fetch['college_name']).'.jpg'; if (file_exists($imagePath)) { ?> <img src="<?php echo $imagePath; ?>"> <?php ...

The slideshow fails to show correctly after being loaded from an external JavaScript file

Utilizing standard code, I have set up a Slideshow at the top of a website: HTML: <body id="Top" onload="showSlides()"> ... <div id="slides"> <div id="slide1" class="slides fade"></div> <div id="s ...

The copyright (©) symbol is unresponsive to rotation

Why can't I rotate the © character? Am I missing something? .copy { font-size: 12px; font-family: Arial; writing-mode: vertical-rl; text-orientation: mixed; transform: rotate(180deg); } <span class="copy">&copy; This is not ...

Using codeigniter for input validation within the model code

How can I validate input from the database if the current input is less than the value in the database? The View <?php echo form_open('order/confirm');?> <div class="input-control text"> <input type="text" name="paid_v ...

The text should be wrapped to overlap with an image positioned above it

Currently, I am in the process of enhancing a webpage that contains a significant amount of old legacy code. One issue I have encountered pertains to text wrapping within a fixed-height and width container, as illustrated in the image below: The first ima ...

Hide the border below the active tab

Could anyone assist me in removing the border below the selected tab? I've attempted multiple approaches without success. I experimented with adding a negative margin to the tab and creating a white border, but as the border I want to conceal is from ...

What is the best way to ensure that the input search bar, microphone icon, and two small boxes adapt to different screen

Upon submitting my exercise for The Odin Project, I was under the impression that everything looked perfectly aligned and centered on my MacBook Pro 15-inch screen. However, when I viewed the completed webpage on a larger computer screen at work, I noticed ...

What is the best way to vertically align an InputLabel within a MUI Grid item?

I'm trying to vertically center the InputLabel inside a MUI Grid item. Here's what I've attempted: import { FormControl, Grid, Input, InputLabel, TextField } from "@mui/material"; export default function App() ...

Resolving a CSS Layout Dilemma: How to Overlay Sidebar on Wrappers

I've run into a challenge while attempting to position a sidebar over page wrappers. The issue with absolute positioning arises when the sidebar needs to align with the corner of the blue header. I have contemplated using JavaScript to maintain its cu ...

The Bootstrap Tooltip seems to be glued in place

Utilizing jQuery, I am dynamically generating a div that includes add and close buttons. Bootstrap tooltips are applied to these buttons for additional functionality. However, a problem arises where the tooltip for the first add button remains visible even ...

Updating text color in JavaFX for a textarea

I'm having trouble getting this to work. After checking the CSS analyzer in the scene builder, it seems that changing the text color in a textarea requires something like this: .text-area .text { -fx-fill: #1e88e5; -fx-font-size: 32px; } How ...