Search code examples
javascripthtmlcssvue.jsiframe

How to print only one specific vue component?


I'm making diploma which needs to be downloadable.

So I made specific vue component (diploma itself) which is in the dom but hidden with v-show (display: none).

Now I only need that specific component to be printed (or saved as pdf) and not a whole page. So I cannot initiate window.print(), but I need somehow to sandbox specific component, so I figured I could use hidden iframe and load component there and initiate print on iframe.contentWindow.print().

One problem is I don't see how I can load component in an iframe.

One way would be to use something like

 iframe.srcdoc = downloadRef.value.$el.innerHTML;

but I don't have styling this way.

I also tried something along the lines of

 iframe.srcdoc = ` ${css} ${downloadRef.value.$el.innerHTML}`;

where css is style tag string with styles, but again not all styles are applicable.

Is there any other way to load vue component into iframe and to render it as such (with vue naturally), or is there any other way to make certain component printable with all necessary styles applied, without using iframe at all?

Thanks in advance.


Solution

  • I think there's an easier way to achieve what you need without using iframe.

    What if you could apply a certain css styling for that component, which would make it occupy the whole page and cover all other content

    <style>
      .overlay {  
        position:absolute;
        top:0;
        left:0;
        width:100%;
        height:100%;
        z-index:1000;
      }
    </style>
    

    You would then be able to add a conditional class on your special component:

    <special-component :class="{'overlay': isPrintModeEnabled}"> ...
    

    So all that's left is to enable the isPrintModeEnabled property as per your rquirements.