Skip to content

Instantly share code, notes, and snippets.

@andronex
Last active February 16, 2020 00:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andronex/80809f9914a0e8e24a6075f9ff49679f to your computer and use it in GitHub Desktop.
Save andronex/80809f9914a0e8e24a6075f9ff49679f to your computer and use it in GitHub Desktop.
Save page HTML to PDF and some IMAGES and PDF files attachment to results PDF using JavaScript / Сохраняем веб страницу из HTML в PDF и прикрепляем несколько произвольных IMAGE и PDF-файлов к результирующему PDF с помощью JavaScript на стороне клиента
/*
* USE
* <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
* <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js" integrity="sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/" crossorigin="anonymous"></script>
* <script src="https://mozilla.github.io/pdf.js/build/pdf.js"></script>
* and Library https://github.com/CodeSeven/toastr for open modal messages
*/
/****** this in up to code page ******/
var SERT_PDF = [],
DOC_NAME = "{$_modx->resource.alias}"; //name result PDF file
//in foreach iterable
SERT_PDF.push("https://****fasad.ru/certificates/Ceresit/ct19betonkontakt1.pdf");
SERT_PDF.push("https://****fasad.ru/certificates/Ceresit/ct19betonkontakt2.pdf");
SERT_PDF.push("https://****fasad.ru/certificates/Ceresit/ct19betonkontakt3.pdf");
/****** this in up to code page ******/
pdfjsLib.GlobalWorkerOptions.workerSrc = '/js/pdfjs/build/pdf.worker.js'; //local or //mozilla.github.io/pdf.js/build/pdf.worker.js
function getPDF() {
doCanvas();
}
function doCanvas() {
let selector = "article.product";
margins = { w:0, h:0};
if (window.screen.width < 1024) {
selector = ".product__chars";
margins = { w:5, h:10};
html2canvas(document.querySelector('h1'), {
scale: 1
}).then(canvas => {
html2canvas(document.querySelector(selector), {
scale: 1
}).then(canvas2 => {
doPDF(canvas, margins, canvas2);
});
});
}
else{
html2canvas(document.querySelector(selector), {
scale: 1
}).then(canvas => {
doPDF(canvas, margins);
});
}
}
function getImgFromUrl(logo_url, callback) {
var img = new Image();
img.src = logo_url;
img.onload = function () {
var dataURI = getBase64Image(img);
callback(dataURI);
};
}
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/jpeg");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
function getPdfSert(SERT_PDF_index){
url = SERT_PDF[SERT_PDF_index]
var pages = [], heights = [], width = 0, height = 0, currentPage = 1;
scale = 1;
var loadingTask = pdfjsLib.getDocument(url);
loadingTask.promise.then(function(pdf) {
var pages = [], heights = [], width = 0, height = 0, currentPage = 1;
scale = 1;
numPages = pdf.numPages;
currPage = 1;
thePDF = pdf;
pdf.getPage(currPage).then(handlePages);
});
}
function handlePages(page){
console.log("Printing " + currPage);
var viewport = page.getViewport({ scale: scale, });
var canvas = document.createElement('canvas') , ctx = canvas.getContext('2d');
var renderContext = { canvasContext: ctx, viewport: viewport };
canvas.height = viewport.height;
canvas.width = viewport.width;
page.render(renderContext).promise.then(function() {
//pages.push();
ctx.putImageData(ctx.getImageData(0, 0, canvas.width, canvas.height), 0, 0);
var dataURL2 = canvas.toDataURL('image/jpeg');
//console.log(dataURL2);
dataURL2 = dataURL2.replace(/^data:image\/(png|jpg);base64,/, "");
pageHeight= doc.internal.pageSize.height;
//console.log(pageHeight);
doc.addPage();
y = 0
//document.body.appendChild(img);
//var dataURI = getBase64Image(img);
doc.addImage(dataURL2, 'JPEG', margins.w, y, 210, 297);
//console.log(SERT_PDF_index, SERT_PDF_count);
if(currPage == numPages && SERT_PDF_index == SERT_PDF_count){
savePDF();
}
else{
currPage++;
if ( thePDF !== null && currPage <= numPages )
{
thePDF.getPage( currPage ).then( handlePages );
}
else{
SERT_PDF_index = SERT_PDF_index + 1;
getPdfSert(SERT_PDF_index);
}
}
});
}
function savePDF(){
setTimeout(function(){
doc.save(DOC_NAME + '.pdf');
$('.product__chars-download').show();
toastr.clear();
}, 1000);
}
function doPDF(canvas, margins, canvas2) {
doc = new jsPDF({
format: 'a4',
orientation:'p'
});
doc.internal.scaleFactor = 5;
if(canvas2){
doc.addImage(canvas.toDataURL(), 'PNG', margins.w, margins.h);
doc.addImage(canvas2.toDataURL(), 'PNG', margins.w, 60);
}
else{
doc.addImage(canvas.toDataURL(), 'PNG', margins.w, margins.h);
}
var count = $('#product_descr-serfs a img').length;
$('#product_descr-serfs a img').each(function(i){
pageHeight= doc.internal.pageSize.height;
y = 298
if (y >= pageHeight)
{
doc.addPage();
y = 0
}
getImgFromUrl($(this).parent().attr('href'), function(dataURI){
doc.addImage(dataURI, 'JPEG', margins.w, y, 210, 297);
if (i+1 === count) {
SERT_PDF_index = 0;
SERT_PDF_count = (SERT_PDF.length-1);
if(SERT_PDF_count >= 0){
getPdfSert(SERT_PDF_index);
}
else{
savePDF();
}
}
});
});
if(count == 0){
SERT_PDF_index = 0;
SERT_PDF_count = (SERT_PDF.length-1);
if(SERT_PDF_count >= 0){
getPdfSert(SERT_PDF_index);
}
else{
savePDF();
}
}
}
//action click on button
$('.product__chars-download').click(function () {
$('.product__chars-download').hide();
toastr["success"]("<h4>Подождите, пожалуйста, идёт формирование PDF документа!</h4>", "&nbsp;")
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
setTimeout(getPDF(), 500);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment