Programing

HTML에 PDF를 포함하는 권장 방법?

lottogame 2020. 9. 27. 12:39
반응형

HTML에 PDF를 포함하는 권장 방법?


HTML에 PDF를 포함하는 권장 방법은 무엇입니까?

  • iFrame?
  • 목적?
  • 깊숙이 박다?

Adobe는 그것에 대해 무엇을 말합니까?

필자의 경우 PDF는 즉시 생성되므로 플러시하기 전에 타사 솔루션에 업로드 할 수 없습니다.


아마도 가장 좋은 방법은 PDF.JS 라이브러리 를 사용하는 입니다. 타사 플러그인이없는 PDF 문서 용 순수 HTML5 / JavaScript 렌더러입니다.

온라인 데모 : http://mozilla.github.com/pdf.js/web/viewer.html

GitHub : https://github.com/mozilla/pdf.js


이것은 빠르고 간단하며 타사 스크립트가 필요하지 않습니다.

<embed src="http://example.com/the.pdf" width="500" height="375" 
 type="application/pdf">

업데이트 (2018 년 1 월) :

Android의 Chrome 브라우저는 더 이상 PDF 삽입을 지원하지 않습니다. Google 드라이브 PDF 뷰어를 사용하여이 문제를 해결할 수 있습니다.

<embed src="https://drive.google.com/viewerng/
viewer?embedded=true&url=http://example.com/the.pdf" width="500" height="375">

이 목적으로 Google PDF 뷰어를 사용할 수도 있습니다. 내가 아는 한 공식적인 Google 기능은 아니지만 (내가 잘못 했습니까?) 매우 훌륭하고 원활하게 작동합니다. 이전에 PDF를 어딘가에 업로드하고 URL을 사용해야합니다.

<iframe src="http://docs.google.com/gview?url=http://example.com/mypdf.pdf&embedded=true" style="width:718px; height:700px;" frameborder="0"></iframe>

중요한 것은 Flash 플레이어가 필요하지 않고 JavaScript를 사용한다는 것입니다.


쿼리 문자열에 몇 가지 옵션을 전달하여 브라우저에 PDF가 표시되는 방식을 제어 할 수 있습니다. IE8에서 작동하지 않는다는 것을 깨달을 때까지이 작업에 만족했습니다. :(

Chrome 9 및 Firefox 3.6에서 작동하지만 IE8에서는 "PDF를 표시 할 수없는 경우 여기에 오류 메시지를 삽입하십시오."라는 메시지가 표시됩니다.

그래도 위 브라우저의 이전 버전은 아직 테스트하지 않았습니다. 그러나 누군가에게 도움이 될 경우를 대비하여 어쨌든 여기에 코드가 있습니다. 이렇게하면 확대 / 축소가 85 %로 설정되고 스크롤바, 도구 모음 및 탐색 창이 제거됩니다. IE에서도 작동하는 것을 발견하면 게시물을 업데이트하겠습니다.

<object width="400" height="500" type="application/pdf" data="/my_pdf.pdf?#zoom=85&scrollbar=0&toolbar=0&navpanes=0">
    <p>Insert your error message here, if the PDF cannot be displayed.</p>
</object>

<object>둘 다 사용하면 <embed>더 광범위한 브라우저 호환성을 얻을 수 있습니다.

<object data="http://yoursite.com/the.pdf" type="application/pdf" width="750px" height="750px">
    <embed src="http://yoursite.com/the.pdf" type="application/pdf">
        <p>This browser does not support PDFs. Please download the PDF to view it: <a href="http://yoursite.com/the.pdf">Download PDF</a>.</p>
    </embed>
</object>

ImageMagick을 통해 PNG로 변환하고 PNG (빠르고 더티)를 표시합니다.

<?php
  $dir = '/absolute/path/to/my/directory/';
  $name = 'myPDF.pdf';
  exec("/bin/convert $dir$name $dir$name.png");
  print '<img src="$dir$name.png" />';
?>

빠른 솔루션이 필요하고 브라우저 간 PDF보기 문제를 피하려는 경우 및 PDF가 한두 페이지 인 경우 좋은 옵션입니다. 물론, 공유 호스팅 환경에서는 사용할 수없는 옵션 인 ImageMagick을 웹 서버에 설치해야합니다 (Ghostscript가 필요함). 이와 같이 작동하는 PHP 플러그인 (imagick이라고 함)도 있지만 고유 한 요구 사항이 있습니다.


이 코드를 찾으십시오-HTML에 PDF를 포함하려면

<!-- Embed PDF File -->
<object data="YourFile.pdf" type="application/x-pdf" title="SamplePdf" width="500" height="720">
    <a href="YourFile.pdf">shree</a> 
</object>

FDViewPDF2SWF (자체는 xpdf 기반 )와 SWF 뷰어를 결합하여 서버에서 즉시 PDF 문서를 변환하고 포함 할 수 있습니다.

xpdf is not a perfect PDF converter. If you need better results then Ghostview has some ability to convert PDF documents into other formats which you may be able to more easily build a Flash viewer for.

But for simple PDF documents, FDView should work reasonably well.


Our problem is that for legal reasons we are not allowed to temporarily store a PDF on the hard disk. In addition, the entire page should not be reloaded when displaying a PDF as Preview in the Browser.

First we tried PDF.jS. It worked with Base64 in the viewer for Firefox and Chrome. However, it was unacceptably slow for our PDF. IE/Edge didn't work at all.

We therefore tried it with a Base64 string in an HTML object tag. This again didn't work for IE/Edge (maybe the same problem as with PDF.js). In Chrome/Firefox/Safari again no problem. That's why we chose a hybrid solution. IE/Edge we use an IFrame and for all other browsers the object-tag.

The IFrame solution would of course also work for Chrome and co. The reason why we didn't use this solution for Chrome is that although the PDF is displayed correctly, Chrome makes a new request to the server as soon as you click on "download" in the preview. The required hidden-field pdfHelperTransferData (for sending our form data needed for PDF generation) is no longer set because the PDF is displayed in an IFrame. For this feature/bug see Chrome sends two requests when downloading a PDF (and cancels one of them).

Now the problem children IE9 and IE10 remain. For these we gave up a preview solution and simply send the document by clicking the preview button as a download to the user (instead of the preview). We have tried a lot but even if we had found a solution the extra effort for this tiny part of users would not have been worth the effort. You can find our solution for the download here: Download PDF without refresh with IFrame.

Our Javascript:

var transferData = getFormAsJson()
if (isMicrosoftBrowser()) {
        // Case IE / Edge (because doesn't recoginzie Pdf-Base64 use Iframe)
        var form = document.getElementById('pdf-helper-form');
        $("#pdfHelperTransferData").val(transferData);
        form.target = "iframe-pdf-shower";
        form.action = "serverSideFunctonWhichWritesPdfinResponse";
        form.submit();
 } else {
        // Case non IE use Object tag instead of iframe
        $.ajax({
            url: "serverSideFunctonWhichRetrivesPdfAsBase64",
            type: "post",
            data: { downloadHelperTransferData: transferData },
            success: function (result) {
                $("#object-pdf-shower").attr("data", result);
            }
        })
 }

Our HTML:

<div id="pdf-helper-hidden-container" style="display:none">
   <form id="pdf-helper-form" method="post">
        <input type="hidden" name="pdfHelperTransferData" id="pdfHelperTransferData" />
   </form>
</div>

<div id="pdf-wrapper" class="modal-content">
    <iframe id="iframe-pdf-shower" name="iframe-pdf-shower"></iframe>
    <object id="object-pdf-shower" type="application/pdf"></object>
</div>

To check the browser type for IE/Edge see here: How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript? I hope these findings will save someone else the time.


  1. Create a container to hold your PDF

    <div id="example1"></div>
    
  2. Tell PDFObject which PDF to embed, and where to embed it

    <script src="/js/pdfobject.js"></script>
    <script>PDFObject.embed("/pdf/sample-3pp.pdf", "#example1");</script>
    
  3. You can optionally use CSS to specify visual styling, including dimensions, border, margins, etc.

    <style>
    .pdfobject-container { height: 500px;}
    .pdfobject { border: 1px solid #666; }
    </style>
    

source : https://pdfobject.com/


Scribd no longer require you to host your documents on their server. If you create an account with them so you get a publisher ID. It only takes a few lines of JavaScript code to load up PDF files stored on your own server.

For more details, see Developer Tools.


One of the options you should consider is Notable PDF
It has a free plan unless you are planning on doing real-time online collaboration on pdfs

Embed the following iframe to any html and enjoy the results:

<iframe width='1000' height='800' src='http://bit.ly/1JxrtjR' frameborder='0' allowfullscreen></iframe>

<object width="400" height="400" data="helloworld.pdf"></object>

PdfToImageServlet using ImageMagick's convert command.

Usage example: <img src='/webAppDirectory/PdfToImageServlet?pdfFile=/usr/share/cups/data/default-testpage.pdf'>


You can use the relative location of the saved pdf like this:

Example1

<embed src="example.pdf" width="1000" height="800" frameborder="0" allowfullscreen>

Example2

<iframe src="example.pdf" style="width:1000px; height:800px;" frameborder="0" allowfullscreen></iframe>


To stream the file to the browser, see Stack Overflow question How to stream a PDF file as binary to the browser using .NET 2.0 - note that, with minor variations, this should work whether you're serving up a file from the file system or dynamically generated.

With that said, the referenced MSDN article takes a rather simplistic view of the world, so you may want to read Successfully Stream a PDF to browser through HTTPS as well for some of the headers you may need to supply.

Using that approach, an iframe is probably the best way to go. Have one webform that streams the file, and then put the iframe on another page with its src attribute set to the first form.


This is the way I did with AXIOS and Vue.js:

        axios({
            url: `urltoPDFfile.pdf`,
            method: 'GET',
            headers: headers,
            responseType: 'blob'
        })
        .then((response) => {
            this.urlPdf = URL.createObjectURL(response.data)
        })
        .catch((error) => {
            console.log('ERROR   ', error)
        })

add urlPDF dynamically to HTML:

<object width='100%' height='600px' :data='urlPdf' type='application/pdf'></object>

  1. Construct a blob of the input PDF bytes
  2. Use an iframe and PDF.js patched with this cross browser workaround

The URI for the iframe should look something like this:

/viewer.html?file=blob:19B579EA-5217-41C6-96E4-5D8DF5A5C70B

Now FF, Chrome, IE 11, and Edge all display the PDF in a viewer in the iframe passed via standard blob URI in the URL.


If you don't want to host PDF.JS on your own, you could try DocDroid. It is similar to the Google Drive PDF viewer but allows custom branding.


I found this works just fine and the browser handles it in firefox. I have not checked IE...

<script>window.location='url'</script>

참고URL : https://stackoverflow.com/questions/291813/recommended-way-to-embed-pdf-in-html

반응형