How does one print iframes? - html

I built a printable version of my data using multiple iframes to display line item details. However, if any of my iframe content is larger than a page they get cut off when printing (they display fine on the screen). All of my iframes point back to the same domain and I'm using the browser's File->Print function to do my printing. I don't think it's a browser specific bug as I get the same results in IE & FF.
What do I need to do to print an HTML document containing multiple iframes?

I don't believe there's an easy way of doing this. If they're all on the same domain, why are you using IFRAMEs? Why not put the data directly in the page? If you're looking for scrolling, a div with height: ###px; overflow: auto; would allow it without having to use IFRAMEs, and a CSS print stylesheet would allow you to take the overflow/height CSS off when the user hits print.

I found an answer here. While less than ideal, it'll allow me to print the master record first and then optionally print each line item as a seperate print job by printing each iframe individually.

There are different answers to this problem depending on the browser engine. To solve these issues in a simple cross-browser way I created https://github.com/noderaider/print.
I offer two npm packages:
print-utils - Generic JavaScript library
react-focus - React iframe component
Usage without React
Install via npm:
npm i -S print-utils
HTML:
<iframe id="print-content" src="/frame.html"></iframe>
JavaScript (ES2015)
import { usePrintFrame } from 'print-utils'
/** Start cross browser print frame */
const disposePrintFrame = usePrintFrame(document.getElementById('print-frame'))
/** Stop using print frame */
disposePrintFrame()
Usage with React
npm i -S react-focus
Usage:
import React, { Component } from 'react'
import reactFocus from 'react-focus'
/** Create Focus Component */
const Focus = reactFocus(React)
/**
* Use the component within your application just like an iframe
* it will automatically be printable across all major browsers (IE10+)
*/
export default class App extends Component {
render() {
return (
<div>
<div>
<h2>Welcome to react-focus</h2>
</div>
<div>
<Focus src={`?d=${Date.now()}`} />
</div>
</div>
)
}
}

Try the following (just a guess) at the bottom of your CSS:
#media print {
iframe {
overflow: visible;
}
}

Related

CSS of one component causing unwanted formatting in another

I am still just learning in Angular, CSS, and HTML (all three are new), so have some patience with me please.
I received some code, and was given the task to fix some formatting.
Here is the problem:
When the page first loads, the page header has some padding. See picture below on the left.
However, when I navigate to another page, which has this code:
/* Removing padding and scroll bar from main page */
::ng-deep html > body > main#app-content {
overflow-y: hidden;
padding: 0;
}
and then navigate to any other component/page, the padding is gone and everything is moved all the way to left of the screen, which is very annoying. See picture below on the right. Note: someone told me that this is the code that is causing this situation, and I actually have no idea what it is actually doing (besides setting the padding and y-scroll).
This picture shows two components/pages before I access the page with the code above (shown on the left side in the picture), and then after I navigate to that page with the code above (shown on t eh right side in the picture). Note the green line is for reference to show how the padding is gone.
So I would like to have the original padding/formatting back when I navigate back to it after I access the page with the code above.
Also, can someone explain to me why it's doing this? And if possible, what does the code actually mean? Here are some specific questions:
How can I stop this from happening on another page?
What does "::ng-deep html > body > main#app-content" mean?
What does the greater sign do?
TLDR: Here is a stackblitz with an example of how to edit a global style using a service rather than ::ng-deep. https://stackblitz.com/edit/angular-ivy-p4pkdu?file=src/app/app.component.html
::ng-deep is an angular feature that promotes the following css to apply globally (everywhere in your application). It should really be avoided, as there is usually a better way to apply global styles. This feature is actually being deprecated, I'll put an alternative at the end of this answer.
html > body > main#app-content is just a CSS selector. In this case we are selecting the main element with id app-content, which has body as a parent, which has html as a parent. Here is a good reference for CSS syntax: https://www.w3schools.com/cssref/css_selectors.asp.
So we are applying these css styles to an html element of type main and with id app-content, the style is applied globally, so it will still persist after the encapsulating component is destroyed.
A better alternative to ::ng-deep is to use a service to edit global styles. First off, any global styles should be stored or imported into the global styles file, usually called styles.css in an angular project. If you only need the style in one component, you can put this css in the respective component css file instead. We declare it as a class so we can add it to an element dynamically.
In styles.css
.noPaddingOrScrollbar {
overflow-y: hidden;
padding: 0;
}
Then generate a service with the cli using ng g service <serviceName>. For example, to generate a service named globalStyleService in a folder called services we do ng g service services/global-style. We'll add a boolean to our service to indicate whether we want the style applied or not.
One caveat is that we need to use setTimeout to set the boolean, to avoid the dreaded NG0100: Expression has changed after it was checked error. setTimeout will default to a timeout of zero, but will still delay the code execution until after Angular finishes a round of change detection.
import { Injectable } from '#angular/core';
#Injectable({
providedIn: 'root',
})
export class GlobalStyleService {
private _noPaddingOrScrollbar = false;
set noPaddingOrScrollbar(value: boolean) {
//Delay setting until after change detection finishes
setTimeout(() => (this._noPaddingOrScrollbar = value));
}
get noPaddingOrScrollbar() {
return this._noPaddingOrScrollbar;
}
constructor() {}
}
Now you need to find in what component this main#app-content element is actually located. It'll be in the html file of one of the parent components. You can then inject the service into this parent component ts file, and set the class dynamically in the component's html file.
Parent component ts file
export class ParentComponent {
constructor(public globalStyle: GlobalStyleService) {}
...
}
We use the angular directive [class.className]="boolean" to set the class dynamically.
Parent component html file
...
<main
id="app-content"
[class.noPaddingOrScrollbar]="globalStyle.noPaddingOrScrollbar"
></main>
...
Now you can add or remove this class from anywhere in your application. So in the component containing the hacky css, we inject the service, add the style during ngOnInit and remove it during ngOnDestroy. Of course remove the ::ng-deep statement from the css file as well.
Child component ts file
export class MyComponent implements OnInit, OnDestroy {
constructor(private globalStyle: GlobalStyleService) {}
ngOnInit(): void {
this.globalStyle.noPaddingOrScrollbar = true;
}
ngOnDestroy(): void {
this.globalStyle.noPaddingOrScrollbar = false;
}
...
}

Easiest way to add html to a React component

Say I have the following component in my web app:
class About extends React.Component {
render() {
return (
<div className="about">
/* place html here. */
</div>
)
}
}
I'm currently practicing my understanding of raw html/css. So ideally, I want to be able to write up this about section somewhere else. E.G., an about.html and an about.css, an about.html with some inline css, or a <style> tag. Or most ideally, lower down in the same file that defines this component.
The idea is I want to separate my practicing of hmtl/css from the React specific / JSX code.
Is this possible? and if so what is the least friction route assuming that this is not a very mission critical project and I'm fine with taking a less secure or more hacky approach?
If you want, you can declare a variable elsewhere or write a different component separate from this block and bring it in. But at the end of the day, you're still going to be writing JSX. You can still use .css to style your JSX the same as you would html, there's really no difference.

Node, phantomjs & converting html to pdf: element dimensions ignored?

I am wanting to generate a PDF from an HTML document, where the HTML document has elements specified with dimensions in cm. The idea is that an element or image is specified to fit in the page as specified. The issue is I can't get the dimensions to be respected.
This is the test HTML I am working with:
<html>
<head>
<title>test case</title>
</head>
<body>
<div style="width: 21cm; height: 27cm; border: solid 1px black;">This should be within page bounds!?</div>
</body>
</html>
Trying with the NodeJS module 'phantomjs-pdf' (0.1.2), I used the following code:
var pdf = require('phantomjs-pdf');
var options = {
"html" : "./test-data/document.html",
};
pdf.convert(options, function(result) {
/* Using a buffer and callback */
result.toBuffer(function(returnedBuffer) {});
/* Using a readable stream */
var stream = result.toStream();
/* Using the temp file path */
var tmpPath = result.getTmpPath();
/* Using the file writer and callback */
result.toFile("out.pdf", function() {});
});
The output document is 21cm x 29.71.cm (US Letter).
I have tried another package 'html-pdf', which also seems to to be PhantomJS based and get the same behaviour, suggesting the issue may be PhantomJS related?
Any suggestions?
I am open to using an alternative package for going from HTML to PDF, on the condition the element dimensions are respected. This is because I will be using an image as the background (PNG or SVG, depending on support), which represents an expected document template and then will be putting HTML elements with a given section of the page, based on an absolute position within an element.
I am using NodeJS 6.7.0, MacOS X 10.12 and I have PhantomJS 2.0.0 installed via MacPorts.
I gave up on PhantomJS after discovering https://github.com/fraserxu/electron-pdf. So far it has exceeded expecations. Because Electron runs Chromium the printToPDF functionality works pretty much as you'd expect. You can npm install electron-pdf and use the CLI to evaluate it for your app. Since you want Letter size add -p Letter and maybe set the margins to none.
In either case, I found that the (browser) window size in pixels needed to match the PDF size. For Letter this would be (8.5" * 96) by (11" * 96) 96 is the standard pixel per inch ratio for HTML. If you want to work in cm use that ratio.

Styling dynamically generated HTML [duplicate]

How can I control the background image and colour of a body element within an iframe? Note, the embedded body element has a class, and the iframe is of a page that is part of my site.
The reason I need this is that my site has a black background assigned to the body, and then a white background assigned to divs that contain text. A WYSIWYG editor uses an iframe to embed content when editing, but it doesn't include the div, so the text is very hard to read.
The body of the iframe when in the editor has a class that isn't used anywhere else, so I'm assuming this was put there so problems like this could be solved. However, when I apply styles to class.body they don't override the styles applied to body. The weird thing is that the styles do appear in Firebug, so I've no idea what's going on!
Thanks
UPDATE - I've tried #mikeq's solution of adding a style to the class that is the body's class. This doesn't work when added to the main page's stylesheet, but it does work when added with Firebug. I'm assuming this is because Firebug is applied to all elements on the page whereas the CSS is not applied within iframes. Does this mean that adding the css after window load with JavaScript would work?
The below only works if the iframe content is from the same parent domain.
The following code works for me. Tested on Chrome and IE8. The inner iframe references a page that is on the same domain as the parent page.
In this particular case, I am hiding an element with a specific class in the inner iframe.
Basically, you just append a style element to the head section of the document loaded in a frame:
frame.addEventListener("load", ev => {
const new_style_element = document.createElement("style");
new_style_element.textContent = ".my-class { display: none; }"
ev.target.contentDocument.head.appendChild(new_style_element);
});
You can also instead of style use a link element, for referencing a stylesheet resource.
An iframe is a 'hole' in your page that displays another web page inside of it. The contents of the iframe is not in any shape or form part of your parent page.
As others have stated, your options are:
give the file that is being loaded in the iframe the necessary CSS
if the file in the iframe is from the same domain as your parent, then you can access the DOM of the document in the iframe from the parent.
You cannot change the style of a page displayed in an iframe unless you have direct access and therefore ownership of the source html and/or css files.
This is to stop XSS (Cross Site Scripting)
This code uses vanilla JavaScript. It creates a new <style> element. It sets the text content of that element to be a string containing the new CSS. And it appends that element directly to the iframe document's head.
Keep in mind, however, that accessing elements of a document loaded from another origin is not permitted (for security reasons) -- contentDocument of the iframe element will evaluate to null when attempted from the browsing context of the page embedding the frame.
var iframe = document.getElementById('the-iframe');
var style = document.createElement('style');
style.textContent =
'body {' +
' background-color: some-color;' +
' background-image: some-image;' +
'}'
;
iframe.contentDocument.head.appendChild(style);
Override another domain iframe CSS
By using part of SimpleSam5's answer, I achieved this with a few of Tawk's chat iframes (their customization interface is fine but I needed further customizations).
In this particular iframe that shows up on mobile devices, I needed to hide the default icon and place one of my background images. I did the following:
Tawk_API.onLoad = function() {
// without a specific API, you may try a similar load function
// perhaps with a setTimeout to ensure the iframe's content is fully loaded
$('#mtawkchat-minified-iframe-element').
contents().find("head").append(
$("<style type='text/css'>"+
"#tawkchat-status-text-container {"+
"background: url(https://example.net/img/my_mobile_bg.png) no-repeat center center blue;"+
"background-size: 100%;"+
"} "+
"#tawkchat-status-icon {display:none} </style>")
);
};
I do not own any Tawk's domain and this worked for me, thus you may do this even if it's not from the same parent domain (despite Jeremy Becker's comment on Sam's answer).
An iframe has another scope, so you can't access it to style or to change its content with javascript.
It's basically "another page".
The only thing you can do is to edit its own CSS, because with your global CSS you can't do anything.
This should work with cross domain if you're the owner of the both
The trick here is to assign a global css variable to your body, to listen message with the new color, and then to change the global css variable once receive a message.
I'm using angular, but it should work with pure javascript
My use case was to show to the user what he how the color change would impact his website in the iframe before saving it
Domain A
#ViewChildren('iframeContainer') iframeContainer: QueryList<ElementRef>
sendDataToIframe(
data = {
type: 'colorChange',
colors: {primary: '#000', secondary: '#fff'},
},
): void {
if (this.targetUrl)
this.iframeContainer.first.nativeElement.contentWindow.postMessage(data) // You may use document.getElementById('iframeContainer') instead
}
Domain B
acceptedEditOrigins = [
'https://my.origine.ccom', // Be sur to have a correct origin, to avoid xss injecto: https://en.wikipedia.org/wiki/Cross-site_scripting
]
constructor() {
// Listen to message
window.addEventListener('message', (event) => this.receiveMessage(event), false)
}
receiveMessage(event: MessageEvent) {
if (this.acceptedEditOrigins.includes(event.origin))
switch (event.data.type) {
case 'colorChange': {
this.setWebsiteConfigColor(event.data.colors)
}
}
}
setWebsiteConfigColor(colors: WebsiteConfigColors) {
if (colors) {
const root = document.documentElement
for (const [key, value] of Object.entries(colors)) {
root.style.setProperty(`--${key}`, value) // --primary: #000, --secondary: #fff
}
}
}
body {
background-color: var(--primary);
}
If you have control of the page hosting the iframe and the page of the iframe, you can pass a query parameter to the iframe...
Here's an example to add a class to the iframe based on whether or not the hosting site is mobile...
Adding iFrame:
var isMobile=$("mobile").length; //detect if page is mobile
var iFrameUrl ="https://myiframesite/?isMobile=" + isMobile;
$(body).append("<div id='wrapper'><iframe src=''></iframe></div>");
$("#wrapper iframe").attr("src", iFrameUrl );
Inside iFrame:
//add mobile class if needed
var url = new URL(window.location.href);
var isMobile = url.searchParams.get("isMobile");
if(isMobile == "1") {
$("body").addClass("mobile");
}
For juste one iframe, you can do something like this:
document.querySelector('iframe').contentDocument.body.style.backgroundColor = '#1e1e2d';
In case you have multiple iframe you're dealing with:
document.querySelectorAll('iframe').forEach((iframe) => {
iframe.contentDocument.body.style.backgroundColor = '#1e1e2d';
});
Perhaps it's changed now, but I have used a separate stylesheet with this element:
.feedEkList iframe
{
max-width: 435px!important;
width: 435px!important;
height: 320px!important;
}
to successfully style embedded youtube iframes...see the blog posts on this page.
give the body of your iframe page an ID (or class if you wish)
<html>
<head></head>
<body id="myId">
</body>
</html>
then, also within the iframe's page, assign a background to that in CSS
#myId {
background-color: white;
}

How can I implement 'skip to content' links in Angular JS?

I'm trying to create a website that meets certain accessibility standards with tab clicks. I have a navigation menu on the left side of the screen and my users are requesting a "Skip to content" link so they don't have to constantly cycle through multiple links to get to where the content is.
However, I'm using AngularJS in my web app, and if I use the standard skip to content functionality (example: http://accessibility.oit.ncsu.edu/training/accessibility-handbook/skip-to-main-content.html), it won't work. I'm already using anchors (with #s) for the Angular code.
Is there any other way to implement this? I have a particular div tag that I would like the tab selection to go to. It should go to one of the elements inside the div.
I've used angular-scroll to good effect before. It's lightweight (8.5kB), easy to use, and even takes care of scrolling animations for you. It also meets accessibility standards, as the Tab key can be used to navigate just like a normal anchor tag.
Implement like this:
JS
angular
.module('app', ['duScroll'])
.controller('MainCtrl', function ($scope, $document) {
//Controller logic here
}
HTML
Navigation Link
<!-- further down the page -->
<div id="nav-one">
Content goes here.
</div>
Working CodePen for reference: http://codepen.io/Pangolin-/pen/dPQRZa
I recently worked with $anchor$croll and have some tips for you.
In your template:
Go
...
<div id="hello-scroll">Hello Scroll!</div>
In your controller:
angular
.module('someModule', [])
.controller('scrollCtrl', function($scope, $timeout, $timeout, $anchorScroll) {
/**
* #name scrollTo
* #desc Anchor scrolling within page using $anchorScroll
* #param {String} hash - Element ID.
* #return void
*/
$scope.scrollTo = function(hash) {
$location.hash(hash);
$timeout(function() {
$anchorScroll();
}, 100);
}
});
The reason I added the $timeout call is because when I tested it without it, the $scrollTo didn't seem to work. It seems that the call to $location.hash(hash) takes some small time to process, hence the 100 ms wait.