首页 > 解决方案 > 打印 vueJS 组件或转换为 pdf

问题描述

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

我也试过Printd

我的代码大致如下:

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

但是,结果看起来与组件的呈现方式完全不同。我一直无法找到解决方案。有人可以帮助我吗?

在此处输入图像描述

标签: vue.jsprintinghtml-to-pdfhtml-pdf

解决方案


存在问题是因为 printd 创建了一个新的 Document 用于打印,因此样式不会传递到您正在引用的子组件中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)
  })
},

推荐阅读