the picture from highcharts in the PDF made by html2canvas is blurry? - highcharts

(function() {
var form = $('#printContent');
$('#create_pdf').on('click', function() {
$('body').scrollTop(0);
createPDF();
});
//create pdf
function createPDF() {
getCanvas().then(function(canvas) {
var imgData = canvas.toDataURL("image/png");
var imgWidth = 210;
var pageHeight = 295;
var imgHeight = (canvas.height) * imgWidth / canvas.width;
var heightLeft = imgHeight;
var doc = new jsPDF('p', 'mm');
var position = 0;
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
console.log(canvas.height);
while(heightLeft >= 0) {
position = heightLeft - imgHeight;
doc.addPage();
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
// console.log(position);
}
doc.save('file.pdf');
});
}
// create canvas object
function getCanvas() {
return html2canvas(form, {
imageTimeout: 0,
removeContainer: false
});
}
}());
I use the html2canvas to make PDF, but the charts in the PDF is blurry, is there solution to solve it? the title and the legend are blurry, and the code is below?

If you set legend to useHTML this solves the problem:
legend: {
useHTML: true
}

Related

Image canvas toDataURL function is not wokring on ios

I have a drawImage function in my application which loads the image from a blob and then from that image object calls the toDataURL function for the canvas to draw image. The problem is that this code works on android and browser but not working on iphone or ipad.
I have tried passing the image type to the toDataURL function and tried setting the default width and height of the canvas to prevent width getting 0 for the canvas but nothing seems to work on iphone or ipad. It only shows a blank screen inplace of the image.
the code works fine on mac/safari as well but not in iphone/ipad on any browser.
here is my drawImage function
_drawImage(img) {
// console.log("drawimage");
this.setState({ isGenerating: true });
if (img) {
fetch(img)
.then((r) => r.blob())
.then((blob) => {
loadImage(
blob,
(img) => {
if (img.type === "error") {
this.setState({ error: true });
// console.log(img, "Error loading image ");
} else {
const image = new window.Image();
const height = this.props.height;
const width = this.props.width;
image.src = img.toDataURL('image/jpeg');
console.log(image.src, height, width)
image.onload = () => {
let offsetX,
offsetY,
renderableWidth = image.width,
renderableHeight = image.height;
var imageDimensionRatio = image.width / image.height;
var canvasDimensionRatio = width / height;
// console.log(
// "ratios of image and canvas =",
// imageDimensionRatio,
// canvasDimensionRatio
// );
if (imageDimensionRatio < canvasDimensionRatio) {
renderableHeight = height;
renderableWidth =
image.width * (renderableHeight / image.height);
offsetX = (width - renderableWidth) / 2;
offsetY = 0;
} else if (imageDimensionRatio > canvasDimensionRatio) {
renderableWidth = width;
renderableHeight =
image.height * (renderableWidth / image.width);
offsetX = 0;
offsetY = (height - renderableHeight) / 2;
} else {
renderableHeight = height;
renderableWidth = width;
offsetX = 0;
offsetY = 0;
}
console.log(renderableHeight, renderableWidth, image)
this.setState(
{
image: image,
renderableHeight,
renderableWidth,
imgHeight: image.height,
imgWidth: image.width,
offsetX,
offsetY,
height,
width,
},
() => {
this.setState({ isGenerating: false });
}
);
};
}
},
{
orientation: true,
canvas: true,
}
);
});
}
}
EDIT
I've solved the issue by passing maxWidth to loadImage params along with orientation and canvas, which limits the width to not to exceed in ios devices and thus onload function works properly.
basically I've added the below code.
maxWidth: 10000

Jspdf and html2pdf not working with dynamic data for multiple pages(more than 25 pages in pdf) , overlapping issue

I am trying to implement generic solution since my html content won't be fixed,i want to convert html 2 pdf but problem is getting cut between the pages, page break not working correctly.
//var staticHeight = 0;
//$('div').each(function () {
// staticHeight += $(this).filter(':visible').outerHeight(true);
// var pageHeight = 100
// console.log(staticHeight)
// if (staticHeight > pageHeight) {
// $(this).after('<div class="page-break" id="activediv2"> asasjjasasa asas </div>');
// staticHeight = 0;
// }
//});
//return html2canvas(document.getElementsByClassName('custom-content')[0], {
// onrendered: function (canvasObj) {
// startPrintProcess(canvasObj, 'printedPDF', function () {
// alert('PDF saved');
// });
// //save this object to the pdf
// }
//});
//return html2canvas($(element)[0], {
// background: "#ffffff",
// onrendered: function (canvas) {
// var myImage = canvas.toDataURL("image/jpeg,1.0");
// // Adjust width and height
// var imgWidth = (canvas.width * 60) / 247;
// var imgHeight = (canvas.height * 70) / 247;
// // jspdf changes
// var pdf = new jsPDF('l', 'mm', 'a4');
// pdf.addImage(myImage, 'png', 15, 2, imgWidth, imgHeight); // 2: 19
// pdf.save('sample.pdf');
// }
//});
var HTML_Width = $(element).width();
var HTML_Height = $(element).height();
var top_left_margin = 15;
var PDF_Width = HTML_Width + (top_left_margin * 2);
var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
var canvas_image_width = HTML_Width;
var canvas_image_height = HTML_Height;
pdf = "";
html2canvas(element, {
background: '#FFFFFF',
onclone: function (doc) {
hiddenDiv = document.getElementsByClassName('custom-content')[0];
hiddenDiv.style.display = 'block';
},
onrendered: function (canvas) {
var width = canvas.width;
var height = canvas.height;
var millimeters = {};
millimeters.width = Math.floor(width * 0.274583);
millimeters.height = Math.floor(height * 0.274583);
var context = canvas.getContext('2d');
context.scale(2, 2);
var imgData = canvas.toDataURL('image/png');
var doc = new jsPDF("l", "mm", "a4");
// doc.deletePage(1);
// doc.addPage(millimeters.width, millimeters.height);
//doc.addImage(imgData, 'PNG', 0, 0, width, height);
//doc.save('wardrobemodel.pdf');
var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;
for (var i = 0; i <= totalPDFPages; i++) {
doc.addPage(PDF_Width, PDF_Height);
doc.addImage(imgData, 'JPG', 0, -(PDF_Height * i) + (top_left_margin * 4), canvas_image_width, canvas_image_height);
}
doc.save('wardrobemodel.pdf');
}
});
//var worker = html2pdf().from(element).toPdf();
////for (let i = 0; i < pages.length; i++) {
//// worker = worker.set(opt).from(pages[i]).toContainer().toCanvas().toPdf().get('pdf').then((pdf) => {
//// if (i < pages.length - 1) { // Bump cursor ahead to new page until on last page
//// pdf.addPage();
//// }
//// });
////}
//worker = worker.save();
//$('.tile-body').find('div').each(function () {
// var eleHeight = $(this).filter(':visible').outerHeight(true);
// staticHeight += pix2mm(eleHeight, 300);
// var pageHeight = 257
// console.log(staticHeight)
// if (staticHeight > pageHeight) {
// $(this).after('<div class="page-break mt-1 mb-1" id="activediv2"></div>');
// staticHeight = 0;
// }
//});
return html2canvas(element, {
onrendered: function (canvasObj) {
startPrintProcess(canvasObj, 'printedPDF', function () {
alert('PDF saved');
});
//save this object to the pdf
}
});
//$('.tile-body').children('div').each(function () {
// var eleHeight = $(this).filter(':visible').outerHeight(true);
// staticHeight += pix2mm(eleHeight, 300);
// var pageHeight = 257
// console.log(staticHeight)
// if (staticHeight > pageHeight) {
// $(this).after('<div class="page-break mt-3 mb-5" id="activediv2"></div>');
// staticHeight = 0;
// }
//});
staticHeight = 0;
//var opt = {
// margin: 0.25,
// filename: 'ontract.pdf',
// image: { type: 'jpeg', quality: 0.98 },
// html2canvas: { scale: 2 },
// jsPDF: { unit: 'mm', format: 'a4', orientation: 'landscape' },
// pagebreak: { mode: 'avoid-all', after: '#activediv2' }
//};
//var worker = html2pdf().from(element).toPdf();
//worker.save();
// html2pdf().from(element).set(opt).toPdf().get('pdf').save()
// return;
//html2canvas(element, {
// logging: false
//}).then(function (canvas) {
// var pdf = new jsPDF('l', 'mm', 'a4');//A4 paper, portrait
// /// pdf.internal.scaleFactor = 30;
// var ctx = canvas.getContext('2d'),
// a4w = 190, a4h = 257,//A4 size, 210mm x 297mm, 10 mm margin on each side, display area 190x277
// imgHeight = Math.floor(a4h * canvas.width / a4w),//Convert pixel height of one page image to A4 display scale
// renderedHeight = 0;
// var pdfConf = {
// pagesplit: true,
// pagebreak: { mode: 'avoid-all', before: '#activediv2' }
// };
// var logo = document.getElementsByClassName(".logo-img")[0];//Icon placed in header
// while (renderedHeight < canvas.height) {
// var page = document.createElement("canvas");
// page.width = canvas.width;
// page.height = Math.min(imgHeight, canvas.height - renderedHeight);//Maybe less than one page
// //Trim the specified area with getImageData and draw it into the canvas object created earlier
// page.getContext('2d').putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0);
// //Add an image to the page with a 10 mm / 20 mm margin
// pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'JPEG', 10, 20, a4w, Math.min(a4h, a4w * page.height / page.width));
// //Add header logo
// // pdf.addImage(logo, 'SVG', 5, 3);
// var context = page.getContext('2d');
// context.scale(2, 2);
// //pdf.addHTML(element, { pagesplit: true, canvas: page }, function () {
// // // var out = pdf.output('dataurlnewwindow'); // crashed if bigger file
// // pdf.save('two-by-four.pdf')
// //});
// renderedHeight += imgHeight;
// if (renderedHeight < canvas.height)
// pdf.addPage();//Add an empty page if there is more to follow
// delete page;
// }
// pdf.save('content.pdf');
//});
//return;
//var HTML_Width = $(element).width();
//var HTML_Height = $(element).height();
//var top_left_margin = 15;
//var PDF_Width = HTML_Width + (top_left_margin * 2);
//var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
//var canvas_image_width = HTML_Width;
//var canvas_image_height = HTML_Height;
//var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;
//html2canvas($(element)[0], { allowTaint: true }).then(function (canvas) {
// var context = canvas.getContext('2d');
// context.scale(2, 2);
// console.log(canvas.height + " " + canvas.width);
// var imgData = canvas.toDataURL("image/jpeg", 1.0);
// var pdf = new jsPDF('l', 'pt', [PDF_Width, PDF_Height]);
// pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height);
// for (var i = 1; i <= totalPDFPages; i++) {
// pdf.addPage(PDF_Width, PDF_Height);
// pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height * i) + (top_left_margin * 4), canvas_image_width, canvas_image_height);
// }
// pdf.save("HTML-Document.pdf");
//});
//return;
///
//html2canvas($(element)[0], { allowTaint: true }).then(function (canvas) {
// calculatePDF_height_width(".print-wrap", 1);
// var imgData = canvas.toDataURL("image/png", 1.0);
// pdf.addPage(PDF_Width, PDF_Height);
// pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, HTML_Width, HTML_Height);
// pdf.save("11.pdf")
//});
div {
page-break-inside: avoid;
}
this is what i tried
In short my target to achieve add page break if generated pdf is breaking html content between two pages.
I solve my problem for export HTML to multiple-page PDF. I create canvas per div. Perhaps this is will help you all.
private canvas: any = {
monthYearCanvas: null,
monthYearHeight: 0,
periodCanvas: null,
periodHeight: 0,
assetCanvas: null,
assetHeight: 0,
badActorCanvas: null,
badActorHeight: 0,
eventCanvas: null,
eventHeight: 0,
tenLowOffCanvas: null,
tenLowOffHeight: 0,
};
public triggerPrintReport(): void {
if (
this.isLoadingMonthYear ||
this.isLoadingOnPeriod ||
this.isLoadingOnAsset ||
this.isLoadingOnBadActor ||
this.isLoadingOnEvent ||
this.isLoadingTenLowOff
) {
alert('Wait for load data');
return;
}
this.messageReport = true;
const monthYearHTML = document.getElementById('htmlData-monthYear');
const periodHTML = document.getElementById('htmlData-period');
const assetHTML = document.getElementById('htmlData-asset');
const badActorHTML = document.getElementById('htmlData-badActor');
const eventHTML = document.getElementById('htmlData-event');
const tenLowOffHTML = document.getElementById('htmlData-tenLowOff');
this.createCanvasURL(monthYearHTML, 'monthYear');
this.createCanvasURL(periodHTML, 'period');
this.createCanvasURL(assetHTML, 'asset');
this.createCanvasURL(badActorHTML, 'badActor');
this.createCanvasURL(eventHTML, 'event');
this.createCanvasURL(tenLowOffHTML, 'tenLowOff');
}
private createCanvasURL(element: any, type: string): void {
html2canvas(element).then(canvas => {
const width = 208;
if (type === 'monthYear') {
this.canvas.monthYearHeight = canvas.height * width / canvas.width;
this.canvas.monthYearCanvas = canvas.toDataURL('image/png');
} else if (type === 'period') {
this.canvas.periodHeight = canvas.height * width / canvas.width;
this.canvas.periodCanvas = canvas.toDataURL('image/png');
} else if (type === 'asset') {
this.canvas.assetHeight = canvas.height * width / canvas.width;
this.canvas.assetCanvas = canvas.toDataURL('image/png');
} else if (type === 'badActor') {
this.canvas.badActorHeight = canvas.height * width / canvas.width;
this.canvas.badActorCanvas = canvas.toDataURL('image/png');
} else if (type === 'event') {
this.canvas.eventHeight = canvas.height * width / canvas.width;
this.canvas.eventCanvas = canvas.toDataURL('image/png');
} else if (type === 'tenLowOff') {
this.canvas.tenLowOffHeight = canvas.height * width / canvas.width;
this.canvas.tenLowOffCanvas = canvas.toDataURL('image/png');
}
this.exportPDF();
});
}
private exportPDF(): void {
const PDF = new jsPDF('p', 'mm', 'a4');
if (
this.canvas.monthYearCanvas &&
this.canvas.periodCanvas &&
this.canvas.assetCanvas &&
this.canvas.badActorCanvas &&
this.canvas.badActorCanvas &&
this.canvas.tenLowOffCanvas
) {
PDF.addImage(this.canvas.monthYearCanvas, 'PNG', 1, 10, 208, this.canvas.monthYearHeight);
PDF.addImage(this.canvas.periodCanvas, 'PNG', 1, 125, 208, this.canvas.periodHeight);
PDF.addPage();
PDF.addImage(this.canvas.assetCanvas, 'PNG', 1, 10, 208, this.canvas.assetHeight);
PDF.addPage();
PDF.addImage(this.canvas.badActorCanvas, 'PNG', 1, 10, 208, this.canvas.badActorHeight);
PDF.addPage();
PDF.addImage(this.canvas.eventCanvas, 'PNG', 1, 10, 208, this.canvas.eventHeight);
PDF.addPage('l');
PDF.addImage(this.canvas.tenLowOffCanvas, 'PNG', 1, 10, 208, this.canvas.tenLowOffHeight);
this.messageReport = false;
PDF.save('angular-demo.pdf');
}
}

HighChart and PDF generation

I am trying to generate a PDF from the high-chat graph. The graph renders correctly on the canvas created, but the PDF generated just has a "black" patch.
var trendChart=$("#trendChart").highcharts();
let trendSvgString = trendChart.getSVG({
exporting: {
sourceWidth: trendChart.chartWidth,
sourceHeight: trendChart.chartHeight
}
});
let parser = new DOMParser();
var EXPORT_WIDTH = 1000;
var render_width = EXPORT_WIDTH;
var render_height = render_width * trendChart.chartHeight / trendChart.chartWidth
var canvas = document.createElement('canvas');
canvas.height = render_height;
canvas.width = render_width;
document.body.appendChild(canvas);
var ctx = canvas.getContext("2d");
var image = new Image;
image.onload = function() {
canvas.getContext('2d').drawImage(this, 0, 0, render_width, render_height);
};
image.src = 'data:image/svg+xml;base64,' + window.btoa(trendSvgString);
var dataURL = canvas.toDataURL("image/jpeg");
console.log(dataURL);
var doc = new window.jspdf.jsPDF('p','pt','a4');
doc.addImage(dataURL, 'JPEG', 10, 10, 500, 200);
doc.save('a4.pdf')
console.log('pdf generated');
What could be missing here?

Error on Opening PDF that is generated by JSPDF Image Canvas

I am using the following javascript to take a canvas shot of page and turn it into PDF , however when it saves the file ... I cant open the file in PDF I get the following error "There was an error Processing a Page. There was a PRoblem reading this document(110) " I can open the same file within the browser but not on my computer
function exportPDF() {
var pdf = new jsPDF('l','px'),
source = $('body')[0];
var canvasToImage = function(canvas){
var img = new Image();
var dataURL = canvas.toDataURL('image/png');
img.src = dataURL;
return img;
};
var canvasShiftImage = function(oldCanvas,shiftAmt){
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');
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){
var pdf = new jsPDF('l','px'),
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, 0, null, 'NONE');
totalPdfHeight += (pdfPageHeight * pdfScaleFactor * htmlScaleFactor);
if(totalPdfHeight < htmlPageHeight){
pdf.addPage();
}
safetyNet++;
}
pdf.save(address.innerHTML + 'test.PDF');
};
html2canvas(source, {
onrendered: function(canvas){
canvasToImageSuccess(canvas);
}
});
Please follow the answer on the below git link
https://github.com/MrRio/jsPDF/issues/862

Clearing Stage of as2 Photo Gallery

I'm building a website with several pages on different layers/frames in the timeline. On the "photos" layer, I wrote some code to a load a photo gallery. The problem is that the gallery doesn't disappear when I click on another page and keeps lingering over all the other content. Here is my code. Thanks in advance for any help you can give.
import mx.transitions.Tween;
import mx.transitions.easing.*;
this.createEmptyMovieClip("container",1);
var imagesNumber:Number = 9;
var scrolling:Boolean = true;
for (i=1; i<=imagesNumber; i++) {
container.attachMovie("thumb"+i,"thumb"+i+"_mc",i);
myThumb_mc = container["thumb"+i+"_mc"];
myThumb_mc._x = (i-1)*myThumb_mc._width;
myThumb_mc._y = (Stage.height-myThumb_mc._height)/2;
myThumb_mc._alpha = 50;
myThumb_mc.largerImage = i;
myThumb_mc.onRollOver = function() {
this._alpha = 100;
};
myThumb_mc.onRollOut = function() {
this._alpha = 50;
};
myThumb_mc.onRelease = function() {
this._alpha=50;
for (i=1; i<=imagesNumber; i++) {
var myClip = container["thumb"+i+"_mc"];
myClip.enabled = false;
}
scrolling = false;
_root.attachMovie("image"+this.largerImage,"large_mc",2);
large_mc._x = (Stage.width-large_mc._width)/2;
large_mc._y = (Stage.height-large_mc._height)/2;
new Tween(large_mc, "_alpha", Strong.easeOut, 0, 100, 0.5, true);
new Tween(container, "_alpha", Strong.easeOut, 100, 50, 0.5, true);
large_mc.onRelease = function() {
this.enabled=false;
scrolling = true;
var myFadeOut = new Tween(large_mc, "_alpha", Strong.easeOut, 100, 0, 0.5, true);
new Tween(container, "_alpha", Strong.easeOut, 50, 100, 0.5, true);
myFadeOut.onMotionFinished = function() {
for (i=1; i<=imagesNumber; i++) {
var myClip = container["thumb"+i+"_mc"];
myClip.enabled = true;
}
large_mc.removeMovieClip();
};
};
};
}
container.onEnterFrame = function() {
if (scrolling) {
this._x += Math.cos((-_root._xmouse/Stage.width)*Math.PI)*15;
if (this._x>0) {
this._x = 0;
}
if (-this._x>(this._width-Stage.width)) {
this._x = -(this._width-Stage.width);
}
}
};

Resources