这个问题与缩放有关。在我的情况下,我在 Angular 应用程序中运行时将高度和宽度加倍,这解决了我的问题。您也可以尝试增加高度和重量来解决此问题。
import * as jsPDF from 'jspdf';
import * as html2canvas from "html2canvas";
import * as $ from 'jquery';
export class Print {
static exportTwo(elem: any,progress:any) {
var canvasToImage = function (canvas: any) {
var img = new Image();
var dataURL = canvas.toDataURL('image/png', 0.92);
img.src = dataURL;
return img;
};
var canvasShiftImage = function (oldCanvas: any, shiftAmt: any) {
shiftAmt = parseInt(shiftAmt) || 0;
if (!shiftAmt) { return oldCanvas; }
var newCanvas = document.createElement('canvas');
newCanvas.height = oldCanvas.height - shiftAmt;
newCanvas.width = oldCanvas.width;
var ctx = newCanvas.getContext('2d');
ctx['imageSmoothingEnabled'] = false;
ctx['mozImageSmoothingEnabled'] = false;
ctx['oImageSmoothingEnabled'] = false;
ctx['webkitImageSmoothingEnabled'] = false;
ctx['msImageSmoothingEnabled'] = false;
var img = canvasToImage(oldCanvas);
ctx.drawImage(img, 0, shiftAmt, img.width, img.height, 0, 0, img.width, img.height);
return newCanvas;
};
var canvasToImageSuccess = function (canvas: any) {
var l = {
orientation: 'p',
unit: 'mm',
format: 'a4',
compress: true,
fontSize: 40,
lineHeight: 1,
autoSize: false,
printHeaders: true
};
var pdf = new jsPDF(l),
pdfInternals = pdf.internal,
pdfPageSize = pdfInternals.pageSize,
pdfScaleFactor = pdfInternals.scaleFactor,
pdfPageWidth = pdfPageSize.width,
pdfPageHeight = pdfPageSize.height,
totalPdfHeight = 0,
htmlPageHeight = canvas.height,
htmlScaleFactor = canvas.width / (pdfPageWidth * pdfScaleFactor),
safetyNet = 0;
while (totalPdfHeight < htmlPageHeight && safetyNet < 15) {
var newCanvas = canvasShiftImage(canvas, totalPdfHeight);
pdf.addImage(newCanvas, 'PNG', 0, 0, pdfPageWidth, pdfPageHeight, 'NONE', 'SLOW');
totalPdfHeight += (pdfPageHeight * pdfScaleFactor * htmlScaleFactor);
if (totalPdfHeight < (htmlPageHeight)) {
pdf.addPage();
}
safetyNet++;
}
var source = $('#print')[0];
pdf.save('invoice.pdf');
};
var bigCanvas = $("<div>").appendTo($('#print'));
var scaledElement = $('#print').clone()
.css({
'margin': '2%',
'padding': '1%',
'transform': 'scale(2,2)',
'transform-origin': '0 0',
})
.appendTo(bigCanvas);
var oldWidth = scaledElement.width();
var oldHeight = scaledElement.height();
var newWidth = oldWidth * 2;
var newHeight = oldHeight * 2;
bigCanvas.css({
'width': newWidth+200,
'height': newHeight+200,
'margin': '2%',
'padding': '1%',
})
html2canvas(bigCanvas[0]).then((canvas: any) => {
canvasToImageSuccess(canvas);
bigCanvas.remove();
progress.done();
});
}
}