bymayo / craft-pdf-transform

Transform a PDF page to an image (JPEG, PNG)
MIT License
12 stars 9 forks source link

How to apply a transform? #5

Closed zenbug closed 1 year ago

zenbug commented 4 years ago

Can you provide an example of how one would apply a standard Craft transform to the generated image in a template?

bymayo commented 4 years ago

Sure!

{# Get the PDF #}
{% set pdf = entry.pdf.one() %}

{# Convert PDF to Image #}
{% set pdfImage = craft.pdfTransform.url(pdf) %}

{# Set Transform #}
{% set pdfImageTransform = {
    mode: 'crop',
    width: 800,
    height: 600
} %}

{# Output Transformed PDF Image #}
<img src="{{ pdfImage.getUrl(pdfImageTransform) }}" alt="PDF">

I personally would do this with Imager X plugin though, as you have more control over the caching of the files etc. As I would 100% recommend images are cached if they are transformed.

Potentially do some error checking e.g. {% if pdfImage|length %} to make sure the image exists before you try and transform it also.

zenbug commented 4 years ago

When I try this code, I get the error "Impossible to invoke a method ("getUrl") on a string variable."

This seems to make sense to me, because the plugin outputs a URL already, right? So I can't use ".getUrl" on something that's already a URL.

Or am I misunderstanding something? Are you able to make that code work ?

Christopholus commented 4 years ago

We had a similar issue with the getUrl returning the same error.

Our team came up with a solution that works well, albeit a bit of a hacky one:

We took PDFTransform's returned URL, trimmed out the folder and ran a craft query to locate the created image asset. We're then able to reference this asset like we would any other, and lean on Craft's excellent transforming abilities to do the rest.

Our solution is below, hope it helps!

        {% set resourceThumb = craft.pdfTransform.url(download) %}
        {% set cleanedURL = resourceThumb | trim('/images/resource_thumbs/') %}
        {% set thumbAsset = craft.assets().filename('*'~cleanedURL~'*').one()  %}
        {% if thumbAsset|length %}
            <img src="{{ thumbAsset.getUrl('resourceThumb') }}" alt="" />
        {% endif %}
zenbug commented 4 years ago

That's clever. Thanks!

bymayo commented 1 year ago

You shouldn't need to do this now as of 1.0.8 (Craft 3) and 2.0.1 (Craft 4) as it will now output the Asset, not just the URL if you use the new render() method:

{% set pdfFile = entry.pdfFile.one() %}

{% set pdfToImage = craft.pdfTransform.render(pdfFile) %}

{% set pdfTransform =  pdfToImage.one().getUrl('resourceThumb') %} 

{% if pdfTransform|length %}
         <img src="{{ pdfTransform.getUrl('resourceThumb') }}" alt="{{ pdfToImage.one().title }}" />
{% endif %}