Como exibir arquivo PDF em HTML?

155

Eu tenho um arquivo PDF gerado automaticamente pelo itext e preciso exibi-lo em HTML. Minha pergunta é: Como exibir um arquivo PDF local em HTML usando pdf.js ? Esse arquivo PDF deve ser gerado por alguns padrões?

vivek
fonte
1
Possível duplicação de Exibir PDF no navegador de web
Rizvan

Respostas:

230

A implementação de um arquivo PDF em sua página HTML é muito fácil.

<embed src="file_name.pdf" width="800px" height="2100px" />

Certifique-se de alterar a largura e a altura para suas necessidades. Boa sorte!

Gofilord
fonte
Ótima solução, simples.
AugustoL
5
<iframe src="file_name.pdf" style="width: 100%;height: 100%;border: none;"></iframe>
Augsααc t ի εöβ
A <embed>tag é nova no HTML5, muito conveniente. veja aqui link
Belter
2
A melhor maneira é descrita em jsgyan.blogspot.in/2017/12/…
Suman Bogati
1
Ele mostra que o plug-in não é compatível com dispositivos móveis no navegador Chrome.
JWC
50

Eu uso o visualizador de PDF incorporável do Google Docs. Os documentos não precisam ser enviados ao Google Docs, mas precisam estar disponíveis on-line.

<iframe src="https://docs.google.com/gview?url=https://path.com/to/your/pdf.pdf&embedded=true" style="width:600px; height:500px;" frameborder="0"></iframe>
Rahul Sinha
fonte
1
Aqui está o link: Google Docs
incorporado
Você precisa usar o iframe junto com o visualizador do Google Docs. Caso contrário, poderá receber a mensagem "Erro detectado pelo firewall do aplicativo", dependendo da sua hospedagem.
user890332
1
Observe que esse método suporta apenas PDFs de até
25mb
2
Apenas mais um comentário, se você deseja incorporar um arquivo PDF no Google Drive. Depois de clicar no pdf, localize "Incorporar item", ele gerará o HTML iframe.
596 Daisy Qin
Isso não significa necessariamente precisava ser on-line, você pode armazená-lo em seus ativos localmente e apontar para ele
Manzur Khan
24

Se você quiser PDF.js usar, eu sugiro que você leia ESTE

Você também pode fazer upload do seu pdf em algum lugar (como o Google Drive) e usar o URL dele em um iframe

ou

<object data="data/test.pdf" type="application/pdf" width="300" height="200">
<a href="data/test.pdf">test.pdf</a>
</object>
Comunidade
fonte
15

você pode exibir facilmente em uma página html como esta

<embed src="path_of_your_pdf/your_pdf_file.pdf" type="application/pdf"   height="700px" width="500">

harun ugur
fonte
11

Na página html para pc é fácil de implementar

<embed src="study/sample.pdf" type="application/pdf"   height="300px" width="100%">

mas o pdf mostrado no celular por esse código não é possível, você precisa de um plug-in

se você não respondeu ao seu site. Em seguida, o código pdf acima não é exibido no celular, mas você pode colocar a opção de download após o código

<embed src="study/sample.pdf" type="application/pdf"   height="300px" width="100%" class="responsive">
<a href="study/sample.pdf">download</a>
pradip kor
fonte
No chrome, tudo bem, mas no IE não está funcionando. Como pode fazer no IE
Hong Van Vit
7

A maneira mais simples é usar,

<iframe src="pdf-link">
</iframe>

e se ele ainda estiver sendo baixado em vez de visualizado, verifique o cabeçalho de resposta do servidor, ele deve ter Content-Disposition:Inlinee não Content-Disposition:Attachment.

Rohith Murali
fonte
7

1. Incorporação embutida em HTML nativa do navegador:

<embed
    src="http://infolab.stanford.edu/pub/papers/google.pdf#toolbar=0&navpanes=0&scrollbar=0"
    type="application/pdf"
    frameBorder="0"
    scrolling="auto"
    height="100%"
    width="100%"
></embed>
<iframe
    src="http://infolab.stanford.edu/pub/papers/google.pdf#toolbar=0&navpanes=0&scrollbar=0"
    frameBorder="0"
    scrolling="auto"
    height="100%"
    width="100%"
></iframe>

Pró:

  • Sem limitações de tamanho de arquivo PDF (até centenas de MB)
  • É a solução mais rápida

Contras:

  • Não funciona em navegadores móveis

2. Visualizador do Google Docs:

<iframe
    src="https://drive.google.com/viewerng/viewer?embedded=true&url=http://infolab.stanford.edu/pub/papers/google.pdf#toolbar=0&scrollbar=0"
    frameBorder="0"
    scrolling="auto"
    height="100%"
    width="100%"
></iframe>

Pró:

  • Funciona no navegador de desktop e móvel

Contras:

  • Limite de arquivo de 25 MB
  • Requer tempo adicional para baixar o visualizador

3. Outras soluções para incorporar PDF:


NOTA IMPORTANTE:

Verifique o cabeçalho de resposta HTTP X-Frame-Options. Deve ser SAMEORIGIN.

X-Frame-Options SAMEORIGIN;
Ukr
fonte
6

Formato de documento portátil ( PDF ).

  • Qualquer navegador «Use o _Embeddable Google Document Viewer para incorporar o arquivo PDF iframe.

    <iframe src="http://docs.google.com/gview?
        url=http://infolab.stanford.edu/pub/papers/google.pdf&embedded=true"
        style="width:600px; height:500px;" frameborder="0">
    </iframe>
  • Somente para o navegador Chrome «Visualizador de PDF do Chrome usando o plug-in. pluginspage=http://www.adobe.com/products/acrobat/readstep2.html.

    <embed type="application/pdf" 
    src="http://www.oracle.com/events/global/en/java-outreach/resources/java-a-beginners-guide-1720064.pdf" 
    width="100%" height="500" alt="pdf" pluginspage="http://www.adobe.com/products/acrobat/readstep2.html" 
    background-color="0xFF525659" top-toolbar-height="56" full-frame="" internalinstanceid="21" 
    title="CHROME">

Exemplo de trecho:

<html>
   <head></head>
   <body style=" height: 100%;">
      <div style=" position: relative;">
      <div style="width: 100%; /*overflow: auto;*/ position: relative;height: auto; margin-top: 70px;">
         <p>An 
            <a href="https://en.wikipedia.org/wiki/Image_file_formats" >image</a> is an artifact that depicts visual perception
         </p>
         <!-- To make div with scroll data [max-height: 500;]-->
         <div style="/* overflow: scroll; */ max-height: 500; float: left; width: 49%; height: 100%; ">
            <img width="" height="400" src="https://peach.blender.org/wp-content/uploads/poster_bunny_bunnysize.jpg?x11217" title="Google" style="-webkit-user-select: none;background-position: 0px 0px, 10px 10px;background-size: 20px 20px;background-image:linear-gradient(45deg, #eee 25%, transparent 25%, transparent 75%, #eee 75%, #eee 100%),linear-gradient(45deg, #eee 25%, white 25%, white 75%, #eee 75%, #eee 100%);cursor: zoom-in;" />
            <p>Streaming an Image form Response Stream (binary data) «  This buffers the output in smaller chunks of data rather than sending the entire image as a single block. 
               <a href="http://www.chestysoft.com/imagefile/streaming.asp" >StreamToBrowser</a>
            </p>
         </div>
         <div style="float: left; width: 10%; background-color: red;"></div>
         <div style="float: left;width: 49%; ">
            <img width="" height="400" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot"/>
            <p>Streaming an Image form Base64 String « embedding images directly into your HTML.
               <a href="https://en.wikipedia.org/wiki/Data_URI_scheme">
               <sup>Data URI scheme</sup>
               </a>
               <a href="https://codebeautify.org/image-to-base64-converter">
               <sup>, Convert Your Image to Base64</sup>
               </a>
            <pre>data:[&lt;media type&gt;][;base64],&lt;data&gt;</pre>
            </p>
         </div>
      </div>
      <div style="width: 100%;overflow: auto;position: relative;height: auto; margin-top: 70px;">
      <video style="height: 500px;width: 100%;" name="media" controls="controls">
         <!-- autoplay -->
         <source src="http://download.blender.org/peach/trailer/trailer_400p.ogg" type="video/mp4">
         <source src="http://download.blender.org/peach/trailer/trailer_400p.ogg" type="video/ogg">
      </video>
      <p>Video courtesy of 
         <a href="https://www.bigbuckbunny.org/" >Big Buck Bunny</a>.
      </p>
      <div>
         <div style="width: 100%;overflow: auto;position: relative;height: auto; margin-top: 70px;">
            <p>Portable Document Format 
               <a href="https://acrobat.adobe.com/us/en/acrobat/about-adobe-pdf.html?promoid=CW7625ZK&mv=other" >(PDF)</a>.
            </p>
            <div style="float: left;width: 49%; overflow: auto;position: relative;height: auto;">
               <embed type="application/pdf" src="http://www.oracle.com/events/global/en/java-outreach/resources/java-a-beginners-guide-1720064.pdf" width="100%" height="500" alt="pdf" pluginspage="http://www.adobe.com/products/acrobat/readstep2.html" background-color="0xFF525659" top-toolbar-height="56" full-frame="" internalinstanceid="21" title="CHROME">
               <p>Chrome PDF viewer 
                  <a href="https://productforums.google.com/forum/#!topic/chrome/MP_1qzVgemo">
                  <sup>extension</sup>
                  </a>
                  <a href="https://chrome.google.com/webstore/detail/surfingkeys/gfbliohnnapiefjpjlpjnehglfpaknnc">
                  <sup> (surfingkeys)</sup>
                  </a>
               </p>
            </div>
            <div style="float: left; width: 10%; background-color: red;"></div>
            <div style="float: left;width: 49%; ">
               <iframe src="https://docs.google.com/gview?url=http://infolab.stanford.edu/pub/papers/google.pdf&embedded=true#:page.7" style="" width="100%" height="500px" allowfullscreen="" webkitallowfullscreen=""></iframe>
               <p>Embeddable 
                  <a href="https://googlesystem.blogspot.in/2009/09/embeddable-google-document-viewer.html" >Google</a> Document Viewer. Here's the code I used to embed the PDF file: 
<pre>
&lt;iframe 
src="http://docs.google.com/gview?
url=http://infolab.stanford.edu/pub/papers/google.pdf&embedded=true" 
style="width:600px; height:500px;" frameborder="0"&gt;&lt;/iframe&gt;
</pre>
               </p>
            </div>
         </div>
      </div>
   </body>
</html>

Yash
fonte
5

Eu tive algo semelhante antes e usei tags normalmente

<a href="path_of_your_pdf/your_pdf_file.pdf" tabindex="-1"><strong>click here</strong></a>

mas é interessante descobrir outras maneiras, como acima!

DirWolf
fonte
2

O elemento é suportado por todos os navegadores e define um objeto incorporado em um documento HTML.

Conclusão: OBJETO é bom, EMBED é antigo. Além das tags PARAM do IE, qualquer conteúdo entre as tags OBJECT será renderizado se o navegador não suportar o plug-in referido do OBJECT e, aparentemente, o conteúdo será solicitado por HTTP independentemente de ser renderizado ou não. Referência

Código de trabalho: https://www.w3schools.com/code/tryit.asp?filename=G7L8BK6XC0A6

<!DOCTYPE html>
<html>
<body>

<object width="400px" height="400px" data="https://s3.amazonaws.com/dq-blog-files/pandas-cheat-sheet.pdf"></object>
</body>
</html>

Sufiyan Ansari
fonte
0

Você pode usar

<iframe src="your_pdf_file_path" height="100%" width="100%" scrolling="auto"></iframe>

Ou, se você quiser fazer com que ela ocupe a página inteira:

<a href="your_pdf_file_path>Link</a>
aaron34weston
fonte