Jump to content

[archived] RockPdf - mPDF helper module


bernhard

Recommended Posts

On 10/20/2018 at 1:23 PM, charger said:

However, the problem remains: the PDFs do get saved correctly, but when trying to download them (either via wireSendFile() or RockPDF’s download()), they are blank or corrupted.

I was able to solve the problem meanwhile. It was related to my template file structure. I’m using the delayed output strategy together with some nested wireRenderFile() calls which lead to the problem.

  • Thanks 1
Link to comment
Share on other sites

1 hour ago, charger said:

The following line in RockPdf.module.php returns a wrong URL if the PW installation lives in a subdirectory (subdirectory is applied twice):


'httpUrl' => rtrim($this->pages->get(1)->httpUrl, '/') . $url,

Thx for reporting that. Could you please provide a working solution so that I don't need to setup a completely new environment using a subdir? Thx

Link to comment
Share on other sites

On 10/13/2018 at 11:20 AM, ceberlin said:

I have problems printing images embedded into a textarea if the config.php has this setting: $config->pagefileSecure=true

 ERROR: Could not find image file (.............. /site/assets/files/2922/unterschrift.jpg)

The file actually is stored under this path: ............... /site/assets/files/-2922/unterschrift.jpg

It seems that you have 

$config->pagefileSecure = true;
$config->pagefileSecurePathPrefix = '-';

in your config, is that correct? I had the same and to fix it you have to use the disk-filepath instead of an URL because the URL is protected via .htaccess.

So I used 

$page->getUnformatted($fieldName)->first()->filename

instead.

Sorry, I did not read your comment correctly. If you use images in a textarea I think you could replace the relative image url with a textformatter.

  • Thanks 2
Link to comment
Share on other sites

7 hours ago, jmartsch said:

Sorry, I did not read your comment correctly. If you use images in a textarea I think you could replace the relative image url with a textformatter.

Thank you... sounds like a cool idea. The textformatter would not be the way to go for me as I - in general - like PW's pagefileSecure feature.

Right now I am thinking of a workaround (not tested yet). Since the pagefileSecure blocking is only active on (1. pages that are hidden from "guest" users by rights restrictions (or 2. pages are unpublished), I will try to publish some innocent blank page that remains visible to users and load the needed images there into some file field in the backend. Then I would reference those (not blocked) images in the textarea of the PDF source page -  and the rights problem is maybe bypassed.

  • Like 1
Link to comment
Share on other sites

  • 3 months later...

@bernhard Servus Bernhard,

I was playing around with RockPDF today... I was wondering if you maybe disabled some mPDF functions (intentionally or not)... I tried e.g. setting header styles or use hyphenation, but those don't seem to work.

// either of these returns 
// Exception: Call to undefined method Mpdf\Mpdf::defaultheaderfontsize() on line: 50 in /home/mysite/www/dev.mysite/site/modules/RockPdf/RockPdf.module.php
$pdf->defaultheaderfontsize=9;
$pdf->defaultheaderfontstyle='I';

// same here: Exception: Call to undefined method Mpdf\Mpdf::SHYlang()
$pdf->SHYlang = 'de';

These functions are straight from the official docs...

oh, and btw: How do I adjust the default download path and filename? (using something else than "output.pdf")

d'oh: $pdf->save('foo.pdf');

Edited by dragan
  • Like 1
Link to comment
Share on other sites

2 hours ago, bernhard said:

Can you try to set those settings via $pdf->settings([ yoursettingsarray ]) ?

Thanks. That works!

I was playing around a bit more with it, and during that I managed to completely trash Tracy (it was gone all of a sudden), had massive problems with PW's file compiler and Tracy Cache, plus PHP memory limits and whatnot... Most probably not related to mPDF or RockPDF at all, I guess I was using wireRenderFile() wrong...

Here's a little example (generates a 24-pages PDF with limited rights, meta-data, and custom font in approx. 3 seconds while in debug mode)

<?
@ini_set('memory_limit', '8192M'); // just to be on the safe side
@set_time_limit(600); // ditto
$pdf = $modules->get('RockPdf');
$pdf->settings([
    'mode' => 'utf-8', 
    'defaultheaderfontsize' => 9,
    'defaultheaderfontstyle' => 'I',
    'defaultheaderline' => 0,
    'SHYlang' => 'de', // doesn't work
    'hyphens' => 'auto', // doesn't work - I have this also in my CSS
    'margin-top' => 20, // doesn't seem to work either, for some reason
    'fontdata' => [
    "inter" => [
        'R' => "Inter-Regular.ttf",
        'B' => "Inter-Black.ttf",
        'I' => "Inter-Italic.ttf",
        'BI' => "Inter-BlackItalic.ttf",
    ]],
    'default_font' => 'inter'
]);
$pdf->set('SetHeader', 'Offerte Steuerrechner Kanton Zürich 2019, Test AG, ' . date('H:i:s'));
$pdf->set('SetFooter', '{PAGENO}');
$pdf->set('SetTitle', 'Offerte Steuerrechner Kanton Zürich 2019');
$pdf->set('SetAuthor', 'Me Myself and I');
$pdf->set('SetCreator', 'Test AG');
$pdf->set('SetSubject', 'Offerte Steuerrechner');
$pdf->set('SetKeywords', 'Steuerrechner, Offerte, Angebot, Test AG, Frontend-Entwicklung');
$pdf->set('SetProtection', array('copy', 'print', 'print-highres'));
$myOffer = 11568; // each offer has a parent page with meta-data, and "chapters" as children. We pass this to the template on the next line
$str = wireRenderFile("/home/mysitecom/www/dev.test/site/templates/offer-index-dev.php", array("offer_index_page_id" => $myOffer));
$fn = $pages->get($myOffer)->name; // will be used to generate filename.pdf
$pdf->write($str);
d($pdf->save("/home/mysitecom/www/dev.test/site/assets/files/$myOffer/$fn.pdf")); // generate pdf in PW default file assets folder


// in offer-index-dev.php, I have this at the top
if(!isset($offer_index_page_id)) {
    return $this->halt();
    exit();
}

if(isset($offer_index_page_id)) {
    $offer_index = $pages->get($offer_index_page_id);
}

// I then use $offer_index->title etc. instead of $page->title further below

Not exactly rocket science, but maybe somebody else can use bits of it as first baby-steps ?

  • Like 3
Link to comment
Share on other sites

I was wondering why PW didn't automatically recognize that a new file has been uploaded to the assets folder (it's just the way PW works; as long as there is no entry in the DB, PW doesn't care what else is in that folder)... after a quick search I found this thread

I added/replaced now the last couple of lines to:

$path = "/home/mysite/www/dev.test/site/assets/files/$myOffer/$fn.pdf";
d($pdf->save($path));
$myOfferPage->of(false);
$myOfferPage->files->add($path);
$myOfferPage->save('files');

That way, site editors "automatically" see the generated PDF in the backend, and don't have to re-generate a new one each time.

  • Like 1
Link to comment
Share on other sites

  • 3 months later...
  • 5 months later...

@bernhard

many thanks for this great module. I am currently testing how it works and I will be able to use it in the future.

Unfortunately there is one important question for me at the moment:
How do you integrate it into your site? ?
I would like to put the whole code into an own file (the pdf generation doesn't have to be done every time the page is loaded) and then trigger the pdf output via a link/button on my content page.

A tip in the readme how this could look like in a live version (not only in tracy) would be great. Sorry to be stuck on this point.

Link to comment
Share on other sites

@bernhard

many thanks for your PM help.

For everyone else who might have the same problem as me, here are my implementation steps (no guarantee - I'm not a programmer)

1. activate URL segments
  (a good introduction can be found here: https://processwire.com/docs/front-end/how-to-use-url-segments/)
2. create my page WITHOUT URL segment (this shows the content + a button)
3. create a new page for the URL segment (e.g. /pdf) - this creates the PDF and displays it e.g. with show().
4. it works ?
 

My Code from No 2 (content + button) - mytemplate.php

<?php
if(strlen($input->urlSegment2)) throw new Wire404Exception();

switch($input->urlSegment1) {
	case '':
	  // Segment 1 is empty so display main content
		<!-- my main content -->
	  // My button to the PDF-creation-code
		echo "<a href='". $page->url ."pdf/' target='_new'>generate PDF</a>";
    break;

    case 'pdf':
      // Display the PDF
      include 'mytemplate-pdf.php';
      break;

    default:
      // Anything else? Throw a 404
      throw new Wire404Exception();
}
?>

 

My code for example from No 3 (PDF creation) - mytemplate-pdf.php

<?php
$pdf = $modules->get('RockPdf');
$mpdf = $pdf->mpdf;

$pdf->set('SetHeader', 'This is my header text');

// Two different ways to generate an output
$mpdf->WriteHTML('Hello World ' . date('H:i:s'));
$pdf->write('<!-- my custom comment --> Foo Bar Foo Bar ...');

// Output
$pdf->show(); // to directly show your file in the browser
?>

 

  • Like 1
Link to comment
Share on other sites

  • 2 weeks later...

@bernhard I tried setting the header type in the console before the code however this didn't work.

However for my template file which outputs the PDF I tried disabling auto prepend and append of my _init.php and _main.php file and this resolved the matter.

So it would appear that somewhere in the setup the content type is being set even after I've set it in the template file or Tracy Debugger.

For reference - https://mpdf.github.io/troubleshooting/strange-character-output-in-browser.html

Link to comment
Share on other sites

  • 2 months later...

Just updated all the dependencies of this module to the newest versions:

Package operations: 0 installs, 4 updates, 0 removals
  - Updating myclabs/deep-copy (1.7.0 => 1.9.5): Downloading (100%)
  - Updating paragonie/random_compat (v2.0.12 => v9.99.99): Downloading (100%)
  - Updating psr/log (1.0.2 => 1.1.2): Downloading (100%)
  - Updating mpdf/mpdf (v7.1.0 => v7.1.9): Downloading (100%)

v1.0.2

  • Like 2
Link to comment
Share on other sites

Just realized that mPDF version maximum was set to 7.x - RockPdf 2.0.0 uses mPDF library v8.0.5 and might introduce some breaking changes - so be careful with the update or just use RockPdf <= 1.0.2

Updating dependencies (including require-dev)
Package operations: 0 installs, 2 updates, 0 removals
  - Updating setasign/fpdi (1.6.2 => v2.3.0): Downloading (100%)
  - Updating mpdf/mpdf (v7.1.9 => v8.0.5): Downloading (100%)

v2.0.0

  • Like 3
Link to comment
Share on other sites

Another update - RockPdf now supports FontAwesome 5 in mPDF library ??

This works using webfonts (after I've unsuccessfully tried with SVG) and it supports resizing and coloring icons via CSS or LESS (wich didn't work when using SVG). I've updated the readme:

Using FontAwesome 5 with mPDF

  • Download a copy of fontawesome (https://fontawesome.com/download, eg Free for Web)
  • Copy the TTF file into your /site/assets/RockPdf/fonts/ folder
  • Add your font to your settings and start using icons in your PDFs
// tracy console
$pdf = $modules->get('RockPdf');
$pdf->settings([
  'fontdata' => (new \Mpdf\Config\FontVariables())->getDefaults()['fontdata'] + [
    "far" => [
      'R' => "fa-regular-400.ttf",
      'I' => "fa-regular-400.ttf",
    ],
  ],
]);
$icon = "<i style='font-family: far;'>&#xf118;</i> ";
$pdf->write($icon.'Hello World ' . date('H:i:s'));
d($pdf->save());

img

You'll notice that we used the unicode representation of the icon. You can find all the codes on the cheatsheet (https://fontawesome.com/cheatsheet) or on the details page of the icon: https://fontawesome.com/icons/smile?style=regular

Be careful to use the correct style (regular, solid, etc) and unicode! Special thx to jamesfairhurst

Using metadata to get the unicode

Too complicated? RockPdf comes with a helper so that you do not need to take care of all this and just use the regular fontawesome classes that you might already be familiar with! To make that work, just copy the icons.json file that is shipped with fontawesome in the metadata folder into the RockPdf assets folder /site/assets/RockPdf/fonts.

// tracy console
$pdf = $modules->get('RockPdf');
$pdf->settings([
  'fontdata' => (new \Mpdf\Config\FontVariables())->getDefaults()['fontdata'] + [
    "far" => [
      'R' => "fa-regular-400.ttf",
      'I' => "fa-regular-400.ttf",
    ],
  ],
]);
$pdf->write("<style>.far { font-family: far; color: blue; }</style>");
$icon = $pdf->icon('far fa-smile');
$pdf->write($icon.'Hello World ' . date('H:i:s'));
d($pdf->html()); // print content to console
$pdf->save(); // save file to file system

img img

Using this technique you can easily style your icons using CSS or even LESS (when using RockLESS).

Another example

Unfortunately duotone icons do not work (if you know how to make them work please drop me a line!). Also styling the icons is sometimes a bit tricky - some CSS selectors work while others don't. Using classes directly on the icon worked best for me:

$icons = $pdf->icon('fas fa-guitar red-2x')
  .$pdf->icon('far fa-guitar red-2x')
  .$pdf->icon('fal fa-guitar red-2x')
  .$pdf->icon('fad fa-guitar red-2x');
.fab { font-family: fab; }
.fad { font-family: fad; }
.fal { font-family: fal; }
.far { font-family: far; }
.fas { font-family: fas; }
.red-2x { font-size: 10mm; color: red; }

2fzYFjo.png

v2.0.1

  • Like 3
Link to comment
Share on other sites

Yeah... using inline SVGs works just fine... until you want to style fills or strokes via CSS.

I have updated rockPDF just now, and noticed that there's something buggy with using custom fonts.

Quote

Exception: Cannot find TTF TrueType font file "Inter-Regular.ttf" in configured font directories. on line: 33 in /home/foo/www/dev.foo/site/modules/RockPdf/vendor/mpdf/mpdf/src/Fonts/FontFileFinder.php

I have the fonts both in site/templates/fonts/ as well as in site/assets/RockPDF/fonts/. I have now also placed them in site/modules/RockPdf/vendor/mpdf/mpdf/ttfonts, cleared modules cache, but the error persists.

I've looked into the module code, and presumably somewhere here the paths are defined:

  public function init($options = []) {
    // make sure the assets folder exists
    $this->wire->files->mkdir($this->wire->config->paths->assets . $this->className . '/fonts', true);

    $this->settings($options);
  }

  public function settings($options = []) {
    // merge defaults
    $defaults = [
      'tempDir' => $this->wire->files->tempDir('RockPdf'),
      'fontDir' => [
        __DIR__ . '/vendor/mpdf/mpdf/ttfonts',
        $this->wire->config->paths->assets . $this->className . '/fonts',
      ],
    ];
    $options = array_merge($defaults, $options);

Any clues how to fix this?

Link to comment
Share on other sites

Another issue: If I use wireRenderFile(), I get this fatal error:

Quote

Exception: Invalid output file location or specified file does not exist. on line: 518 in /home/foo/www/dev.foobar/wire/modules/PageRender.module

This used to work just fine with the previous version (v.7x), and the assets/file/ folder definitely exists.

Link to comment
Share on other sites

  • bernhard changed the title to [archived] RockPdf - mPDF helper module

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
×
×
  • Create New...