Image canvas toDataURL function is not wokring on ios - 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

Related

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');
}
}

send p5.js image to server

I captured an image from createcapture() through a webcam. Using image(), I got the image onto the canvas. Using saveframes(), and a callback, I was able to send the image to a server, but the image size is very big and I want the image to be 100 x 100 pixels every time whatever may be the size of image from saveframes() before sending it to server.
var x = window.innerWidth * 0.5;
var y = window.innerHeight * 0.75;
function setup()
{
cnv = createCanvas(x, y);
videoInput = createCapture(VIDEO);
videoInput.size(x, y);
videoInput.hide();
}
function draw()
{
if (videoInput) {
image(videoInput, 0, 0, x, y);
}
}
function image()
{
saveFrames('out','png',1,1,
function(im) {
console.log(im);
console.log(typeof im[0]);
// image Data is stored in im[0].imageData
// convert the image to smaller size
data.imageData = im[0].imageData;
// data.imageData = Math.random();
}
);
$.post('addname',data,function(result) {
console.log("data sent", result);
});
}

OpenLayers 3 Shows white space while dragging/panning

I am right now using Ol3 to display static image(like http://openlayers.org/en/latest/examples/static-image.html) . Although when I am zoomed in and start panning/dragging i can see white space as seen in example. I don't want to see that.
Is it possible to pan only till the end of image so that white space does not appear?
You can restrict the dragging of the image by restricting its extent.
Here's an inline link to fiddle.
map.on('moveend', function(evt){
console.log(view.getZoom());
if(view.getZoom()<=2){
view.setZoom(3);
}
});
var constrainPan = function() {
console.log("move");
var extents=[0, 0, 1024, 968]
var visible = view.calculateExtent(map.getSize());
var centre = view.getCenter();
var delta;
var adjust = false;
if ((delta = extents[0] - visible[0]) > 0) {
adjust = true;
//console.log(delta);
centre[0] += delta;
} else if ((delta = extents[2] - visible[2]) < 0) {
adjust = true;
centre[0] += delta;
}
if ((delta = extents[1] - visible[1]) > 0) {
adjust = true;
centre[1] += delta;
} else if ((delta = extents[3] - visible[3]) < 0) {
adjust = true;
centre[1] += delta;
}
if (adjust) {
view.setCenter(centre);
}
};
view.on('change:resolution', constrainPan);
view.on('change:center', constrainPan);

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

(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
}

How to rerender PDF.js page with different scale?

I'm trying just to run the same procedure, but with different scale. But it gives me broken pictures. So what is the correct way to update scale?
function draw(num, scale) {
pdfDoc.getPage(num).then(function(page) {
var viewport = page.getViewport(scale);
var canvas = document.getElementById('the-canvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
}
}
draw(1, 1);
draw(1, 2);

Resources