[Untitled] The text size of the pdf generated using html2canvas and jspdf is different under different screen sizes

Problem: The text size of the pdf generated by using html2canvas and jspdf is different under different screen sizes. Under mac, everything is normal and looks very comfortable, but when I put the page under the extended screen (27 inches), and then generate another
insert image description here
insert image description here
pdf, although the typesetting is the same, but the text becomes very small When I dragged the page back to the mac, I found that the generated pdf was normal. At this time, I guessed that it should not be a text size problem.

Try: print the canvas

const pdfContent = document.querySelector('.pdf-content')
html2canvas(pdfContent).then((canvas) => {
    
    
	console.log(canvas)
})

The printed result is that the height and width of the canvas are different on different screens. At this time, I set the properties of html2canvas

html2canvas(pdfContent, {
    
    
	width: 1407,
	height: 936
}).then((canvas) => {
    
    
	console.log(canvas)
})

Let’s talk about how the data comes from, and then the print preview found that
insert image description here
the picture is not full, or it’s not
right. When it really affects the width and height of the captured picture, the attribute Window.innerWidth
can be obtained through ownerDocument.defaultView.innerHeight. When we print out ownerDocument The .defaultView property, found that there are two properties, innerHeight and innerWidth. The width of these two properties is 1407 and the height is 936 under normal print preview on mac. Then write these two properties to death, and you can ensure that The images rendered under all screens are consistent

full code

const generatePDF = () => {
    
    
	if (haveData.value == true) {
    
    
		const pdfContent = document.querySelector('.pdf-content')
		console.log(pdfContent.ownerDocument.defaultView)
		pdfContent.ownerDocument.defaultView.innerHeight = 936 
		pdfContent.ownerDocument.defaultView.innerWidth = 1407
		pdfContent.ownerDocument.defaultView.devicePixelRatio = 2
		html2canvas(pdfContent).then((canvas) => {
    
    
			console.log(canvas)
			const imgData = canvas.toDataURL('image/png', 1.0)
			const pdf = new jsPDF('p', 'mm', 'a4')
			const a4w = 190; const a4h = 277
			pdf.addImage(imgData, 'PNG', 10, 10, a4w, Math.min(a4h, a4w * canvas.height / canvas.width))
			pdf.setFontSize(20)
			pdf.save(`${
      
      valueMonth.value}月报.pdf`)
		})
	} else {
    
    
		message.warning('本月暂无数据可导出')
	}
}

In this way, you can get the pdf with the same size and the same text size under any screen

Guess you like

Origin blog.csdn.net/c327127960/article/details/131719324