場景:?需要將頁面的局部信息打印出來,只在前端實現,不要占用后端的資源。經過百度經驗,決定使用 print-js
和html2canvas
組件。
1. 下載包
npm install print-js --save
npm install --save html2canvas
2. 組件內引用
<script>import printJS from 'print-js'import 'print-js/dist/print.css'import html2canvas from 'html2canvas'</script>
3. 執行打印方法
<div><el-card style="height: 780px; overflow: auto;page-break-after:always;"><div ref="printPaperRef"><template v-for="index in 15"><!-- 題目: 序號、類型、題干 --><div><div class="num">{{index}}</div>【單選題】<div style="padding-left: 10px;">這是一道很難很難很難很難的單選題,{{index}}}</div></div><!-- 選項 --><el-radio-group style="width: 100%" ><el-radio v-for="item in ['A', 'B', 'C', 'D']" borderclass="answer_radio"><!-- 選項flex浮動 --><div style="display: inline-flex;width: 90%;"><div class="answer_tag">{{ item }}.</div></div><div style="float: right;"><i class="el-icon-success" style="color:#1aac1a;">答案</i></div></el-radio></el-radio-group></template></div></el-card>
</div>import printJS from 'print-js'import 'print-js/dist/print.css'import html2canvas from 'html2canvas'
export default {name: 'ExamProcess',methods: {// 打印試卷printPaper() {html2canvas(this.$refs.printPaperRef, {backgroundColor: 'white',useCORS: true,foreignObjectRendering: false,windowWidth: document.body.scrollWidth,windowHeight: document.body.scrollHeight}).then((canvas) => {const url = canvas.toDataURL()this.img = urlprintJS({printable: url,type: 'image',documentTitle: "--",base64: 'true'})})}}
}
遇到的問題:
1.?html2canvas 文字向下偏移
?解決:? 使用html2canvas@^1.0.0的版本
2.?html2canvas轉圖片不清晰的問題
?
解決:?利用增大dpi
dpi:DPI是指某些設備分辨率的度量單位。DPI越低,掃描的清晰度越低,DPI越高,清晰度越高。
由于受網絡傳輸速度的影響,web上使用的圖片都是72dpi,照片使用300dpi或者更高350dpi,會很清晰。
html2canvas(template, {dpi: 300,//加了一個這個設置 useCORS: true, //(圖片跨域相關)allowTaint: false, //允許跨域(圖片跨域相關)x: 0,//頁面在橫向方向上的滾動距離 橫向上沒有超過 所以設置為0y: window.pageYOffset,//頁面在垂直方向上的滾動距離 設置了以后 超過一屏幕的內容也可以截取windowWidth: document.body.scrollWidth,//獲取在x軸上滾動條中內容windowHeight: document.body.scrollHeight,//獲取在y軸上滾動條中內容});
?解決后的效果:?
?