hanneskod / libmergepdf

PHP library for merging multiple PDFs
390 stars 77 forks source link

Feature Request: Provide method or parameter to write result to file instead of returning it #50

Closed caugner closed 4 years ago

caugner commented 4 years ago

Right now, the $merger->merge() call always returns the raw PDF.

It would be great if I could specify an output path directly to save memory and possibly time (https://github.com/clegginabox/pdf-merger seems to take half as much time when writing to a file).

jraymond96 commented 4 years ago

did you find a solution ?

kaystrobach commented 4 years ago

Use file_put_content directly

ultrono commented 4 years ago

If any Laravel users come across this package (which is ranked pretty highly in Google), you can create a response macro to download the PDF.

In your controller:

$merger = new Merger();
$merger->addIterator(['one.pdf', 'two.pdf']);
$pdf = $merger->merge();

// optionally create a local copy of the merged file
// file_put_contents(storage_path('app/pdf-temp/merged-file.pdf'), $pdf);

return response()->pdfDownload($pdf, 'merged-file.pdf');

In a service provider register a response macro:

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Response;
use Illuminate\Support\ServiceProvider;

class ResponseMacroServiceProvider extends ServiceProvider
{
    /**
     * @return void
     */
    public function boot()
    {
        Response::macro(
            'pdfDownload',
            function (string $pdf, string $fileName) {
                return Response::make($pdf)
                   ->withHeaders(
                       [
                           'Content-Type'        => 'application/pdf',
                           'Content-Disposition' => \sprintf('inline; filename="%s"', $fileName),
                           'Cache-Control'       => 'private, max-age=0, must-revalidate',
                       ]
                   );
            }
        );
    }
}
hanneskod commented 4 years ago

Sorry for the VERY late reply. It is a design decision that this library should only handle merging pdfs, not accessing filesystems or anything like that. I guess it can make it slower in some situations, but it makes the code so much cleaner and more flexible.