How to print shipping labels for multiple orders - javascript

Converted html content into image format when html page is loaded, But can't able to convert html content into image when it is called from controller.(For convertion we are using HTML2CANVAS)
This is for a Linux server, PHP 7.2 and Codeigniter 3.1.5
We have found solution for load html page using below function:
In Javascript
$.each(data, function(key,value) { //for select multiple datas
var html = escape(value.design);
var orderid = value.orderid;
var label_height = value.label_height;
var label_width = value.label_width;
$(".temp_div").load("<?php echo base_url();?>orders/downloadcavas?design="+html+"&orderid="+orderid+"&label_width="+label_width+"&label_height="+label_height);
});
In Codeigniter
function downloadcavas()
{
$data1['design'] = $design = urldecode($_GET["design"]);
$data1['orderid'] = $orderid = $_GET["orderid"];
$data1['label_width'] = $label_width = $_GET["label_width"];
$data1['label_height'] = $label_height = $_GET["label_height"];
if(isset($label_height))
{
if(isset($label_width))
{
$style = "height:".$label_height."in;width:".$label_width."in;";
}
else
{
$style = "height:".$label_height."in;";
}
}
else
{
$style = "";
}
echo '<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8" /><link rel="stylesheet" href="'.base_url().'js/jquery-ui.css"><link href="'.base_url().'js/lable_design.css" rel="stylesheet" />
<style>
.canvas-section {
background-color: #fff;
}
</style>
</head>
<body>
<div id="divCanvas" class="canvas-section divCanvas" style="'.$style.'margin-top:-70px;" >'.$design.' </div>
<script type="text/javascript" >$("#preloader").hide();
$.getScript("'.base_url().'js/html2canvas.js");
setTimeout(function(){
preview1();
},1000);
function preview1()
{
var element = $(".divCanvas");
var orderid = "'.$orderid.'";
var scaleBy = 5;
var w = 1000;
var h = 1000;
var div = document.querySelector(".divCanvas");
var canvas = document.createElement("canvas");
canvas.width = w * scaleBy;
canvas.height = h * scaleBy;
canvas.style.width = w + "px";
canvas.style.height = h + "px";
var context = canvas.getContext("2d");
context.scale(scaleBy, scaleBy);
html2canvas(div, {
useCORS: true,
canvas:canvas,
onrendered: function (canvas) {
theCanvas = canvas;
var image = theCanvas.toDataURL("image/jpg");
$.ajax({
url: "'.base_url().'template_builder/template/orderimagesave",
data:"canvas="+image+"&orderid="+orderid,
type: "POST",
cache: false,
global: false,
success: function(data){ }});
}
});
} </script>
</body>
</html>';
}
But we cant able to convert images for continuous html content. Can you please suggest anyother method to convert html content into image without loading html page.
Thanks in advance

Related

Using PDF-Lib to create a document and print without saving the document locally

Within my web application, I am attempting to create a PDF document (which I am doing successfully) and then print it.
Most of the solutions I have found said that you will have to do it server-side probably with some PHP, which would be fine. but If I did that, I would have no clue how to do this.
The application is only really used by one machine and it is not distributed on the web so it is locally hosted only so no need for another end-user computer.
Application Goal / Expected result
I would like the application to:
Generate a PDF based on the user's input (DONE AND WORKS)
Use the PDF and PRINT straight away
EDIT: I have a printer so I do not need a printer on demand
So it appears I would have a few viable options...
PDF-Lib client-side only (possible client-side DB?)
PDF-Lib client-side and a server-side link using PHP?
Fully server-side
A base 64 link?
I have tried locally saving it to the machine and using the file but it will not allow me, unfortunately :(
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get Your Certificate for The Event</title>
<link rel="stylesheet" href="style.css">
<link rel="favicon" href="favicon.ico">
</head>
<body>
<header>
<img src="FR_Logo.png" alt="FRSystems Logo" width="500" height="250" />
<h4>Get your certificate of your laps</h4>
</header>
<main>
<label for="name">Type Your Name</label>
<input required type="text" name="Name" autocomplete="name" placeholder="" id="name" minlength="1"
maxlength="16">
<Button id="submitBtn">Get Certificate</Button>
</main>
<script src="https://unpkg.com/pdf-lib/dist/pdf-lib.js"></script>
<script src="https://unpkg.com/pdf-lib/dist/pdf-lib.min.js"></script>
<iframe id="iframe"></iframe>
<script src="./FileSaver.js"></script>
<script src="https://unpkg.com/#pdf-lib/fontkit#0.0.4"></script>
<script src="./index.js"></script>
</body>
</html>
Index.JS
const userName = document.getElementById("name");
const submitBtn = document.getElementById("submitBtn");
const { PDFDocument, rgb, degrees, StandardFonts } = PDFLib;
const capitalize = (str, lower = false) =>
(lower ? str.toLowerCase() : str).replace(/(?:^|\s|["'([{])+\S/g, (match) =>
match.toUpperCase()
);
submitBtn.addEventListener("click", () => {
const val = capitalize(userName.value);
//check if the text is empty or not
if (val.trim() !== "" && userName.checkValidity()) {
console.log(val);
createPdf(val);
} else {
userName.reportValidity();
}
});
function print() {
var frame = document.getElementById('frame');
frame.contentWindow.focus();
frame.contentWindow.print();
};
function readURL(input) {
console.log("GOT HERE");
// if (input.files && input.files[0]) {
console.log("GOT HERE 2");
var reader = new FileReader();
reader.onload = function (e) {
console.log(e.target.result);
// $('#pdfResult')
// .attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
console.log(reader.readAsDataURL(input.files[0]));
// }
};
async function createPdf(val) {
const pdfDoc = await PDFDocument.create();
const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman);
const page = pdfDoc.addPage();
const { width, height } = page.getSize();
page.setSize(841.89, 595.28)
// midpoint x = 420.945, y= 297.64
console.log(page.getSize(),width,height)
const fontSize = 30
var textWidth = timesRomanFont.widthOfTextAtSize(val, fontSize);
console.log(timesRomanFont.widthOfTextAtSize(val, fontSize))
var textHeight = timesRomanFont.heightAtSize(fontSize);
var nameY = ((page.getHeight() / 2) + 50) - (textHeight / 2);
var centerY = page.getHeight() / 2 - textHeight / 2;
var centerX = page.getWidth() / 2 - textWidth / 2;
page.drawText(val, {
x: centerX,
y: nameY,
size: fontSize,
font: timesRomanFont,
color: rgb(0, 0, 0),
});
var score = "32"; // Would be taken from the database (Select query) using ID/ChipNumber
var scoreString = "who completed " + score + " laps";
var bottomText = "< EVENT NAME > on < LONG DATE >";
var supportingText = "< Support Text >"
var textWidthScoreString = timesRomanFont.widthOfTextAtSize(scoreString, fontSize);
console.log(timesRomanFont.widthOfTextAtSize(scoreString, fontSize));
var scoreY = ((page.getHeight() / 2) + 0) - (textHeight / 2);
var scoreX = page.getWidth() / 2 - textWidthScoreString / 2;
var bottomTextWidthString = timesRomanFont.widthOfTextAtSize(bottomText, fontSize);
var bottomTextY = ((page.getHeight() / 2) - 50) - (textHeight / 2);
var bottomTextX = page.getWidth() / 2 - bottomTextWidthString / 2;
var supportingTextWidthString = timesRomanFont.widthOfTextAtSize(supportingText, fontSize);
var supportingTextY = ((page.getHeight() / 2) - 100) - (textHeight / 2);
var supportingTextX = page.getWidth() / 2 - supportingTextWidthString / 2;
page.drawText(scoreString, {
x: scoreX,
y: scoreY,
size: fontSize,
font: timesRomanFont,
color: rgb(0, 0, 0),
});
page.drawText(bottomText, {
x: bottomTextX,
y: bottomTextY,
size: fontSize,
font: timesRomanFont,
color: rgb(0, 0, 0),
});
page.drawText(supportingText, {
x: supportingTextX,
y: supportingTextY,
size: fontSize,
font: timesRomanFont,
color: rgb(0, 0, 0),
});
const pdfBytes = await pdfDoc.save();
console.log(pdfBytes);
console.log(pdfDoc)
// Create a new file
// This uses File Saver to save the files, i used this to temp save whilst i moved around the text
var file = new File(
[pdfBytes],
"test-Certificate.pdf",
{
type: "application/pdf;charset=utf-8",
}
);
console.log(file);
// var iframe = document.getElementById('iframe');
// iframe.src = file;
// iframe.contentWindow.focus();
// iframe.contentWindow.print();
// readURL(file);
// saveAs(file);
console.log(saveAs(file));
};

How to fetch Google Drive PDF url using pdf.js script on new web page?

I have an example of two websites that uses google drive and whenever they have a new document they just change unique id (drive uploaded document) in URL (after ?id=) and than the documentis display in on a canvas. It's also SEO friendly and indexed by google. So what should be it's raw code?
Demo - Click Here | I want this One {Check Code by Inspect Tool}
Demo Website Image/Inspect code
I just want to use google drive for storage and call document on my website's pdf.js canvas for increase page view, user time, and display ads on PDF web pages like the demo that above.
Here are is the demo for PDF.JS showing PDF in the webpage
var url = 'https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf'; //Loaading the PDF from URL
// Loaded via <script> tag, create shortcut to access PDF.js exports.
var pdfjsLib = window['pdfjs-dist/build/pdf'];
// The workerSrc property shall be specified.
pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';
var pdfDoc = null,
pageNum = 1,
pageRendering = false,
pageNumPending = null,
scale = 0.8,
canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
/**
* Get page info from document, resize canvas accordingly, and render page.
* #param num Page number.
*/
function renderPage(num) {
pageRendering = true;
// Using promise to fetch the page
pdfDoc.getPage(num).then(function(page) {
var viewport = page.getViewport({scale: scale});
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
var renderContext = {
canvasContext: ctx,
viewport: viewport
};
var renderTask = page.render(renderContext);
// Wait for rendering to finish
renderTask.promise.then(function() {
pageRendering = false;
if (pageNumPending !== null) {
// New page rendering is pending
renderPage(pageNumPending);
pageNumPending = null;
}
});
});
// Update page counters
document.getElementById('page_num').textContent = num;
}
/**
* If another page rendering in progress, waits until the rendering is
* finised. Otherwise, executes rendering immediately.
*/
function queueRenderPage(num) {
if (pageRendering) {
pageNumPending = num;
} else {
renderPage(num);
}
}
/**
* Displays previous page.
*/
function onPrevPage() {
if (pageNum <= 1) {
return;
}
pageNum--;
queueRenderPage(pageNum);
}
document.getElementById('prev').addEventListener('click', onPrevPage);
/**
* Displays next page.
*/
function onNextPage() {
if (pageNum >= pdfDoc.numPages) {
return;
}
pageNum++;
queueRenderPage(pageNum);
}
document.getElementById('next').addEventListener('click', onNextPage);
/**
* Asynchronously downloads PDF.
*/
pdfjsLib.getDocument(url).promise.then(function(pdfDoc_) {
pdfDoc = pdfDoc_;
document.getElementById('page_count').textContent = pdfDoc.numPages;
// Initial/first page rendering
renderPage(pageNum);
});
#canvas {
border: 1px solid black;
}
button{
border: none;
background: #000;
color: #fff;
margin: 10px;
padding: 10px;
}
<script src="//mozilla.github.io/pdf.js/build/pdf.js"></script>
<h1>PDF.js Example</h1>
<div>
<button id="prev">Previous</button>
<button id="next">Next</button>
<span>Page: <span id="page_num"></span> / <span id="page_count"></span></span>
</div>
<canvas id="canvas"></canvas>
For more details and documentation visit:
https://mozilla.github.io/pdf.js/getting_started/
Changed pdf URLs to see the result
Tested here:
https://codepen.io/max-makhrov/pen/JjpLxXP
Here're failed URLs:
https://drive.google.com/open?id=1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O
https://drive.google.com/1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O/export?exportFormat=pdf&format=pdf
https://drive.google.com/export?id=1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O
https://drive.google.com/uc?export=download&id=1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O&exportFormat=pdf&format=pdf
https://drive.google.com/uc?export=download&format=pdf&id=1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O
https://drive.google.com/uc?export?format=pdf&id=1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O
https://docs.google.com/viewer?srcid=1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O&pid=explorer&efh=false&a=v&chrome=false&embedded=true
https://drive.google.com/file/d/1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O/
https://drive.google.com/file/export?format=pdf&id=1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O
Here's a surprise: you may use a range from existing Google Sheet if it has an Access. This URL works:
https://docs.google.com/spreadsheets/d/1qNQ6iCMoBCQgJzBB63ymtBQ6BedXZFhjgZZKGItjeVA/export?exportFormat=pdf&format=pdf&size=1.87x1.386&portrait=true&scale=2&top_margin=0&bottom_margin=0&left_margin=0&right_margin=0&sheetnames=false&printtitle=false&horizontal_alignment=LEFT&gridlines=false&fmcmd=12&gid=0&r1=1&r2=7&c1=1&c2=4
I added a demo to load pdf with lazy load. We need to implement drive api to fetch the pdf from drive or it will give cross-origin error.
<!DOCTYPE html>
<html>
<head>
<title>PDF Demo for Qdev</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/pdfjs-dist#2.2.228/build/pdf.min.js"></script>
<style>
body {
margin: 0;
background-color: #dfdfdf; /* Grey background */
}
.center {
text-align: center; /* center pages */
}
</style>
</head>
<body>
<div id="pages" class="center"></div>
<script>
// download the pdf
var pdfTask = pdfjsLib.getDocument("https://atikur-rabbi.github.io/data/sample.pdf");
// parse the get params
var queryString = window.location.hash.split("#")[1];
// default params
var params = {pg: 1};
var pagen = 0;
// if get params are present
if (queryString) {
// update the default settings
params = Object.assign(params, parseParams(queryString));
}
// Load the pages div from the DOM
var pages = document.getElementById("pages");
// handle the pdf once loaded (asyncronous)
pdfTask.promise.then(function(pdf) {
// globalize pdf
window.pdf = pdf;
// load the first page
loadPage(pdf, parseInt(params.pg));
pagen++;
});
// stores the page number of the page currently in the viewport
var curpage = parseInt(params.pg) + pagen;
// every half a second, check for scroll updates
setInterval(function() {
// if we're within 200px of the bottom of the page
if (document.body.scrollHeight - (window.scrollY + window.innerHeight) < 200) {
if (window.pdf != undefined) {
// load 5 more pages
for (var i=0; i<5; i++) {
loadPage(pdf, parseInt(params.pg)+pagen);
pagen++;
}
}
}
// if the page in our viewport has changed, update the url
if (curpage != parseInt(params.pg) + parseInt(window.scrollY /
(document.body.scrollHeight / pagen))) {
curpage = parseInt(params.pg) + parseInt(window.scrollY /
(document.body.scrollHeight / pagen));
window.location.hash = "#pg=" + curpage;
}
}, 500);
// render `pg` from `pdf` and append it to the pages div
function loadPage(pdf, pg){
pdf.getPage(pg).then(function(page){
var scale = 1.7;
var viewport = page.getViewport({scale: scale});
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
canvas.id = "page-" + pg;
canvas.height += viewport.height;
canvas.width = viewport.width;
pages.appendChild(canvas);
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
});
}
// parses get params from a query string into an object
function parseParams(queryString) {
var query = {};
var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
}
return query;
}
</script>
</body>
</html>

PDF.js get images of one page and display them as HTML

according to this: [Extract images from PDF file with JavaScript
I tried to filter the JPEG images from PDF. It works in the way, that I get the name of the images of one page in an array.
What I want to do: Display the images next to the PDF as HTML . The solution mentioned above doesn't work, I do not know, how to get the image itself and not just the name.
<script type="text/javascript" src="pdf.js"></script>
<script type="text/javascript">
PDFJS.workerSrc = "/path/to/pdf.worker.js";
</script>
<div>
<button id="prev">Previous</button>
<button id="next">Next</button>
<span>Page: <span id="page_num"></span> / <span id="page_count"></span></span>
</div>
<canvas id="the-canvas" style="width: 500px;"></canvas>
<div id="images"></div>
<script type="text/javascript">
PDFJS.workerSrc = "pdf.worker.js";
</script>
<script src="js.js"></script>
js.js:
// URL of PDF document
var url = "test/pdf_one.pdf";
var pageNum = 11;
var pageCount = 0;
loadPage(pageNum);
function loadPage(number){
// Asynchronous download PDF
PDFJS.getDocument(url)
.then(function(pdf) {
pageCount = pdf.numPages;
document.getElementById("page_num").innerHTML = "" + pageNum;
document.getElementById("page_count").innerHTML = "" + pageCount;
return pdf.getPage(number);
})
.then(function(page) {
// Set scale (zoom) level
var scale = 1.5;
// Get viewport (dimensions)
var viewport = page.getViewport(scale);
// Get canvas#the-canvas
var canvas = document.getElementById('the-canvas');
// Fetch canvas' 2d context
var context = canvas.getContext('2d');
// Set dimensions to Canvas
canvas.height = viewport.height;
canvas.width = viewport.width;
// Prepare object needed by render method
var renderContext = {
canvasContext: context,
viewport: viewport
};
// Render PDF page
page.render(renderContext);
getImages(page);
});
}
function getImages(page){
var test = [];
page.getOperatorList().then(function (ops) {
for (var i=0; i < ops.fnArray.length; i++) {
if (ops.fnArray[i] == PDFJS.OPS.paintJpegXObject) {
console.log(ops.argsArray[i][0]);
document.getElementById("images").innerHTML = "<img src='"+ops.argsArray[i][0]+".jpg'>";
test.push(ops.argsArray[i][0])
}
}
});
console.log(test);
if(pageNum === 13){
console.log("IMAGES");
console.log(test[0]);
document.getElementById("images").innerHTML = "<img src='"+test[0]+".jpg'>";
}
}
document.getElementById('prev').addEventListener('click', onPrevPage);
document.getElementById('next').addEventListener('click', onNextPage);
function onNextPage() {
if (pageNum >= pageCount) {
return;
}
pageNum++;
document.getElementById("page_num").innerHTML = "" + pageNum;
loadPage(pageNum);
}
function onPrevPage() {
if (pageNum <= 1) {
return;
}
pageNum--;
document.getElementById("page_num").innerHTML = "" + pageNum;
loadPage(pageNum);
}

For Loop - Changing src every loop

I'm trying to load pdfs and render every single page into a canvas.
It works when I'm only loading a one paged .pdf but not when I'm using a multiple page .pdf
The for-loop is supposed to run as often as there are pages in the pdf,
var total =
Every loop I'm creating a
<canvas class=''></canvas>
which should have the matching page number as class.
can.className = 'pdfpage' + i
But for some reason it always gets the total page count as class. E.g. when loading a five paged .pdf it creates...
<canvas class='pdfpage5'></canvas>
...5 times and not 'pdfpage0', 'pdfpage1', etc.
I'm pretty new to JS so I'm not exactly sure if I'm thinking in the right direction with 'i'. I added
console.log('i is: ' + i);
to confirm that i really adds +1 every turn.
<script src="http://cdnjs.cloudflare.com/ajax/libs/processing.js/1.4.1/processing-api.min.js"></script>
<script src="http://html2canvas.hertzen.com/build/html2canvas.js"></script>
<script type="text/javascript" src="https://rawgithub.com/mozilla/pdf.js/gh-pages/build/pdf.js"></script>
<script type="text/javascript" src='./jsPDF/jspdf.js'></script>
<script src="./jsPDF/plugins/addimage.js"></script>
<script src="./jsPDF/plugins/png_support.js"></script>
<script src="./jsPDF/plugins/canvas.js"></script>
<script type="text/javascript" src='./FileSaver.js-master/FileSaver.js'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://rawgithub.com/mozilla/pdf.js/gh-pages/build/pdf.js"></script>
<div id='1'>
<input id='pdf' type='file'/>
<script type="text/javascript">
PDFJS.disableWorker = true;
var pdf = document.getElementById('pdf');
pdf.onchange = function(ev) {
if (file = document.getElementById('pdf').files[0]) {
fileReader = new FileReader();
fileReader.onload = function(ev) {
console.log(ev);
PDFJS.getDocument(fileReader.result).then(function getPdfHelloWorld(pdf) {
var total = pdf.numPages;
for (var i = 0; i < total; i++) {
console.log('i is: ' + i);
console.log('total pages: ' + total);
//
// Fetch the first page
//
console.log(pdf)
pdf.getPage(i + 1).then(function getPageHelloWorld(page) {
var scale = 1.0;
var viewport = page.getViewport(scale);
//
// Prepare canvas using PDF page dimensions
//
var div = document.getElementById('1');
var can = document.createElement('canvas');
can.className = 'pdfpage' +i;
div.appendChild(can);
canvas = document.getElementsByClassName('pdfpage' +i);
var context = canvas[0].getContext('2d');
canvas[0].height = viewport.height;
canvas[0].width = viewport.width;
//
// Render PDF page into canvas context
//
var task = page.render({canvasContext: context, viewport: viewport})
task.promise.then(function(){
console.log(canvas[0].toDataURL('image/jpeg'));
var dataURL = canvas[0].toDataURL('image/jpeg');
});
});
}
}, function(error){
console.log(error);
});
};
fileReader.readAsArrayBuffer(file);
}
}
</script>
</div>
Try this, it should add the required the classnames
<script src="http://cdnjs.cloudflare.com/ajax/libs/processing.js/1.4.1/processing-api.min.js"></script>
<script src="http://html2canvas.hertzen.com/build/html2canvas.js"></script>
<script type="text/javascript" src="https://rawgithub.com/mozilla/pdf.js/gh-pages/build/pdf.js"></script>
<script type="text/javascript" src='./jsPDF/jspdf.js'></script>
<script src="./jsPDF/plugins/addimage.js"></script>
<script src="./jsPDF/plugins/png_support.js"></script>
<script src="./jsPDF/plugins/canvas.js"></script>
<script type="text/javascript" src='./FileSaver.js-master/FileSaver.js'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://rawgithub.com/mozilla/pdf.js/gh-pages/build/pdf.js"></script>
<div id='1'>
<input id='pdf' type='file'/>
<script type="text/javascript">
PDFJS.disableWorker = true;
var pdf = document.getElementById('pdf');
pdf.onchange = function(ev) {
if (file = document.getElementById('pdf').files[0]) {
fileReader = new FileReader();
fileReader.onload = function(ev) {
console.log(ev);
PDFJS.getDocument(fileReader.result).then(function getPdfHelloWorld(pdf) {
var total = pdf.numPages;
for (var i = 0; i < total; i++) {
console.log('i is: ' + i);
console.log('total pages: ' + total);
//
// Fetch the first page
//
console.log(pdf)
pdf.getPage(i + 1).then(function getPageHelloWorld(page) {
var scale = 1.0;
var viewport = page.getViewport(scale);
//
// Prepare canvas using PDF page dimensions
//
var div = document.getElementById('1');
var can = document.createElement('canvas');
can.className = 'pdfpage' +(page.pageIndex + 1);
div.appendChild(can);
canvas = document.getElementsByClassName('pdfpage' +(page.pageIndex + 1));
var context = canvas[0].getContext('2d');
canvas[0].height = viewport.height;
canvas[0].width = viewport.width;
//
// Render PDF page into canvas context
//
var task = page.render({canvasContext: context, viewport: viewport})
task.promise.then(function(){
console.log(canvas[0].toDataURL('image/jpeg'));
var dataURL = canvas[0].toDataURL('image/jpeg');
});
});
}
}, function(error){
console.log(error);
});
};
fileReader.readAsArrayBuffer(file);
}
}
</script>
</div>
Basically, all I have done is replace i with page.pageIndex +1 in the callback function

When calling canvas.toDataURL, why is the part from rasterizeHTML.drawHTML black?

I have a button and when it is pressed it calls common_save_project(). What happens right now is the canvas is produced correctly on the screen, but the image that is created by canvas.toDataURL is black where rasterizeHTML.drawHTML was called. I am using http://cburgmer.github.io/rasterizeHTML.js/.
Here is the relevant code:
function common_save_project()
{
var image = common_screenshot();
$.ajax
(
{
type: "POST",
processData: false,
url: SITE_URL + "/system/xml/import/" + app_type + "/" + session_id + "/?prjid=" + project_id,
data: "xml=" + common_order_xml + "&prodid=" + product_id + "&file=" + image.src
}
).done(function( msg )
{
console.log("Project saved. " + msg);
});
}
function common_screenshot()
{
var canvas = document.getElementById("save_image_canvas");
var ctx = canvas.getContext('2d');
if (typeof(moulding_canvas) === "undefined")
{
canvas.height = parseInt($("#matte_canvas").height());
canvas.width = parseInt($("#matte_canvas").width());
}
else
{
canvas.height = parseInt($("#moulding_canvas").height());
canvas.width = parseInt($("#moulding_canvas").width());
}
canvas.style.backgroundColor = "#FFFFFF";
var moulding_top = 0;
var moulding_left = 0;
if (document.getElementById("moulding_canvas"))
{
moulding_top = -1 * parseInt(document.getElementById("moulding_canvas").style.top);
moulding_left = -1 * parseInt(document.getElementById("moulding_canvas").style.left);
}
var mattes_html = document.getElementById("mattes").innerHTML;
mattes_html = mattes_html.replace(/<\/?script\b.*?>/g, "");
mattes_html = mattes_html.replace(/ on\w+=".*?"/g, "");
rasterizeHTML.drawHTML(mattes_html).then(function (renderResult)
{
ctx.drawImage(renderResult.image, moulding_left, moulding_top);
});
ctx.drawImage(matte_canvas, moulding_left, moulding_top);
if (typeof(moulding_canvas) !== "undefined")
{
ctx.drawImage(moulding_canvas, 0, 0);
}
var image = new Image();
image.src = canvas.toDataURL("image/jpeg");
return image;
}
Original:
After rasterizeHTML.drawHTML:
Final result (after canvas.toDataURL):
It will work fine if you will re-declare the canvas again for saving.
Try this:
<script type="text/javascript">
var canvas = document.getElementById("canvas");
rasterizeHTML.drawHTML('<h1>hello Im here</h1>Some <span style="color: green; font-size: 20px;">HTML</span>', canvas);
$('#saveImg').click(function(){
var canvas = document.getElementById("canvas");
var dataURL = canvas.toDataURL("image/png");
window.open(dataURL, "toDataURL() image", "width=600, height=200");
});
</script>

Categories

Resources