1、问题:在 textarea 中,当内容换行时打印文件,文本没有换行,导致内容丢失。
2、原因:因为html2Canvas转化为图片时,不能识别 \n 、\r
3、解决方法:在打印前用div标签存储内容,并用<br /> 替换 \n,\r ,给div设置打印出来的样式;打印后还原<el-input >标签
html代码
<div id="pdfDom">
<el-input
v-if="isShow"
v-model="cshh"
type="textarea"
placeholder="只能输入2000个字符"
:rows="6"
maxlength="2000"
show-word-limit
/>
<div
v-else
class="textareaClass"
v-html=cshh && cshh.replace(/(\n|\r|\r\n)/g, '<br />')"
/>
</div>
js代码
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default {
data() {
return {
cshh:'',
isShow:true,
}
},
//打印方法
printPage() {
this.isShow = false
const that = this
setTimeout(() => {
html2Canvas(document.querySelector('#pdfDom'), {
allowTaint: true,
})
.then(function(canvas) {
const contentWidth = canvas.width
const contentHeight = canvas.height
const pageHeight = (contentWidth / 592.28) * 841.89
let leftHeight = contentHeight
let position = 0
const imgWidth = 595.28
const imgHeight = (592.28 / contentWidth) * contentHeight
const pageData = canvas.toDataURL('image/jpeg', 1.0)
const PDF = new JsPDF('', 'pt', 'a4')
if (leftHeight < pageHeight) {
PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
} else {
while (leftHeight > 0) {
PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
leftHeight -= pageHeight
position -= 841.89
if (leftHeight > 0) {
PDF.addPage()
}
}
}
PDF.save('导出文件' + '.pdf')
that.isShow = true
})
.catch(() => {
that.isShow = true
})
}, 100)
},
}
css 代码 根据实际情况设置样式
.textareaClass {
height: auto;
min-height: 129px;
display: block;
resize: vertical;
padding: 5px 15px;
line-height: 1.5;
box-sizing: border-box;
font-size: 13px;
font-family: "Avenir", Helvetica, Arial, sans-serif !important;
color: #606266;
background-color: #fff;
background-image: none;
border: 1px solid #dcdfe6;
border-radius: 4px;
transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
}
4、修改后导出内容换行