Tuesday, 28 May 2024

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']);

No comments:

Post a Comment

Laravel Export data to csv

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