// 导出页面为PDF格式
import JsPDF from 'jspdf'
import store from '@/store'
import domtoimage from './dom_to_image';
export default {
	install(Vue, options) {
		Vue.prototype.getPdf = () => {
			return new Promise((r, j) => {
				var title = store.state.answerSheet.paperItem.name
				setTimeout(() => {
					domtoimage.toJpeg(document.querySelector('#pdfDom'), {
							bgcolor: '#fff'
						})
						.then((pageData) => {
							let img = new Image();
							img.src = pageData;
							img.onload = function() {
								console.log('height', img.height);
								console.log('width', img.width);
								// const a4Height = 841.89
								// const a4Width = 595.28
								const a4Height = 297
								const a4Width = 210
								let contentWidth = img.width
								let contentHeight = img.height
								let pageHeight = contentWidth / a4Width * a4Height
								let leftHeight = contentHeight
								let position = 0
								//a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
								let imgWidth = a4Width
								let imgHeight = a4Width / contentWidth * contentHeight
								// console.log(pageData)
								let PDF = new JsPDF({
									orientation: 'p',
									unit: 'mm',
									format: 'a4',
									putOnlyUsedFonts: true
								})
								// 如果是一页的情况
								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 -= a4Height
										if (leftHeight > 0) {
											PDF.addPage()
										}
									}
								}
								PDF.save(title + '.pdf')
								r(PDF.output('blob'))
							}
						})
						.catch(function(error) {
							console.error('oops, something went wrong!', error);
							j(error)
						});
				}, 1000)
			})
		}
	}
}
