Jump to content

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 2
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 2
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

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
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Similar Content

    • By monollonom
      (once again I was surprised to see a work of mine pop up in the newsletter, this time without even listing the module on PW modules website 😅. Thx @teppo !)
      FieldtypeQRCode
      Github: https://github.com/romaincazier/FieldtypeQRCode
      Modules directory: https://processwire.com/modules/fieldtype-qrcode/
      A simple fieldtype generating a QR Code from the public URL of the page, and more.
      Using the PHP library QR Code Generator by Kazuhiko Arase.

      Options
      In the field’s Details tab you can change between .gif or .svg formats. If you select .svg you will have the option to directly output the markup instead of a base64 image. SVG is the default.
      You can also change what is used to generate the QR code and even have several sources. The accepted sources (separated by a comma) are: httpUrl, editUrl, or the name of any text/URL/file/image field.
      If LanguageSupport is installed the compatible sources (httpUrl, text field, ...) will return as many QR codes as there are languages. Note however that when outputting on the front-end, only the languages visible to the user will be generated.
      Formatting
      Unformatted value
      When using $page->getUnformatted("qrcode_field") it returns an array with the following structure:
      [ [ "label" => string, // label used in the admin "qr" => string, // the qrcode image "source" => string, // the source, as defined in the configuration "text" => string // and the text used to generate the qrcode ], ... ] Formatted value
      The formatted value is an <img>/<svg> (or several right next to each other). There is no other markup.
      Should you need the same markup as in the admin you could use:
      $field = $fields->get("qrcode_field"); $field->type->markupValue($page, $field, $page->getUnformatted("qrcode_field")); But it’s a bit cumbersome, plus you need to import the FieldtypeQRCode's css/js. Best is to make your own markup using the unformatted value.
      Static QR code generator
      You can call FieldtypeQRCode::generateQRCode to generate any QR code you want. Its arguments are:
      string $text bool $svg Generate the QR code as svg instead of gif ? (default=true) bool $markup If svg, output its markup instead of a base64 ? (default=false) Hooks
      Please have a look at the source code for more details about the hookable functions.
      Examples
      $wire->addHookAfter("FieldtypeQRCode::getQRText", function($event) { $page = $event->arguments("page"); $event->return = $page->title; // or could be: $event->return = "Your custom text"; }) $wire->addHookAfter("FieldtypeQRCode::generateQRCodes", function($event) { $qrcodes = $event->return; // keep everything except the QR codes generated from editUrl foreach($qrcodes as $key => &$qrcode) { if($qrcode["source"] === "editUrl") { unset($qrcodes[$key]); } } unset($qrcode); $event->return = $qrcodes; })
    • By Sebi
      AppApiFile adds the /file endpoint to the AppApi routes definition. Makes it possible to query files via the api. 
      This module relies on the base module AppApi, which must be installed before AppApiFile can do its work.
      Features
      You can access all files that are uploaded at any ProcessWire page. Call api/file/route/in/pagetree?file=test.jpg to access a page via its route in the page tree. Alternatively you can call api/file/4242?file=test.jpg (e.g.,) to access a page by its id. The module will make sure that the page is accessible by the active user.
      The GET-param "file" defines the basename of the file which you want to get.
      The following GET-params (optional) can be used to manipulate an image:
      width height maxwidth maxheight cropX cropY Use GET-Param format=base64 to receive the file in base64 format.
    • By MarkE
      This fieldtype and inputfield bundle was built for storing measurement values within a field, rendering them in a variety of formats and converting them to other units or otherwise modifying them via the API.
      The API consists of a number of predefined functions, some of which include...
      render() for rendering the measurement object, valueAs() for converting the value to another unit value, convertTo() for converting the whole measurement object to different units, and add() and subtract() for for modifying the stored value by the value (converted as required) in another measurement. In the admin the inputfield includes a checkbox (which can be optionally disabled) for converting values on page save. For an example if a value was typed in as centimeters, the unit was changed to metres, and the page saved with this checkbox selected, said value would be automatically converted so that e.g. 170 cm becomes 1.7 m.

      A simple length field using Fieldtype Measurement and Inputfield Measurement.
      Combination units (e.g. feet and inches) are also supported.
      Please note that this module is 'proof of concept' at the moment - there are limited units available and quite a lot of code tidying to do. More units will be added shortly.
      See the GitHub at https://github.com/MetaTunes/FieldtypeMeasurement for full details and updates.
    • By tcnet
      File Manager for ProcessWire is a module to manager files and folders from the CMS backend. It supports creating, deleting, renaming, packing, unpacking, uploading, downloading and editing of files and folders. The integrated code editor ACE supports highlighting of all common programming languages.
      https://github.com/techcnet/ProcessFileManager

      Warning
      This module is probably the most powerful module. You might destroy your processwire installation if you don't exactly know what you doing. Be careful and use it at your own risk!
      ACE code editor
      This module uses ACE code editor available from: https://github.com/ajaxorg/ace

      Dragscroll
      This module uses the JavaScript dragscroll available from: http://github.com/asvd/dragscroll. Dragscroll adds the ability to drag the table horizontally with the mouse pointer.
      PHP File Manager
      This module uses a modified version of PHP File Manager available from: https://github.com/alexantr/filemanager
       
    • By tcnet
      This module implements the website live chat service from tawk.to. Actually the module doesn't have to do much. It just need to inserted a few lines of JavaScript just before the closing body tag </body> on each side. However, the module offers additional options to display the widget only on certain pages.
      Create an account
      Visit https://www.tawk.to and create an account. It's free! At some point you will reach a page where you can copy the required JavaScript-code.

      Open the module settings and paste the JavaScript-code into the field as shown below. Click "Submit" and that's all.

      Open the module settings
      The settings for this module are located int the menu Modules=>Configure=>LiveChatTawkTo.

       
×
×
  • Create New...