Jump to content

generating PDF-Documents with images


August
 Share

Recommended Posts

Hi again, after trying pages2PDF, RockPDF and mpdf I'm not sure which of them I should use. Of course, there is also wirePDF.

I merged mpdf with rockPDF, add a footer and a page in Landscape and that works, like in the code-snippet below but be am I on the right way?

After that I tried a couple of times rendering an image. Nothing happend, the same with Pages2PDF too. I also copied an Image-URL within processwire and tried further getting an Image within the PDF-Document, but it still display only the red marked placeholder.

I simply would like create an PDF on click from some Pages including the Images.

Are there special requirements on Debian 10 with Apache and php 7.3 using Processwire 3.0.123.?
Is there a guide that I didn't found?
Is somebody out there who has a similar issue solved and would you be so kind to explain?

 

        $pdf = $modules->get('RockPdf');
        $mpdf = $pdf->mpdf;
#        $mpdf->showImageErrors = true;
        $pdf->set('SetHeader', 'header text');
        $mpdf->AddPage('L');
#        $mpdf->Image(urlencode('site/assets/files/1845/image-2.275x200.jpg'), 0, 0, 210, 297, 'jpg', '', true, false);
        $pdf->set('SetFooter', '
<table width="100%">
    <tr>
        <td width="33%">{DATE j.m.Y}</td>
        <td width="33%" align="center">{PAGENO}/{nbpg}</td>
        <td width="33%" style="text-align: right;">whatever</td>
    </tr>
</table>');
        $pdf->show(); // generate pdf

 

Link to comment
Share on other sites

$img = $pages->get(1)->images->first(); // adjust to your setup
$pdf = $modules->get('RockPdf');
$mpdf = $pdf->mpdf;
$mpdf->WriteHTML('Hello World ' . date('H:i:s'));
$mpdf->WriteHTML('<div>Showing image ' . $img->url . '</div>');
$mpdf->WriteHTML('<img src="' . $img->url . '">');
$pdf->save();

Does this work?

  • Like 1
Link to comment
Share on other sites

13 hours ago, August said:

After that I tried a couple of times rendering an image. Nothing happend, the same with Pages2PDF too. I also copied an Image-URL within processwire and tried further getting an Image within the PDF-Document, but it still display only the red marked placeholder.

I think you need to pass the full (absolute) filename to the mpdf->image() method, not a relative one and not(!) a URL.

$filename = "/absolute/filepath/to/the/image.jpg";

// or when using PWs pageimage
$filename = $image->filename;

// do a test in your script for debugging:
if(!is_readable($filename)) die('Missing file');

$mpdf->AddPage('L');
$mpdf->Image($filename, 0, 0, 210, 297, 'jpg', ...

 

  • Like 2
Link to comment
Share on other sites

4 hours ago, Jens Martsch - dotnetic said:

You need to use the disk path instead of the URL

I'm using ->url in several spots in my projects and it works. Maybe he messed up something else or maybe our setups are just different. The screenshot looks like he is already using a full disc path /var/www/... and not an url site/assets/...

@August Make sure the file exists on your server and then just try different paths/urls and see which one works for you. Start doing it manually without using pw variables and once you have one working example expand on that one.

  • Like 1
Link to comment
Share on other sites

Well, yeah, I am using path because of different reasons. Because my images are not available via URL (or only if logged in) as I use pagefileSecure in my config. So the process mPDF has no access to the images, and therefore I use the path.

  • Like 1
Link to comment
Share on other sites

Hey, lets pull it down to this:

serving the full filesystempath should work everytime, if the file is_readable(),

URL „may“ work most of the time, as the pdf-lib will expand it to the full filesystempath. 

In both scenarios finally the full filesystempath is needed to read, parse, import the imagefile into the pdf object. 

?

  • Like 1
Link to comment
Share on other sites

2 hours ago, Jens Martsch - dotnetic said:

Well, yeah, I am using path because of different reasons. Because my images are not available via URL (or only if logged in) as I use pagefileSecure in my config. So the process mPDF has no access to the images, and therefore I use the path.

Nice to know, thx. I haven't been working with pdf for some time but I remember I've always had issues with the correct file paths... I think paths did somehow not work, but not sure. I think they didn't work in older versions of mpdf. There you had to define relative paths (not public urls) to a root path that was set in the module's config. Maybe things have changed to the good ? 

  • Like 1
Link to comment
Share on other sites

Hey Guys, thanks a lot for your replies. Back after work, I have just checked your answers and I'm closely suprised. It is the indication of the absolute path that the image outputs immediately. Bernhards snippet - an excerpt, I took again. Then I only changed one line as in the code-snippet below, that solved the problem. .

$mpdf->WriteHTML('<div>Showing image ' . $img->filename . '</div>');

image.png.916905d03e02045363fab265de0f4fbe.png As in the Screenshot beside, the seond Path(last line) is the right one.

Thank you bernhard, horst and jens - your all commitment is just great!

  • Like 4
Link to comment
Share on other sites

  • 2 years later...

Hey guys, I found a solution to the problem when using url or httpUrl for images in the code for the PDF. If you use "$img->filename", then the image would not render if output to the browser, but only in the pdf file.

You have to strip the rootUrl and replace "site" with "../../site", then you can have both, a working HTML page with images displayed and also afterwards a PDF also with images.

I created a helper function for this:

  public function convertUrlToRelativeInPdf($html): string {
    $html = str_replace($this->rootUrl, '', $html);
    return preg_replace('/\/site/', '../../site', $html);
  }

here is my helper function to generate all of my PDFs:

/**
   * @param $html
   * @param $pdfName
   * @param $mode
   * @param $header
   * @param $footer
   * @param $body
   * @param $stylesheet
   * @param $page
   * @param $debug
   * @param $settings
   * @return string
   * @throws WireException
   * @throws WirePermissionException
   */
  public function generatePdf($html = false, $pdfName = 'test', $mode = 'save', $header = false, $footer = false, $body = false, $stylesheet = false, $page = false, $debug = false, $settings = false): string {

    $pdf = $this->modules->get('RockPdf');
//    $pdf->mpdf->curlAllowUnsafeSslRequests  = true;
//    $pdf->mpdf->showImageErrors = true;
//    $pdf->mpdf->setBasePath ('https://shop.fugamo.de');
    $html = $this->convertUrlToRelativeInPdf($html);

    $pdf->settings([
      'margin_left' => 20,
      'margin_right' => 20,
      'margin_top' => 55,
      'margin_bottom' => 50,
      'format' => 'A4',
      'fontdata' => (new \Mpdf\Config\FontVariables())->getDefaults()[ 'fontdata' ] + [
          'sans-serif' => [
            'R' => 'Lato-Regular.ttf',
            'I' => 'Lato-Italic.ttf',
          ]
        ],
    ]);

    if (is_array($settings)) {
      $pdf->settings($settings);
    }

    $stylesheet = file_get_contents($stylesheet) ?: file_get_contents($this->config->paths->templates . '/pages2pdf/styles.css'); // external css
    $stylesheet = "<style>$stylesheet</style>";
    $pdf->write($stylesheet);

    if ($header && is_file($header)) $pdf->SetHTMLHeader($this->convertUrlToRelativeInPdf(wireRenderFile($header)));

    if ($body && is_file($body)) {
      if ($page) {
        $pdf->write($this->convertUrlToRelativeInPdf(wireRenderFile($body, ["page" => $page])));
      } else {
        $pdf->write($this->convertUrlToRelativeInPdf(wireRenderFile($body)));
      }
    } else {
      $pdf->write($html);
    }
    if ($footer && is_file($footer)) $pdf->SetHTMLFooter($this->convertUrlToRelativeInPdf(wireRenderFile($footer)));

    if ($debug) {
      die($pdf->html());
    }
    $returnValue = "";
    switch ($mode) {
      case 'download':
        $pdf->download($pdfName . ".pdf");
        $returnValue = "Das PDF wurde runtergeladen.";
        break;
      case 'show':
        $pdf->show($pdfName);
        break;
      case 'save':
        $pdfFile = $this->pdfPath . "$pdfName.pdf";
//        die($pdfFile);
        $pdf->save($pdfFile);
//        $this->message("PDF wurde gespeichert: $pdfFile");
        $returnValue = $pdfName. ".pdf";
        break;
      case 'saveAndShow':
        $pdfFile = $this->pdfPath . "$pdfName.pdf";
        $pdf->save($pdfFile);
        $pdf->show($pdfName);
    }
    bd($returnValue);
    return $returnValue;
  }

and I call it like this

$MyHelperModule = $this->modules->get('nameOfMyHelperModule');
// attention, I am using named parameters here, only available in PHP >= 8.0
$MyHelperModule->generatePdf(
      html: $html,
      pdfName: "Sammelauswertung-$id", // name
	  mode: 'show',
      stylesheet: $this->config->paths->templates . '/pages2pdf/styles.css', // stylesheet
      settings: [
        'margin_left' => 10,
        'margin_right' => 10,
        'margin_top' => 20,
        'margin_bottom' => 20,
      ]
    );

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...