Files
oleibman 29c870c294 Mpdf Configuration Parameters Including Custom Fonts (#3559)
Fix #3015. Fix #2766. Both issues requested a way to set Mpdf configuration parameters. I explained this could be done by extending class Mpdf and overriding protected function createExternalWriterInstance. So, no change is needed to PhpSpreadsheet. The parameters they wanted to override didn't seem interesting from a PhpSpreadsheet perspective. However, the configuration parameters include the ability to add fonts on the fly to those distributed by Mpdf, and that does sound useful. Normally, Mpdf (and Dompdf and Tcpdf) support a limited number of fonts, and will substitute for fonts they don't know (most fonts, even commonly used one, wind up using a DejaVu variant). Using these configuration options can lead to a more faithful Pdf representation of the spreadsheet.

In order to demonstrate this in action, I've added a new sample, a new class extending Mpdf, and a distinctive small font file from Google fonts with its (SIL Open Font) license. IANAL, but I can't see how this wouldn't be permitted use. There are no source code changes.

An alternate approach would be to add a callback to Writer/Pdf/Mpdf. It seems that this would be at least as much effort for the end-user as extending the class, and more effort for us.

It appears that Dompdf and Tcpdf need prep work to achieve the same end, and are thus less suitable for demonstrating via an example. I will continue to research.
2023-05-11 08:42:14 -07:00

44 lines
1.5 KiB
PHP

<?php
/**
* Override to MPDF class to allow setting config options.
*/
namespace PhpOffice\PhpSpreadsheet\Writer\Pdf;
class Mpdf2 extends Mpdf
{
/**
* Gets the implementation of external PDF library that should be used.
* This member extends Mpdf in order to allow specification of
* non-default configuration variables. In this case,
* it allows inclusion of a font which would not normally
* be used by Mpdf (which would instead use a default substitution).
* Other configuration options may be specified here.
*
* @param array $config Configuration array
*
* @return \Mpdf\Mpdf implementation
*/
protected function createExternalWriterInstance($config)
{
$defaultConfig = (new \Mpdf\Config\ConfigVariables())->getDefaults();
$fontDirs = $defaultConfig['fontDir'];
$newFontDirectory = __DIR__;
$config['fontDir'] = array_merge($fontDirs, [$newFontDirectory]);
$defaultFontConfig = (new \Mpdf\Config\FontVariables())->getDefaults();
// Note that Mpdf config uses lower-case fontdata
// even though it uses camel-case fontDir.
$fontdata = $defaultFontConfig['fontdata'];
$fontFile = 'ShadowsIntoLight-Regular.ttf';
$config['fontdata'] = $fontdata + [ // lowercase letters only in font key
'shadowsintolight' => [
'R' => $fontFile,
],
];
return new \Mpdf\Mpdf($config);
}
}