How to Open PDF File in Another Tab Using CodeIgniter

Last updated 6 days, 12 hours ago | 19 views 75     5

Tags:- PHP CodeIgniter

Opening a PDF file in a new browser tab can enhance user experience, especially when dealing with reports or documentation. CodeIgniter, a popular PHP framework, makes this process straightforward. Here's a step-by-step guide to help you achieve this.

Prerequisites

  • CodeIgniter installed and configured.

  • A PDF file to display.

Step-by-Step Guide

  1. Set Up Your Controller

Create a new controller or use an existing one. For instance, PdfController.php:

class PdfController extends CI_Controller {

    public function view_pdf() {
        $file_path = 'path/to/your/file.pdf';
        if (file_exists($file_path)) {
            header('Content-Type: application/pdf');
            header('Content-Disposition: inline; filename="file.pdf"');
            readfile($file_path);
        } else {
            show_404();
        }
    }
}
  1. Configure Routes

In the routes.php file, add a route for accessing the PDF:

$route['view-pdf'] = 'PdfController/view_pdf';
  1. Create a Link to Open the PDF in a New Tab

In your view file, such as pdf_view.php, create an anchor tag with the target="_blank" attribute:

<a href="<?php echo base_url('view-pdf'); ?>" target="_blank">Open PDF</a>
  1. Verify the Result

Access the link in your browser. The PDF file should open in a new tab.

Conclusion

By following these steps, you can seamlessly open PDF files in a new browser tab using CodeIgniter. This approach enhances user experience and allows for easy viewing and downloading of PDF documents.