print content of <iframe> which exceeds one page

ぃ、小莉子 提交于 2019-12-11 03:52:31

问题


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;
  }
}

回答1:


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);



回答2:


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>


来源:https://stackoverflow.com/questions/54912648/print-content-of-iframe-which-exceeds-one-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!