2

I have a vueJS component that I want to print. However, when I use the standard print dialog I lose all the CSS and basically only have plain text.

I have also tried Printd.

My code is along the lines of:

mounted () {
    this.cssText = `
        .a4-paper {
            height: 29cm;
            width: 14cm;
        }
        h4, h3, h2, h1 {
            text-align: center;
            width: 100%;
        }
        label.underline {
            border-bottom: solid black 1px;
            height: 0.3cm;
            width: 100%;
        }`;
    this.d = new Printd()  
},
methods: {
    show(event: Event) {
        this.event = event;
        this.visible = true;
    },
    print() {
        this.d.print(this.$el, this.cssText)
    }
}

However, the result looks nothing like how the component is rendered. I haven't been able to find a solution for this. Can somebody help me?

enter image description here

KaffeeKaethe
  • 301
  • 1
  • 3
  • 10

1 Answers1

1

The problem exists because printd creates a new Document for printing, therefore styles aren't carried down into the child component, which you are referencing with this.$el

The workaround which I use is to take all of the style elements from the head of the current document and append them to the document that printd creates. Change your print method to the following;

print() {
  const d = new Printd()
  d.print(this.$el, this.cssText, (win, doc, node, launchPrint) => {
    // Get style elements
    const styles = [].slice.call(document.getElementsByTagName('style'))
    // append them to the the new document head element
    styles.forEach(styleElement => doc.head.appendChild(styleElement.cloneNode(true)))
    launchPrint(win)
  })
},
Barris
  • 969
  • 13
  • 29