Skip to content

Commit

Permalink
Added: Transform PDF's on upload setting
Browse files Browse the repository at this point in the history
  • Loading branch information
bymayo committed Dec 5, 2022
1 parent 9def66f commit 6bc9572
Show file tree
Hide file tree
Showing 7 changed files with 109 additions and 66 deletions.
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
# PDF Transform Changelog

## 1.0.9 - 2022-12-05

> **Note**
> After upgrading ensure you switch on the "Transform PDF's on upload" setting in the plugin settings. Previously this was automatically on, but now defaults to false.
### Added
- Setting to optionally turn on PDF transforms on asset upload

### Fixed
- Added human friendly exception if volume is not set in the plugin settings

## 1.0.8 - 2022-11-14
### Added
- Amazon S3 Compatability
Expand Down
29 changes: 17 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ A use case for this is to show the preview of a PDF before a user downloads that

- Install with Composer via `composer require bymayo/pdf-transform` from your project directory
- Enable / Install the plugin in the Craft Control Panel under `Settings > Plugins`
- Customise the plugin settings, _*especially*_ the `Image Volume` option.
- Customise the plugin settings, _*especially*_ the `Output Image Volume` option.

You can also install the plugin via the Plugin Store in the Craft Admin CP by searching for `PDF Transform`.

Expand All @@ -34,30 +34,35 @@ You can also install the plugin via the Plugin Store in the Craft Admin CP by se
<td><strong>Default</strong></td>
<td><strong>Description</strong></td>
</tr>
<tr>
<td>Page Number</td>
<td>1</td>
<td>Set with page should in the PDF should be converted to an image.</td>
<tr>
<td>Transform PDF's on upload</td>
<td>false</td>
<td>Automatically transform any PDF file uploaded to output image volume via Assets.</td>
</tr>
<tr>
<td>Image Volume</td>
<td>Output Image Volume</td>
<td>null</td>
<td>Choose where converted images should be stored.</td>
<td>The volume you want to output transformed PDF's to.</td>
</tr>
<tr>
<td>Page Number</td>
<td>1</td>
<td>Set which page in the PDF should be transformed to an image.</td>
</tr>
<tr>
<td>Image Resolution</td>
<td>72</td>
<td>Set the resolution of the converted image.</td>
<td>Set the resolution of the transformed image.</td>
</tr>
<tr>
<td>Image Format</td>
<td>jpg</td>
<td>Set the file format of the converted image.</td>
<td>Set the file format of the transformed image.</td>
</tr>
<tr>
<td>Image Quality</td>
<td>100</td>
<td>Set the image quality of the converted image.</td>
<td>Set the image quality of the transformed image.</td>
</tr>
</table>

Expand All @@ -70,10 +75,10 @@ To transform a PDF to an image use the following Twig tag:
{% set transformedPdf = craft.pdfTransform.render(pdfToTransform) %}
{{ transformedPdf.one().url }}
{{ transformedPdf.url }}
```

The transformed PDF (Now an image stored in Assets) can then be output using `{{ transformedPdf.one().url }}`. Or get any Asset property e.g. `title`, `id`, `filename` etc.
The transformed PDF (Now an image stored in Assets) can then be output using `{{ transformedPdf.url }}`. Or get any Asset property e.g. `title`, `id`, `filename` etc.

If the transformed image doesn't exist then the PDF will be transformed via the template. This may cause the template/page to become slow whilst the PDF is transformed.

Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "bymayo/pdf-transform",
"description": "Transform a PDF page to an image (JPEG, PNG)",
"type": "craft-plugin",
"version": "1.0.8",
"version": "1.0.9",
"keywords": [
"craft",
"cms",
Expand Down
17 changes: 8 additions & 9 deletions src/PdfTransform.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ class PdfTransform extends Plugin
// =========================================================================

public static function log($message)
{
{
Craft::getLogger()->log($message, \yii\log\Logger::LEVEL_INFO, 'pdf-transform');
}
}

/**
* @inheritdoc
Expand All @@ -71,7 +71,7 @@ public function init()
]
);

Craft::getLogger()->dispatcher->targets[] = $fileTarget;
Craft::getLogger()->dispatcher->targets[] = $fileTarget;

Event::on(
CraftVariable::class,
Expand Down Expand Up @@ -108,12 +108,11 @@ function(Event $event) {

$element = $event->element;

if ($element instanceof \craft\elements\Asset) {
if ($event->isNew && $element->extension === 'pdf') {
// @TODO: trigger the imageToPdf function
PdfTransform::$plugin->pdfTransformService->pdfToImage($element);
}
}
if ($element instanceof \craft\elements\Asset) {
if ($event->isNew && $element->extension === 'pdf' && $this->getSettings()->transformPdfsOnUpload) {
PdfTransform::$plugin->pdfTransformService->pdfToImage($element);
}
}

}
);
Expand Down
4 changes: 3 additions & 1 deletion src/models/Settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@ class Settings extends Model
/**
* @var string
*/
public $page = 1;
public $transformPdfsOnUpload = false;
public $imageVolume = null;
public $page = 1;
public $imageFormat = 'jpg';
public $imageResolution = 72;
public $imageQuality = 100;
Expand All @@ -42,6 +43,7 @@ public function rules()
{
return [
[['page', 'imageVolume', 'imageResolution', 'imageQuality'], 'integer'],
['transformPdfsOnUpload', 'boolean'],
['imageFormat', 'string']
];
}
Expand Down
84 changes: 51 additions & 33 deletions src/services/PdfTransformService.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Craft;
use craft\base\Component;
use Yii;
use yii\base\Exception;
use craft\services\Volumes;
use Spatie\PdfToImage\Pdf;
use craft\elements\Asset;
Expand All @@ -27,7 +28,7 @@
class PdfTransformService extends Component
{

private $settings;
private $settings;

// Public Methods
// =========================================================================
Expand All @@ -39,7 +40,12 @@ public function __construct() {
public function getVolumeOptions()
{

$volumesArray = array();
$volumesArray = array(
array(
'label' => 'Select a volume',
'value' => null
)
);
$volumes = new Volumes;

foreach ($volumes->getAllVolumes() as $volume) {
Expand All @@ -58,8 +64,13 @@ public function getVolumeOptions()
public function getImageVolume()
{
$imageVolumeId = $this->settings->imageVolume;
$volume = Craft::$app->getVolumes()->getVolumeById($imageVolumeId);
return $volume;

if ($imageVolumeId) {
$volume = Craft::$app->getVolumes()->getVolumeById($imageVolumeId);
return $volume;
}

throw new Exception('PDF Transform: No output image volume selected in settings');
}

public function getFileName($asset)
Expand Down Expand Up @@ -97,40 +108,47 @@ public function pdfToImage($asset)
$filename = $this->getFileName($asset);
$volume = $this->getImageVolume();

$pathService = Craft::$app->getPath();
$tempPath = $pathService->getTempPath(true) . '/' . mt_rand(0, 9999999) . '.png';
file_put_contents($tempPath, file_get_contents($asset->url));

$tempPathTransform = $pathService->getTempPath(true) . '/' . $filename;

$folder = Craft::$app->getAssets()->getRootFolderByVolumeId($volume->id);

$pdf = new Pdf($tempPath);

$pdf
->setPage($this->settings->page)
->setResolution($this->settings->imageResolution)
->setCompressionQuality($this->settings->imageQuality)
->saveImage($tempPathTransform);

$assetTransformed = new Asset();
$assetTransformed->tempFilePath = $tempPathTransform;
$assetTransformed->filename = $filename;
$assetTransformed->folderId = $folder->id;
$assetTransformed->newFolderId = $folder->id;
$assetTransformed->kind = 'Image';
$assetTransformed->title = $asset->title;
$assetTransformed->avoidFilenameConflicts = true;
$assetTransformed->setVolumeId($volume->id);
$assetTransformed->setScenario(Asset::SCENARIO_CREATE);

$assetTransformed->validate();

try {

$pathService = Craft::$app->getPath();
$tempPath = $pathService->getTempPath(true) . '/' . mt_rand(0, 9999999) . '.png';
file_put_contents($tempPath, file_get_contents($asset->url));

$tempPathTransform = $pathService->getTempPath(true) . '/' . $filename;

$folder = Craft::$app->getAssets()->getRootFolderByVolumeId($volume->id);

$pdf = new Pdf($tempPath);

$pdf
->setPage($this->settings->page)
->setResolution($this->settings->imageResolution)
->setCompressionQuality($this->settings->imageQuality)
->saveImage($tempPathTransform);

$assetTransformed = new Asset();
$assetTransformed->tempFilePath = $tempPathTransform;
$assetTransformed->filename = $filename;
$assetTransformed->folderId = $folder->id;
$assetTransformed->newFolderId = $folder->id;
$assetTransformed->kind = 'Image';
$assetTransformed->title = $asset->title;
$assetTransformed->avoidFilenameConflicts = true;
$assetTransformed->setVolumeId($volume->id);
$assetTransformed->setScenario(Asset::SCENARIO_CREATE);

$assetTransformed->validate();

if (Craft::$app->getElements()->saveElement($assetTransformed, false))
{
return $assetTransformed;
}

}
catch (Exception $e) {
throw new Exception('PDF Transform: Could not transform PDF to image');
}


}

Expand Down
28 changes: 18 additions & 10 deletions src/templates/settings.twig
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,17 @@

{% do view.registerAssetBundle("bymayo\\pdftransform\\assetbundles\\PdfTransform\\PdfTransformAsset") %}

{{ forms.textField({
label: 'Page Number',
instructions: 'The page number to render.',
id: 'page',
name: 'page',
value: settings['page'],
required: true
})
}}
{{ forms.lightswitchField({
label: 'Transform PDF\'s on upload',
instructions: 'Automatically transform any PDF file uploaded to output image volume via Assets.',
id: 'transformPdfsOnUpload',
name: 'transformPdfsOnUpload',
on: settings['transformPdfsOnUpload'],
}) }}

{{ forms.selectField({
label: 'Output Image Volume',
instructions: 'The volume you want to output renders to',
instructions: 'The volume you want to output transformed PDF\'s to',
id: 'imageVolume',
name: 'imageVolume',
value: settings['imageVolume'],
Expand All @@ -23,6 +21,16 @@
})
}}

{{ forms.textField({
label: 'Page Number',
instructions: 'The page number to transform.',
id: 'page',
name: 'page',
value: settings['page'],
required: true
})
}}

{{ forms.textField({
label: 'Image Resolution',
id: 'imageResolution',
Expand Down

0 comments on commit 6bc9572

Please sign in to comment.