Display a PDF file within an IFrame using JavaScript and then print it

Why is it so challenging to achieve? I've dedicated 48 hours to research this, yet it seems impossible!

Although recent Chrome versions allow the parent window to access PDFs in iframes, both FF and IE prevent any interaction with the iframe that displays an "application/pdf".

The code snippet is straightforward:

<iframe id="pdfFrame" src="/mydomain/document.pdf"></iframe>

If I try to execute:

pdfFrame.contentWindow.print();

FF throws:

Error: Permission denied to access property 'print'

While IE returns:

SCRIPT65535: Invalid calling object 

Has anyone encountered a similar scenario? Any solutions to share? Or perhaps alternative suggestions? All I want is to smoothly download a PDF from my domain and send it directly to the printer.

I experimented with CSS @media to format my document but encountered issues. Despite setting the frame to 100%, only half of the content gets printed.

Appreciate any insights or advice! Thank you!

Answer №1

To display the PDF file using the HTML provided below, we utilize an Iframe specifically for Chrome printing.

<object id="exPDF" type="application/pdf" data="pdfUrl#toolbar=1&navpanes=0&statusbar=0&messages=0" style="width:100%;height:475px;" >

<iframe id="iframePDF" name="iframePDF" src="pdfUrl" width="1" height="1" >

//javascript
try {
    if (isChrome) {
        var iframe = document.getElementById('iframePDF');
        if (iframe.src) {
            var frm = iframe.contentWindow;
            frm.focus();// focus on contentWindow is needed on some versions  
            frm.print();
        }
    } else {
        var _pdf_o = document.getElementById('exPDF');
        if (_pdf_o != undefined) {
            _pdf_o.print();
        } else {
            alert("pdf object not found");
        }
    }
} catch (e) {
    alert(e.description);
}

Answer №2

In order to tackle this issue effectively, one approach is to implement a window event listener within the iframe content and then trigger a message or post message on the parent window. This will enable communication between the two windows, allowing for actions such as printing out a PDF file at the same level.

Although I personally have not tested this specific solution, my experience with utilizing event listeners and post messages in general has proven successful in similar scenarios involving iframes.

If the iframe does not contain any HTML code and simply serves as a direct link to the PDF file, it may be beneficial to explore alternative solutions first.

A helpful resource to reference when embarking on this endeavor could be found here: https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

New Feature in Bootstrap4: Navigation Bar Alignment Shift to the Left

I need help aligning my links to the right side of the page I attempted to use mr-auto but it was not effective <body> <nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top mr-auto mt-2 mt-lg-0"> <a class="navbar-brand" hre ...

Implementing inline styles in the HEAD section of a Next.js website

I currently have a blog hosted on Jekyll at , and I'm looking to migrate it to Next.js. My unique approach involves embedding all the styles directly into the HEAD element of each HTML page, without utilizing any external stylesheet files. However, wh ...

In Cypress, I am trying to specifically choose only numerical values from a dropdown menu. However, the list contains a mix of alphanumeric and numeric values

Looking to streamline: This is my code: cy.get('[role=presentation]') cy.get('[role=row]').find('td') .get('[role=gridcell]').eq(9).click().wait(2000) cy.get('[role=listbox]').get('[role=option]& ...

In React Typescript, the input type="checkbox" does not show any value in the value attribute

I'm facing an issue with displaying text next to a checkbox in React Typescript. When I try to use the value attribute, it doesn't seem to work as expected. Also, attempting to set innerHTML throws an error stating that input is a void element ta ...

Update all the key values in the JSON file to be empty strings

Looking for a solution to modify the values in a list of flat JSON key-value pairs by replacing them with empty strings. Below is an example of the JSON data: { "wl.label.accountPin": "Account PIN", "wl.label.logon": ...

The Angular Sortable Containment feature ensures that items cannot be dropped outside of

I am experiencing an issue with a horizontal sortable Angular list where the containment option is not functioning properly, causing the dragged item to not be dropped. Take a look at the sortable list below without a containment option - you may notice t ...

Ember Gain a comprehensive understanding of the flow of execution between route and controller

Below is a snippet of my "box" route/controller: export default Ember.Controller.extend({ initialized: false, type: 'P', status: 'done', layouts: null, toggleFltr: null, gridVals: Ember.computed.alias('mode ...

Some images fail to load on Ember in the production environment

I am facing an issue with my Ember-cli 1.13 application where all images are loading correctly except those in a specific component. The component is named "list-item" and is defined as follows: {{list-item url="list-url" name="List Name" price="240"}} I ...

What is the best way to choose a random image in a Django template?

I am currently facing an issue with selecting a random image in my Django template each time the page loads: <!--<img src="{% static 'images/640px-Waaah.jpg' %}"/>--> <img src="{% static 'images/Crying_Baby.jp ...

I am puzzled as to why my ajax script is giving me a 404 error even though the URL appears to be correct

Even though it's not a cross-domain problem, Ajax is returning a 404 error code. In my TIZEN Web application project, I am trying to make an ajax request to a WebService that contains functions necessary for the project. Initially, the xhr.status was ...

Expandable fluid inline svg that dynamically fills the remaining space alongside text within a flex row

How can I ensure that an inline SVG occupies all available space within a row without specifying its height across different screen sizes? The solution involves setting the SVG to have 100% height with a viewBox, allowing it to adjust accordingly while ma ...

Modifying CSS post-rendering to accommodate right-to-left or left-to-right text orientation

I have a unique single-page JavaScript website that retrieves text from a web request in JSON format. The direction of the text (RTL or LTR) is only determined once the response is received. Is there a method to re-render the page after receiving the res ...

My controller in AngularJS is having trouble fetching the latest values of the $scope variables

In my code, I've included the relevant snippet below. The base angularJS seems to be functioning properly as the HTML document doesn't display {{}} variables but instead remains blank. I suspect that this is due to the variables receiving a null ...

Unable to handle JQuery POST to PHP in success function

I am struggling with a jQuery post function that is supposed to call a PHP script in order to retrieve a value from the database. Although I can see in Firebug that the PHP file is being called and returning a 200 OK status, the success function in my JS ...

What is the solution to resolving the error in Travis CI stating "Installation failed - version 13.7.0. It appears that the remote repository may be

Struggling to configure a basic JS project with Travis CI, but encountering consistent errors. The job log indicates an issue with installing the specified Node version during NVM installation. I have experimented with altering the Node version and confi ...

Customize Date Display in Material-UI DataGrid

How do I change the date format in MUI DataGrid from mongo's format to moment.js? In addition, I would like to add a new field with an edit icon that, when clicked, will redirect to the edit page. Here is what my code looks like: const columns = [ ...

What is the best way to extract this content from the HTML using Selenium Webdriver?

My goal is to extract the text "1532.6788418669355" from this HTML code, but I've been facing challenges in doing so. Here's what I've attempted: IList options = Driver.FindElements(By.XPath(".//span//*")); Options[0].Text = "" There are n ...

Modifying the HTML <select> element with JavaScript

[resolved] I'm encountering an issue with the code below that is supposed to dynamically change the options in a second drop-down menu based on the selection made in the first menu. I've tried to troubleshoot the problem but haven't been suc ...

Leverage the hidden glitch lurking within Vue

While working with SCSS in vue-cli3, I encountered a strange bug where using /deep/ would result in errors that I prefer not to deal with. Code Running Environment: vue-cli3 + vant + scss CSS: /deep/ .van-tabs__content.van-tabs__content--animated, .va ...

The navigation area is too small for the social media buttons to fit

Hi everyone, I'm encountering an issue with the social media buttons on my website. They're not staying in the navigation header area despite trying to use the float attribute. Here are some images illustrating the problem: https://i.stack.imgur ...