0
votes

I am using mpdf library to convert HTML to PDF and successfully stored my pdf file on local as well as remote server. But I don't want to store my pdf files on my code repos on server and like to utilize storage bucket available on google cloud.

/*
    */
    private function generatePDF($params, $quotationId) {
        $location = '/var/www/html/development/pdfs/';
        $html = $this->load->view('quotation', $data, TRUE);
        $filename = "quo_" .time() . ".pdf";
        $mpdf = new \Mpdf\Mpdf(['mode' => 'en-IN', 'format' => 'A4']);
        $mpdf->WriteHTML($html);
        $mpdf->SetHTMLFooter('<p style="text-align: center; text-size: 12px;">This is computer generated quotation. It does not require signature.</p>');
        $pdf = $mpdf->Output($location . $filename, 'F');
        $this->UploadModel->upload($pdf, $filename);
    }

public function upload($pdf, $pdfName) {
        $storage = new StorageClient();
        $bucket = $storage->bucket("bucketname");
        $object = $bucket->upload($pdf, ['name' => $pdfName]);
        $object = $bucket->object($pdfName);
        $object->update(['acl' => []], ['predefinedAcl' => 'PUBLICREAD']);
    }

Here I have used 'F' type in which it saves the pdf file in pdfs folder created in my code repo hosted on cloud server but I would like to directly store it to Google cloud storage bucket.

I am not having much experience about google cloud and mpdf library so looking for help and guidance to achieve the functionality.

Please kindly help me.

2

2 Answers

0
votes

I see you are using Cloud Storage Client Libraries for PHP.

First, you need to install it to your machine:

composer require google/cloud-storage

And then you need to set up authentication by following the guide.

Once these are set create a bucket to store the PDFs.

Then replace your upload function with the code from the documentation:

use Google\Cloud\Storage\StorageClient;

/**
 * Upload a file.
 *
 * @param string $bucketName the name of your Google Cloud bucket.
 * @param string $objectName the name of the object.
 * @param string $source the path to the file to upload.
 *
 * @return Psr\Http\Message\StreamInterface
 */
function upload_object($bucketName, $objectName, $source)
{
    $storage = new StorageClient();
    $file = fopen($source, 'r');
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->upload($file, [
        'name' => $objectName
    ]);
    printf('Uploaded %s to gs://%s/%s' . PHP_EOL, basename($source), $bucketName, $objectName);
}
0
votes

i also faced same issue & came out with this solution, i hope it will help you.
use 'S' instead of 'F'parameter, so it will return string data & pass this data directly into upload method.