Recommended way to embed PDF in HTML?

前端 未结 24 1929
天命终不由人
天命终不由人 2020-11-21 04:54

What is the recommended way to embed PDF in HTML?

  • iFrame?
  • Object?
  • Embed?

What does Adobe say itself about it?

In my

24条回答
  •  终归单人心
    2020-11-21 05:46

    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:

    
    
    
    

    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.

提交回复
热议问题