Jump to main content

PDF Embed

Using an Attachment element, this snippet offers a smooth method for website authors to easily upload PDF files to a website. Think along the lines of sales brochures, instruction manuals, recipe cards, product spec sheets, forms, eBooks, reports, restaurant menus, lecture handouts and much more. In addition to making the file available for download, some Javascript code is used to extract the filename and dynamically generate an embedded version of the same PDF. Support for embedded PDF files in websites is still very hit-or-miss between different web browsers and devices; so this method offers website users a reliable choice between viewing the PDF in the page or downloading a copy. The CSS and Javascript code only needs adding once on the page. The 'dataPath' variable (the first line within the Javascript) is an absolute or relative path from the current page, back to the directory WebYep is uploading files into (normally https://example.com/webyep-system/data/ as an example). The original file name of the uploaded PDF is applied as a title attribute (on the iFrame), for the benefit of screen readers.

Example

Problems viewing this PDF? You can download it here: report.pdf

HTML & PHP

<div class="embedded_pdf">
  <div class="iframe_container"></div>
  <span>Problems viewing this PDF? You can download it here: </span>
  <?php webyep_attachment("PDF Upload", false, "", 550, 240); // WebYepV2 ?>
</div>

CSS

.pdf_iframe {
    width: 100%;
    min-height: 600px;
    border: 1px solid #ccc;
}

Javascript

const dataPath = 'https://example.com/webyep-system/data/';
const eachFile = document.querySelectorAll('.embedded_pdf');
eachFile.forEach(file => {
    const iframeContainer = file.querySelector('.iframe_container');
    const fileHref = file.querySelector('a').href;
    const params = new URL(fileHref).searchParams;
    const fileName = params.get('FILENAME');
    const fileTitle = params.get('ORG_FILENAME');
    iframeContainer.innerHTML += `<iframe 
        src="${dataPath}${fileName}" 
        title=${fileTitle}
        class="pdf_iframe"
        >
    </iframe>`;
});