Visualizações em PDF inline

:discourse2: Resumo Pré-visualizações de PDF embutidas é um componente de tema apenas para desktop que permitirá que você crie pré-visualizações para anexos em PDF.
:eyeglasses: Pré-visualização Pré-visualizar no Criador de Temas do Discourse (apenas desktop)
:hammer_and_wrench: Link do Repositório https://github.com/discourse/discourse-pdf-previews
:open_book: Novo em Temas do Discourse? Guia para iniciantes sobre o uso de Temas do Discourse

Instalar este componente de tema

Funcionalidades

antes

depois

Como mencionado acima, este componente funcionará apenas em desktop. Há muito pouco benefício em mostrar as pré-visualizações no mobile, já que tudo ficará tão pequeno e muito difícil de ler.

Este componente usa a implementação nativa do navegador para renderizar os PDFs, então os resultados parecerão diferentes em diferentes navegadores.

Além disso, note que o upload de PDFs não é permitido por padrão no Discourse. Se você quiser permitir que seus usuários façam upload de arquivos PDF, precisará adicionar essa extensão às authorized_extensions se quiser que todos os seus usuários possam fazer upload de PDFs, ou às authorized_extensions_for_staff se quiser limitar isso a membros da equipe.

:information_source: Se estiver usando S3, talvez seja necessário atualizar sua política de CORS. Consulte a postagem abaixo: Inline PDF Previews - #106 by JammyDodger

Como uso?

  1. instale o componente
  2. permita uploads de PDF
  3. atualize a página
  4. faça upload de um PDF

É isso. O resto deve funcionar automaticamente.

Configurações

Nome Descrição
modo de pré-visualização Embutido: Anexos de PDF serão renderizados embutidos dentro das postagens

Nova Aba: Links de anexos de PDF levarão o usuário a uma nova aba onde o PDF será renderizado

Funcionalidades Adicionais

Se você quiser que um PDF individual não seja renderizado embutido, basta adicionar um espaço antes do nome do arquivo - por exemplo:

Isso será exibido embutido

[sample-pdf.pdf|attachment](upload://usvbcKiQSWqA3w10gnf5PtydiXR.pdf) (82.9 KB)

Isso não será exibido embutido

[ sample-pdf.pdf|attachment](upload://usvbcKiQSWqA3w10gnf5PtydiXR.pdf) (82.9 KB)

:discourse2: Hospedado por nós? Componentes de tema estão disponíveis para uso em nossos planos Standard, Business e Enterprise.

68 curtidas

I’m hosting my uploads and images on S3, and the preview is blocked by a “CORS policy: No ‘Access-Control-Allow-Origin’ header is present”.

Below is what Chrome console says:

Access to fetch at 'https://travelmassive-discourse-cdn.s3.dualstack.us-west-1.amazonaws.com/original/2X/b/b578f6364592121964e6a2fd4969e5c1222bd909.pdf' (redirected from 'https://lounge.travelmassive.com/uploads/short-url/pTnA3r043WfhDK8HSdPQrtNn8Lf.pdf') from origin 'https://lounge.travelmassive.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Update

I was able to fix this by adding the following CORS policy in my S3 bucket configuration.

<CORSConfiguration>
 <CORSRule>
   <AllowedOrigin>https://mydiscourse.url/</AllowedOrigin>
   <AllowedMethod>GET</AllowedMethod>
   <AllowedHeader>*</AllowedHeader>
   <ExposeHeader>Access-Control-Allow-Origin</ExposeHeader>
 </CORSRule>
</CORSConfiguration>
2 curtidas

It’s necessary to add, that if you see this text in the error message from origin 'https://lounge.travelmassive.com' has been where your domain is without slash / at the end, then in the CORS configuration you should also add your domain without slash at the end like this:
https://mydiscourse.url

1 curtida

I noticed that your uploads are on AWS so, the issue is probably CORS related (the component is not active on your site for me to confirm). See the post below yours.

thanks for sharing that!

Please note that this issue will only affect self-hosters that have set up something like S3. Self-hosters that are not using S3 will not run into this issue. Customers hosted by CDCK will also not need to worry about that since they already have that set up.

That said, CORS configuration is a bit outside of the scope of this topic. If your uploads bucket does not allow your own domain access, then that needs to be fixed regardless since there might be some other issues caused by that.

I’m a little bit unsure what happened here. Both cases seem to be working for me everytime I try. We can just chalk it up to a transitory network issue but please let me know if you see it again :+1:

I pushed a tiny update to this component that should improve the loading perception, there’s now a theme-color based placeholder instead of the default browser Iframe styles. It only shows up while the file is loading so 99% of the time, you won’t even notice it.

Given that most PDFs will load instantly I didn’t feel like adding a spinner would be worth it.

9 curtidas

Would it be possible to make PDF Preview suppressable by prepending a space before the upload link, like with oneboxing? Sometimes you want a list of documents and not previews. Sometimes you want a preview.

9 curtidas

I’m on Safari on MacOS Catalina, and I don’t have anything disabling in-browser PDF display—for instance, http://www.orimi.com/pdf-test.pdf displays fine. But I’m still getting the “Blocked Plug-in” window/message when I view the preview in theme-creator.

Site-specific settings in Safari prefs aren’t any different than other websites.

Is that happening for anyone else?

3 curtidas

Still not working for me on Safari in MacOS Big Sur. No special settings to blog plugins, and other PDFs display in the browser.

Safari Web Inspector has the following complaints when loading the preview page in theme-creator:
Unrecognized Content-Security-Policy directive 'worker-src'.
Refused to load blob:https://theme-creator.discourse.org/7b9b62c7-e782-4080-a521-04e3b06aa142 because it does not appear in the object-src directive of the Content Security Policy.

3 curtidas

This would be a vast improvement to this component! Is that doable, @Johani?

5 curtidas

Same issue for me on Firefox, but only after the 2nd visit :wink:
Is there a workaround for this? Manual declaration in the CSP config?

Thank you

1 curtida

This has stopped working on my site. I get a big black box instead of the PDF preview:

Disabling plugins via Safe Mode makes no difference, nor does removing every other Theme component.

It has happened after moving image and file uploads to S3, which might be the culprit. I hope not, because they can’t be moved back easily!

I’m stumped. Shame, as it is a great component. Any suggestions?

2 curtidas

I am seeing the same behaviour with s3 uploads on.

3 curtidas

Are you still able to download the pdf ?
Still working for me (s3 + secure media and no cdn) :thinking:

1 curtida

Yes, we are. Have the same setup as you (I think).

1 curtida

:thinking:

  • my links in the messages are in the form of domain/secure-media-uploads/original/...
  • but in the console/network I can see that the actual downloads come from the bucket
    Do you see the amz credential ?

if not maybe this coud help ?

I also remember that something weird was happening when I tried to move a post from categories (or was it a copy/paste?) it finally worked when I re-uploaded the file.

1 curtida

I am experiencing this same behavior on a fresh discourse installation and a fresh PDF attachment.

3 curtidas

Thanks @Benjamin_D. Turns out I don’t have secure uploads enabled, and my links all look nice and work fine, such as this one:

https://healthforum.nz/uploads/short-url/jyY18nDviITy5inQ3Rw7xQp0cyS.pdf

So I’m stumped - especially as to why it works in two forums I run and not the other - S3 being the only difference. And that you have it working with S3. I’m really confused.

1 curtida

After updating to the latest version of discourse, the pdf-attachements are no longer displayed. What could be the problem ?

1 curtida

It may be a conflict with another component or theme. It’s working as expected for me. Start by disabling other components and try using the default theme if yours is different. Same with plugins.

3 curtidas

Ok - I’ve made progress. Disabling S3 uploads fixes it for new uploads. But I’m left with a S3 / local mess if I go down that road!

If could be that I am not using the CDN thingo (CloudFront) which throws up the annoying errors on the admin page. I’ll have a crack setting that up and see if that works.

later - nope, a CDN makes no difference.

much later - have removed S3 uploads successfully (with a bit of sweat) so all good now.

Now, I’m keen to improve it! Is any clever person with the skills interested in giving this a crack?

4 curtidas

Estou procurando um plugin que permita abrir o PDF em uma nova aba.
O comportamento atual do meu Discourse é permitir apenas o download.
Seria possível fazer isso com um tema semelhante?

5 curtidas