Tuesday, 28 May 2024

Laravel Export data to csv

 use Illuminate\Http\Response;


// Define a function to export data to CSV

function exportToCSV($exportData, $columns)

{

    $filename = "ReportsForm.csv";


    // Set HTTP headers

    $headers = [

        'Content-type' => 'text/csv',

        'Content-Disposition' => "attachment; filename=$filename",

        'Pragma' => 'no-cache',

        'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',

        'Expires' => '0',

    ];


    // Create a callback function to stream CSV data

    $callback = function () use ($exportData, $columns) {

        $file = fopen('php://output', 'w');

        fputcsv($file, $columns);

        $i = 1;

        foreach ($exportData as $item) {

            $currentData = [

                $i++,

                $item->name,

                $item->email,

                $item->company,

                $item->country,

                $item->hear_from,

                $item->is_subscribed == 0 ? "YES" : "NO",

                $item->created_at,

            ];

            fputcsv($file, $currentData);

        }

        fclose($file);

    };


    // Return a streamed response

    return response()->stream($callback, Response::HTTP_OK, $headers);

}


// Controller method to handle export

public function exportData($id = null)

{

    try {

        if (empty($id)) {

            $exportData = ReportForm::all();

        } else {

            $exportData = ReportForm::whereIn('id', $id)->get();

        }


        // Define columns for CSV

        $columns = ["Index", "Name", "Email", "Company", "Country", "Hear From", "Subscribed", "Date"];


        // Export data to CSV

        return exportToCSV($exportData, $columns);

    } catch (\Exception $e) {

        // Handle exceptions

        return response()->json(['error' => 'Failed to export data.'], Response::HTTP_INTERNAL_SERVER_ERROR);

    }

}


laravel edit existing pdf, and add new page or content

Dependencies: 

composer require setasign/fpdf

composer require setasign/fpdi

composer require barryvdh/laravel-dompdf

Service class :

<?php

namespace App\Services;

use setasign\Fpdi\Fpdi;
use Barryvdh\DomPDF\Facade as PDF;
use Barryvdh\DomPDF\Facade\Pdf as FacadePdf;

class PdfService
{
    public function addHtmlPageToPdf($existingPdfPath, $htmlContent, $outputPdfPath)
    {
        // Load the existing PDF
        $pdf = new Fpdi();
        $pageCount = $pdf->setSourceFile($existingPdfPath);

        // Import all pages from the existing PDF
        for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
            $templateId = $pdf->importPage($pageNo);
            $size = $pdf->getTemplateSize($templateId);

            $pdf->AddPage($size['orientation'], [$size['width'], $size['height']]);
            $pdf->useTemplate($templateId);
        }

        // Convert HTML to PDF using DOMPDF
        $htmlPdfContent = FacadePdf::loadHTML($htmlContent)->output();

        // Create a temporary file for the new PDF page
        $tempHtmlPdfPath = tempnam(sys_get_temp_dir(), 'html_pdf_') . '.pdf';
        file_put_contents($tempHtmlPdfPath, $htmlPdfContent);

        // Add the new HTML page as the last page of the PDF
        $pdf->AddPage();
        $pdf->setSourceFile($tempHtmlPdfPath);
        $templateId = $pdf->importPage(1);
        $pdf->useTemplate($templateId);

        // Output the new PDF
        $pdf->Output($outputPdfPath, 'F');

        // Clean up the temporary file
        unlink($tempHtmlPdfPath);
    }
}



Controller : 

<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\PdfService;

class PDFController extends Controller
{
    protected $pdfService;

    public function __construct(PdfService $pdfService)
    {
        $this->pdfService = $pdfService;
    }

    public function addCodeToPdf(Request $request)
    {
        $existingPdfPath=storage_path('app/reports/example.pdf');
        $htmlContent = '<h1>New Page Content</h1><p>This is a new page.</p>';
        $outputPdfPath = storage_path('app/reports/example.pdf'); //Overwrite existing
        $this->pdfService->addHtmlPageToPdf($existingPdfPath, $htmlContent, $outputPdfPath);
        return response()->download($outputPdfPath);
    }
}



Route : 


use App\Http\Controllers\PdfController;

Route::get('/add-html-page', [PdfController::class, 'addHtmlPage']);

Laravel Export data to csv

 use Illuminate\Http\Response; // Define a function to export data to CSV function exportToCSV($exportData, $columns) {     $filename = ...