Html to MS Word using JS without Header and Footer - javascript

I am trying to convert HTML page into MS Word document file with help of below code.
My problem is I don't want any header and footer in it.
I want to create word file without header and footer extra spaces. Content should be sticky to the top.
I am getting the results but I don't want header and footer in it.
function Export2Doc(element, filename = ''){
var preHtml = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40"><head><meta charset="utf-8"><title>Export HTML To Doc</title><style>body,html{margin-top: 0px !important;padding-top: 0px !important;padding-left: 0px !important;margin-left: 0px !important;font-size: 12px;margin-left: 0px !important;}.scheduledtxt{font-size: 14.5px;}table{margin: auto 0px !important;}</head><body>';
var postHtml="</body></html>";
var html = preHtml+document.getElementById(element).innerHTML+postHtml.trim();
var blob = new Blob(['\ufeff', html], {
type: 'application/msword'
});
// Specify link url
var url = 'data:application/msword;charset=utf-8,' + encodeURIComponent(html);
// Specify file name
filename = "test.doc";
// Create download link element
var downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob ){
navigator.msSaveOrOpenBlob(blob, filename);
}else{
// Create a link to the file
downloadLink.href = url;
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
}
document.body.removeChild(downloadLink);
}
<span id="exportContent">
<h2 style="text-align: center;">Test Document</h2>
</span>
<div style="text-align: center;">
<button id="hiddenBtn" style="background: royalblue; color: white;padding: 10px; border-radius: 10px;" onclick="Export2Doc('exportContent', 'word-content');">Export as .doc</button>
</div>

I have manage to achieve my goal with the following link
css print mode: display header and footer only on first page of a generated word doc
I just had to add below css code.
for better understanding just minify entire code and use when converting to the word file.
#page {
size: 2cm 2.7cmt;
margin: 0.4cm 0cm 0cm 0cm;
mso-page-orientation: portrait;
mso-header: none;
mso-footer: none;
}

Related

How to make a download button to get a generated base64 qr code as png

I want to have a download button below a generated qr code. when clicked the qr code should be downloaded.
This is the code that generates the qr code:
<?php echo do_shortcode( '[kaya_qrcode ecclevel="L" size="175" color="#f72a85" bgcolor="#f8f9fa" align="aligncenter" alt="QR Code"]'); ?>
this is how it looks after generated:
<div class="wpkqcg_qrcode_wrapper"><input type="hidden" id="wpkqcg_qrcode_outputimg_8963d44cf5a45de17_ecclevel" value="L"><input type="hidden" id="wpkqcg_qrcode_outputimg_8963d44cf5a45de17_size" value="175"><input type="hidden" id="wpkqcg_qrcode_outputimg_8963d44cf5a45de17_color" value="#f72a85"><input type="hidden" id="wpkqcg_qrcode_outputimg_8963d44cf5a45de17_bgcolor" value="#f8f9fa"><input type="hidden" id="wpkqcg_qrcode_outputimg_8963d44cf5a45de17_content" value="https://profile.url/"><img src="data:image/png;base64,iVBORw0KGg..." id="wpkqcg_qrcode_outputimg_8963d44cf5a45de17" alt="QR Code" class="wpkqcg_qrcode qr-border" style="width: auto; height: auto; max-width: 100%; clear: both; display: block; margin-left: auto; margin-right: auto;"><div style="clear: both;"></div></div>
I tried this approach by adding this script on top of the button that should trigger the download, but it doesn't work:
<script>
document.getElementById("downloadQrCode").addEventListener("click", function(){
var qrcode = document.querySelectorAll("[id^='wpkqcg_qrcode_outputimg_']")[0];
var imageSrc = qrcode.src;
var byteString = atob(imageSrc.split(',')[1]);
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var blob = new Blob([ab], {type: 'image/png'});
var objectURL = URL.createObjectURL(blob);
var link = document.createElement("a");
link.download = "qrcode.png";
link.href = objectURL;
link.click();
});
</script>
<button id="downloadQrCode" class="tb-btn">Download QR Code</button>

Convert html to Image and Download

I would like to convert every message that is received into an image, and with the download button download it. every post is different
This is my .js code
// fetch Messages
function fetchData() {
$('#displayMessages').html('<div class="alert alert-info">Stiamo recuperando i tuoi messaggi!...</div>');
$('#messages').click();
$.ajax({
url: 'controller/fetch_comments.php',
//success
success: function(data){
if (data=='please login') {
window.location='./';
console.log(data);
}
else{
var $fetch ='';
var component ='';
if (/^[\],:{}\s]*$/.test(data.replace(/\\["\\\/bfnrtu]/g, '#').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
data=JSON.parse(data);
console.log(data);
$.each(data, function(i, fetchAll){
var fetchData= data[i];
let message_title = fetchData.message_title ?? ""
$fetch += '<div class="row m-0"> <div class="pull-left alert col-md-2 mb-0"><img src="assets/img/anon.jpg" style=" width: 50px; height: 50px; border-radius:50%; box-shadow: 0 3px 2px rgba(0, 0, 0, 0.3); border: 5px solid #2c2c2c;" class="m-0"></div> <div class="alert col-md-7 m-0" style="margin-left:0px; color:#2c2c2c;"> <b>' +message_title +'</b><br>' +fetchData.description
+'</div> <div class="col-md-3 alert pull-right m-0"><span style="color: black;" class="fa fa-clock m-0"></span><br><text style="color: black; font-size:10px;"> ';
$fetch+=fetchData.date_created+'</text></div></div>';
});
} else {
$fetch +='<div class="alert alert-danger">Ancora nessun messaggio 😒</div>';
console.log(fetch);
$('#displayMessages').html($fetch)
}
$('#displayMessages').html($fetch);
}
}
});
}
this is the php code
$usersObj = new Comments();
$logsObj = new Logs();
$id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 1;
if (empty($id)) {
exit();
}
if ($allComments = $usersObj ->FETCH_COMMENTS($id)) {
$logDescription = 'data fetched!';
$logsObj->INSERT_LOG($id, $logDescription);
}else{
echo 'log failed';
}
echo isset($allComments) ? json_encode($allComments) : 'nothing found';
This is my html in my dashboard, is used to show the message
<div class="tab-pane active" id="home" role="tabpanel">
<div id="displayMessages">
</div>
</div>
I don't understand where I have to act, thanks for the help feel free to edit the code
You could do this as a oneliner in javascript.
Just by using the library html2canvas.
e.g.
html:
<div id="capture" style="padding: 10px; background: #f5da55">
<h4 style="color: #000; ">Hello world!</h4>
</div>
js:
html2canvas(document.querySelector("#capture")).then(canvas => {
document.body.appendChild(canvas)
});
put the image into an a tag with the propertie of "download".
I hope i could help you out.
EDIT:
In your html file add the cdn as following to the head:
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas
/1.4.1/html2canvas.min.js"></script>
then in your js file
const body = document.querySelector("body");
const a_tag = document.createElement("a"); //just create an a tag
a_tag.innerHTML = "download"; //this text is displayed
a_tag.download = "image.png"; //pictures will download as image.png - you can customize the name and file format, but not all formats are acceptet in html2canvas
body.appendChild(a_tag); //append the a tag to the body element, you will need to customize this for your needs
html2canvas(document.querySelector(".wrapper")).then((canvas) => {
canvas.toBlob((blob) => {
const url = URL.createObjectURL(blob); //creates location of image
a_tag.href = url; //append url to a tags href
});
});
You will need this for every Message you receive. After your messages are displayed in the dom as html, the "html2canvas" will create an image out of that. In the "toBlob" function the image is just cached but not showing anywhere. We link the blob url (location of the cached image) to the a tags href. So if we then click on it, it will download. The .wrapper in the html2canvas function i've selected should be your message-div

onclick in the input field type open flmngr window + select the file and add to the input field the url of the file selected

I am looking for help to customise the code when onclick in the input field type open flmngr window + selecting the file and adding to the input field the URL of the file selected
window.onFlmngrAndImgPenLoaded = function() {
var elBtn = document.getElementById("btn");
// Style button as ready to be pressed
elBtn.style.opacity = 1;
elBtn.style.cursor = "pointer";
var elLoading = document.getElementById("loading");
elLoading.parentElement.removeChild(elLoading);
// Add a listener for selecting files
elBtn.addEventListener("click", function() {
selectFiles();
});
}
function selectFiles() {
let flmngr = window.flmngr.create({
urlFileManager: 'https://fm.n1ed.com/fileManager',
urlFiles: 'https://fm.n1ed.com/files'
});
flmngr.pickFiles({
isMultiple: false,
acceptExtensions: ["png", "jpeg", "jpg", "webp", "gif"],
onFinish: function(files) {
showSelectedImage(files);
}
});
}
function showSelectedImage(files) {
let elImages = document.getElementById("images");
elImages.innerHTML = "";
var file = files[0];
let el = document.createElement("div");
el.className = "image";
elImages.appendChild(el);
let elImg = document.createElement("img");
elImg.src = file.url;
elImg.alt = "Image selected in Flmngr";
el.appendChild(elImg);
let elP = document.createElement("p");
elP.textContent = file.url;
el.appendChild(elP);
}
body {
padding: 20px;
background-color: #F4F4F4;
}
#images {
.image {
border: 1px solid #DDD;
box-shadow: 5px 5px 0 0 #DDD;
background-color: white;
padding: 10px;
display: inline-flex;
flex-direction: column;
margin: 0 25px 25px 0;
img {
max-height: 350px;
border: 1px solid #DDD;
}
p {
margin: 5px 0 0 0;
font-size: 14px;
color: #444;
}
}
}
<h1 class="h5 mb-3">Flmngr file manager: select a single image</h1>
<div id="btn" class="btn btn-primary" style="opacity:0.2;cursor:default">Select image...</div>
<div id="loading" style="font-size:12px">Loading file manager...</div>
<h2 class="h5 mt-5">Selected image</h2>
<div id="images">
No image selected yet.
</div>
<script src="https://cloud.flmngr.com/cdn/FLMNFLMN/flmngr.js"></script>
<script src="https://cloud.flmngr.com/cdn/FLMNFLMN/imgpen.js"></script>
I am looking for something like this clicking on the input field open the flmngr file manager, clicking or selecting the file, populate the URL of the file to the input field
<input type="text" name="field_name" id="field_name" value="https://fm.n1ed.com/files/book.png" onclick="BrowseServer('field_name');">
I really appreciate any help.
Thank you
Best Regards
I found a solution to click on the input
window.onFlmngrAndImgPenLoaded = function() {
var elBtn = document.getElementById("FlmngrBrowseServer");
// Style button as ready to be pressed
elBtn.style.opacity = 1;
elBtn.style.cursor = "pointer";
var elLoading = document.getElementById("loadingFlmngrBrowseServer");
elLoading.parentElement.removeChild(elLoading);
// Add a listener for selecting files
elBtn.addEventListener("click", function() {
selectFiles();
});
}
function selectFiles() {
let flmngr = window.flmngr.create({
urlFileManager: 'https://fm.n1ed.com/fileManager',
urlFiles: 'https://fm.n1ed.com/files'
});
flmngr.pickFiles({
isMultiple: false,
acceptExtensions: ["png", "jpeg", "jpg", "webp", "gif"],
onFinish: function(files) {
showSelectedImage(files);
}
});
}
function showSelectedImage(files) {
var file = files[0];
var x = file.url;
document.getElementById("FlmngrBrowseServer").value = x;
}
<input type="text" name="configuration[MODULE_PAYMENT_BTC_IMAGE]" value="images/payment_bitcoin.png" id="FlmngrBrowseServer">
<div id="loadingFlmngrBrowseServer"></div>
<input type="text" name="configuration[MODULE_PAYMENT_BTC_IMAGE]" value="images/payment_bitcoin.png" id="FlmngrBrowseServer1">
<div id="loadingFlmngrBrowseServer1"></div>
<script src="https://cloud.flmngr.com/cdn/FLMNFLMN/flmngr.js"></script>
<script src="https://cloud.flmngr.com/cdn/FLMNFLMN/imgpen.js"></script>
field and select the file then get the URL link and parse to the input field, but I need a solution for 2 or more input fields.

How to upload image file from computer and set as div background image using jQuery?

The HTML code for image file input:
<input type="file" autocomplete="off" name="background-image" accept="image/*" />
The destination div block where I want to dynamically set the background image:
<div class="clock"></div>
The jQuery function I'm currently using for setting image file uploaded as div background image:
$(".background>div>input[type=file]").change(function () {
var fileExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp'];
if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
alert("Only '.jpeg','.jpg', '.png', '.gif', '.bmp' formats are allowed.");
}
else {
$(".clock").css("background-image",'url("' + $(".background>div>input[type=file]").val() + '")');
}
});
The issue is that the background-image is not being set. This may possibly be because when I checked with browser inspector, the file upload is not containing file url.
Note: The background-color of .clock is set to white initially.Also I'd not like to use a server since my intention is to keep it as client side only application.
This may solve your problem
JS FIDDLE
HTML
<input type='file' id='getval' name="background-image" /><br/><br/>
<div id='clock'></div>
CSS
#clock{
background-image:url('');
background-size:cover;
background-position: center;
height: 250px; width: 250px;
border: 1px solid #bbb;
}
PURE JAVASCRIPT
document.getElementById('getval').addEventListener('change', readURL, true);
function readURL(){
var file = document.getElementById("getval").files[0];
var reader = new FileReader();
reader.onloadend = function(){
document.getElementById('clock').style.backgroundImage = "url(" + reader.result + ")";
}
if(file){
reader.readAsDataURL(file);
}else{
}
}
It's small way to do this without using FileReader.
http://jsfiddle.net/PuneetChawla/vqn7r0nj/
HTML
<input type='file' id='getval' name="background-image" onchange="readURL(event)" /><br/><br/>
<div id='clock'></div>
CSS
#clock{
background-image:url('');
background-size:cover;
background-position: center;
height: 250px; width: 250px;
border: 1px solid #bbb;
}
JavaScript
function readURL(event){
var getImagePath = URL.createObjectURL(event.target.files[0]);
$('#clock').css('background-image', 'url(' + getImagePath + ')');
}
Explanation - The URL.createObjectURL() static method creates a DOMString containing an URL representing the object given in parameter.
var loadFile = function(event) {
var output = document.getElementById('output');
output.style.backgroundImage= "url("+URL.createObjectURL(event.target.files[0])+")";
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<input type="file" accept="image/*" onchange="loadFile(event)">
<div style="width: 500px;height: 500px;" id="output"></div>
</body>
</html>

How to pass uploaded pdf file to the variable. (PDF.JS)

Reference : http://git.macropus.org/2011/11/pdftotext/example/
In this project developer has taken a pdf as input and pass it to variable "input". I want to create an upload menu/dropzone so that anyone can upload their pdf and it automatically get passed to the variable "input" and text can be extracted. I am able to upload the file but don't know how to pass that pdf to the variable "input".
<body>
<form id="upload" method="post" action="upload.php" enctype="multipart/form-data">
<div id="drop">
Drop Here
<a>Browse</a>
<input id="inputx" src="./"type="file" name="upl" multiple />
</div>
<ul>
<!-- The file uploads will be shown here -->
</ul>
</form>
Now using this form a pdf will be uploaded now we have to pass it the variable "input ".
<script>
var input = document.getElementById("input");
var processor = document.getElementById("processor");
var output = document.getElementById("output");
window.addEventListener("message", function(event){
if (event.source != processor.contentWindow) return;
switch (event.data){
case "ready":
var xhr = new XMLHttpRequest;
xhr.open('GET', input.getAttribute("src"), true);
xhr.responseType = "arraybuffer";
xhr.onload = function(event) {
processor.contentWindow.postMessage(this.response, "*");
};
xhr.send();
break;
default:
output.innerHTML = event.data.replace(/\s+/g, " ");
break;
}
}, true);
</script>
</body>
You just need to point Pdf.js to the copy of the file you've uploaded.
In your code above, Pdf.js gets its data via an XMLHttpRequest wherein it looks for a .pdf with the file name defined as the src attribute of the element with ID input:
xhr.open('GET', input.getAttribute("src"), true);
If you set the src attribute on this element to the file path of the pdf you've uploaded to the server, then the script should work as-is.
Here's some code that might help you - index.html is a simple file upload form that calls PHP to upload a file into the same directory it (index.html) is served from. file_upload.php saves the uploaded file and sets the value of the src attribute on the iframe with this line:
<iframe id="input" src= <?php print $_FILES['userfile']['name'] ?> ></iframe>
index.html
<html>
<head>
<title>Converting PDF To Text using pdf.js</title>
</head>
<body>
<div>
<!-- the PDF file must be on the same domain as this page -->
<form enctype="multipart/form-data" action="file_upload.php" method="POST">
<input id="fileInput" type="file" name="userfile"></input>
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>
file_upload.php
<?php
$uploadfile = basename($_FILES['userfile']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
<html>
<head>
<title>Converting PDF To Text using pdf.js</title>
<style>
html, body { width: 100%; height: 100%; overflow-y: hidden; padding: 0; margin: 0; }
body { font: 13px Helvetica,sans-serif; }
body > div { width: 48%; height: 100%; overflow-y: auto; display: inline-block; vertical-align: top; }
iframe { border: none; width: 100%; height: 100%; }
#output { padding: 10px; box-shadow: 0 0 5px #777; border-radius: 5px; margin: 10px; }
#processor { height: 70px; }
</style>
</head>
<div>
<!-- embed the pdftotext web app as an iframe -->
<iframe id="processor" src="../"></iframe>
<!-- a container for the output -->
<div id="output"><div id="intro">Extracting text from a PDF file using only Javascript.<br>Tested in Chrome 16 and Firefox 9.</div></div>
</div>
<div>
<iframe id="input" src= <?php print $_FILES['userfile']['name'] ?> ></iframe>
</div>
<script>
var input = document.getElementById("input");
var processor = document.getElementById("processor");
var output = document.getElementById("output");
window.addEventListener("message", function(event){
if (event.source != processor.contentWindow) return;
switch (event.data){
case "ready":
var xhr = new XMLHttpRequest;
xhr.open('GET', input.getAttribute("src"), true);
xhr.responseType = "arraybuffer";
xhr.onload = function(event) {
processor.contentWindow.postMessage(this.response, "*");
};
xhr.send();
break;
default:
output.textContent = event.data.replace(/\s+/g, " ");
break;
}
}, true);
</script>
</body>
</html>

Categories

Resources