We can generate and save locally a page as pdf with window.print()
, but I want to know if I can save a page as pdf in a variable, exactly like window.print()
generates a pdf, because I want to send it through ajax after. Thanks.

- 603
- 7
- 8
-
Possible duplicate of [Generate pdf from HTML in div using Javascript](https://stackoverflow.com/questions/18191893/generate-pdf-from-html-in-div-using-javascript) – MTCoster Feb 11 '19 at 17:57
3 Answers
As i can understand your exact need this can be of your help.
HTML
<button onclick="document.getElementById('opepdf').click();">Read PDF</button>
<input id="opepdf" type="file" name="name" style="display: none;" onchange="PDFReader(event);"/>
Javascript
function PDFReader(e){
var file = e.target.files[0];
var pdfReader = new FileReader();// Create a File Reader
pdfReader.readAsText(file,'UTF-8');
pdfReader.onload = readerEvent => {
var PDFContent = readerEvent.target.result;
console.log( PDFContent );//PDF content in variable
}
}
Don't know if this cross browser or not but it does not need any js plugin. More elaborate explanation about how you will be using this can improve the answers. If you want to upload a file through ajax you can use other ways.
EDIT: If you want to send PDF through ajax to your server use:
HTML:
<form>
Select PDF
<input id="opepdf" name="opepdf" type="file" /><br>
<div id="upload"></div><br>
<input type="submit" value="submit"/>
</form>
JAVA-SCRIPT: need jquery
//form Submit
$("form").submit(function(evt){
evt.preventDefault();
$("#upload").html("<img src='http://crabsheet.com/cs/wp-content/uploads/2012/08/capture-1.gif'>");
var formData = new FormData($(this)[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (response) {
$("#upload").html(response);
}
});
return false;
});
PHP-Serverside: there should be a "uploads" folder relative to script dir
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["opepdf"]["name"]);
$fileName = $_FILES['opepdf']['name'];
$fileType = $_FILES['opepdf']['type'];
$fileError = $_FILES['opepdf']['error'];
$fileContent = file_get_contents($_FILES['opepdf']['tmp_name']);
if($fileError == UPLOAD_ERR_OK){
//Processes your file here
if (move_uploaded_file($_FILES["opepdf"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["opepdf"]["name"]). " has been uploaded.";
} else {
echo "Error uploading your file.";
}
}else{
switch($fileError){
case UPLOAD_ERR_INI_SIZE:
$message = 'MAX UPLOAD SIZE Reached';
break;
case UPLOAD_ERR_FORM_SIZE:
$message = 'MAX FORM Upload Size Reached';
break;
case UPLOAD_ERR_PARTIAL:
$message = 'Could not finish Upload';
break;
case UPLOAD_ERR_NO_FILE:
$message = 'NO upload File';
break;
case UPLOAD_ERR_NO_TMP_DIR:
$message = 'Servernot configured for file upload';
break;
case UPLOAD_ERR_CANT_WRITE:
$message= 'CANT WRITE';
break;
case UPLOAD_ERR_EXTENSION:
$message = 'Could not finish Upload.';
break;
default: $message = 'Could not finish Upload';
break;
}
echo json_encode(array(
'error' => true,
'message' => $message
));
}
?>

- 1,118
- 15
- 20
-
2is there any reason to down vote the answer. I dont understand how such people even get reputation to down vote. You can at least politely comment before down voting. – Rajendra Apr 14 '19 at 10:29
You know you can save a web page as pdf with window.print()
so you want to catch the output of window.print() as var in javascript. But that's not your goal, right? Your end goal is to save your Html page as a pdf and send it through ajax. So you need to ask, is there any other way to save my Html page as pdf besides using window.print()
? Now you are on the right track. To convert Html to pdf, you can use jsPDF's .html()
PlugIn and html2canvas 1.0.0-alpha.12
.
<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="~/lib/html2canvas/html2canvas.min.js"></script></script>
<!-- html2canvas 1.0.0-alpha.11 up to v1.0.0-rc.1 works, current version may not work -->
<script>
function emailHtml() {
let pdf = new jsPDF('p', 'pt', 'a4');
pdf.html(document.body, {
callback: function () {
let obj = {};
obj.pdfContent = pdf.output('datauristring');
var jsonData = JSON.stringify(obj);
$.ajax({
url: '/api/yourapi',
type: 'POST',
contentType: 'application/json',
data: jsonData
});
}
});
}
</script>

- 3,669
- 5
- 34
- 56
-
is it possible to get the exact contents of window.print() into a var before using jspdf to output a PDF? Reason: my screen HTML (media=screen) has a lot more styles than the print one (media=print)... – Vinay Jun 29 '21 at 06:52