I have been trying to print a HTML document (not hosted by the same server) from my react app. I do not have any controls over this HTML document, I cannot edit it. I need to print the document when a button in my application is clicked. My application code is sort of similar to the below:
class SomeComponent {
_onPrintButtonClick() {
// the code to print the HTML document at HTMLFilePath must go here
}
render() {
return (
// some button
// some input field
<iframe id="iframe" src={HTMLFilePath} />
);
}
}
I have already tried the following:
Attempt #1: Has no effect, only the HTML file opens in a new tab/ window
_onPrintButtonClick() {
const w = window.open(HTMLFilePath);
w.onload = function() {
w.focus();
w.print();
}
}
Attempt #2: Throws cross origins error
_onPrintButtonClick() {
const pWindow = document.getElemetById('iframe');
pWindow.contentWindow.print();
}
Attempt #3: postMessage - I do not own the HTML document, so cannot receive the posted messages there.
UPDATE:
I'm not looking to do anything big, any fix as simple as opening the HTML document in a new window with print dialog popping up would be sufficient.
|