print content of <iframe> which exceeds one

2019-07-18 19:28发布

in my react application I have an iframe which is loaded with HTML document and content of it exceeds 1 page. on pressing Ctrl+p I want to print it in several pages but the print preview only shows one page.

how it should be handled to recognize that the content of iframe is more than one A4 page?

the DOM in chrome devtool looks like

<div class="article-container">
  <iframe style="">#document
   /* hundreds of <p> tags */
  </iframe>
</div>

the structure in react app is like

   <div className="article-container">
      <FrameText content={content} status={!this.state.editStatus} />
   </div>

and the FrameText

class FrameText extends React.Component<Props> {
  iframe: HTMLIFrameElement;
  compinentDidMount(){
    window.addEventListener('beforeprint',(e)=>{console.log(e);})
  }
  /* other stuff*/
  render() {
      const { status } = this.props;
      return <iframe ref={(ref) => (this.iframe = ref!)} style={!status ? { display: 'none' } : {}} />;
  }

so here when the ctrl+p is pressed I get the event and the iframe document is in the event. Also, I have the content of iframe in the local state too.

I could not find anywhere that when this event is triggered what can I do with it to manipulate or somehow tell the print preview that the content is long.

Also, the css is

@media print {
  .article-container {
    background-color: white;
    height: 100%;
    width: 100%;
    position: fixed;
    top: 0;
    left: 0;
    margin: 0;
    padding: 15px;
    font-size: 14px;
    line-height: 18px;
  }
}

2条回答
ゆ 、 Hurt°
2楼-- · 2019-07-18 20:13

Your print media query will not work on iframe inner content that is the reason iframe size is ignored while printing If you want to apply specific print styles to iframe then you have to reference from outside via appropriate method(whether js or html) I am writing a sample to reference styles to iframe there may exist other implementations for it to

let cssLink = document.createElement("link");
cssLink.href = "style.css"; 
cssLink.rel = "stylesheet"; 
cssLink.type = "text/css"; 
frames['iframe1'].document.head.appendChild(cssLink);
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-07-18 20:16

I was able to print multiple pages in an iframe by capturing the CTRL P event, giving focus to the iframe then initiating printing on the iframe.

<iframe id="iframe" name="iframe" src="2.html"></iframe>


<script src="https://code.jquery.com/jquery.min.js"></script>

<script>

    $(document).bind("keyup keydown", function (e) {
        if (e.ctrlKey && e.keyCode === 80) {
            window.frames["iframe"].focus();
            window.frames["iframe"].print();
            return false;
        }
        return true;
    });

</script>
查看更多
登录 后发表回答