Error on Opening PDF that is generated by JSPDF Image Canvas - jspdf

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

Related

Convert dynamic HTML content to pdf on front vuejs issue

I have some trouble how to generate dynamic html content to pdf and have these issues through the implementation.
1- Content are not fit the whole page and had bad oranization on the page
2- The page are not added when have to large content on the page
pdf_statscc(){
var HTML_Width = $("#document").width();
var HTML_Height = $("#document").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($("#document")[0],{allowTaint:true}).then(function(canvas) {
canvas.getContext('2d');
console.log(canvas.height+" "+canvas.width);
var imgData = canvas.toDataURL("image/png");
var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
pdf.addImage(imgData, 'PNG', 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, 'PNG', top_left_margin, -(PDF_Height*i)+(top_left_margin*4),canvas_image_width,canvas_image_height);
}
pdf.save("reportingCC.pdf");
});
Best regard

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?

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

Setting the z-index of loader class

I'm working in Flash AS3, AIR 3.2 for iOS SDK. I'm loading in an image, then applying a shape and textfield over this. But it seems that z-index goes weird with the loader class. At the moment, when this is run, the text and shape is applied first, and the image then gets applied on top of these even though the methods are in a different order. How do I set the shape and text to be above an image that's loaded in from the loader class?
The methods in the main method:
displayImage();
overlayBox();
textAnimation();
These are the methods:
public function displayImage():void {
var imageurl:String = "image.jpg";
myLoader = new Loader();
var fileRequest:URLRequest = new URLRequest(imageurl);
myLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onLoaderProgress);
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaderComplete);
myLoader.load(fileRequest);
}
public function onLoaderProgress(e:ProgressEvent) {
trace(e.bytesLoaded, e.bytesTotal); // this is where progress will be monitored
}
public function onLoaderComplete(e:Event) {
image = new Bitmap(e.target.content.bitmapData);
var imageWidth:Number = image.width;
var imageHeight:Number = image.height;
var resizeWidthVar:Number;
var resizeHeightVar:Number;
trace("Image width: " + image.width);
trace("Image height: " + image.height);
if(imageWidth >= imageHeight) {
resizeHeightVar = imageHeight/displayRes;
trace("resizeHeightVar = " + resizeHeightVar);
imageWidth = imageWidth/resizeHeightVar;
imageHeight = imageHeight/resizeHeightVar;
}
else {
resizeWidthVar = imageWidth/displayRes;
trace("resizeWidthVar = " + resizeWidthVar);
imageWidth = imageWidth/resizeWidthVar;
imageHeight = imageHeight/resizeWidthVar;
}
image.width = imageWidth;
image.height = imageHeight;
trace("Image width: " + image.width);
trace("Image height: " + image.height);
image.x = xScreenPos;
image.y = yScreenPos;
addChild(image); // the image is now loaded, so let's add it to the display tree!
}
public function overlayBox():void {
var overlaySquare:Sprite = new Sprite();
addChild(overlaySquare);
overlaySquare.graphics.beginFill(0x00000, 0.7);
overlaySquare.graphics.drawRect(0, 0, displayRes, displayRes);
overlaySquare.graphics.endFill();
overlaySquare.x = xScreenPos;
overlaySquare.y = yScreenPos;
}
public function textAnimation():void {
//set text format
textFormat.font = "Helvetica Neue Light";
textFormat.size = 12;
textFormat.bold = false;
textFormat.color = 0x000000;
// pass text format
textOne.defaultTextFormat = textFormat;
textOne.text = "Blah blah blah blah";
textOne.autoSize = TextFieldAutoSize.LEFT;
textOne.x = xScreenPos;
textOne.y = yScreenPos;
//add to stage
addChild(textOne);
}
One of the solutions is to replace addChild(image); with the addChildAt(image, 0); another one is to add loader addChild(loader); and don't add image in the complete handler.

Resources