print vueJS组件或转换为pdf

时间:2018-06-05 13:12:22

标签: vue.js printing html-to-pdf html-pdf

我有一个我要打印的vueJS组件。但是,当我使用标准打印对话框时,我丢失了所有CSS,基本上只有纯文本。

我也尝试了打印

我的代码如下:

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

但是,结果与组件的呈现方式完全不同。我还没能找到解决方案。有人可以帮帮我吗?

enter image description here

1 个答案:

答案 0 :(得分:1)

问题的存在是因为printd创建了一个用于打印的新文档,因此样式不会被带入子组件中,您使用this.$el

引用它

我使用的解决方法是从当前文档的头部获取所有样式元素,并将它们附加到printd创建的文档中。将您的打印方法更改为以下内容;

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)
  })
},
相关问题