I'm not a massive javascript/jquery user but I've started to get more into it for use in mobile apps... I've been looking for an answer to solve my problem of getting a blank page when trying to output html as a pdf using jspdf and every post I find has something to do with blobs.
this is my code I have that exports a blank pdf I have left the pdf.save in so I get an export on my PC as a sample of what it should look like but on my ipad and nexus 7 it saves a blank pdf.
var pdf = new jsPDF('p', 'pt', 'letter'), source = $('#home')[0], specialElementHandlers = {
'#bypassme': function(element, renderer){
return true
}
}
margins = {top: 80,bottom: 60,left: 40,width: 522};
pdf.fromHTML(source, margins.left, margins.top, {
'width': margins.width // max width of content on PDF
, 'elementHandlers': specialElementHandlers
},
function (dispose) {
pdf.save('home.pdf');
console.log( pdfOutput );
var pdfOutput = doc.output();
console.log("file system - ");
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
console.log(fileSystem.name);
console.log(fileSystem.root.name);
console.log(fileSystem.root.fullPath);
fileSystem.root.getFile("test.pdf", {create: true}, function(entry) {
var fileEntry = entry;
console.log(entry);
entry.createWriter(function(writer) {
writer.onwrite = function(evt) {
alert("write success");
};
console.log("writing to file");
writer.write( pdfOutput );
}, function(error) {
console.log(error);
});
}, function(error){
console.log(error);
});
},
function(event){
console.log( evt.target.error.code );
});
},
margins
)
Could someone give me a tip or point me in the right direction on how to incorporate your solution into my coding so I can save html formatting & images?
I just had this same issue.
Here's what I did to solve it.
Replace the line
writer.write( pdfOutput );
with this:
var data = pdfOutput;
var buffer = new ArrayBuffer(data.length);
var array = new Uint8Array(buffer);
for (var i = 0; i < data.length; i++) {
array[i] = data.charCodeAt(i);
}
writer.write(buffer);
Not 100% sure that I understand what's happening, but from what I have been researching, you need to convert the output from jsPDF to an ArrayBuffer before writing to the file.
#AdilWaqar I apologise for the delay in my response, I have been moving house. Below I have included the full javascript I finished on to get pdf printing working. it works perfect in android & IOS but the issue with IOS is that once the pdf has been generated you cannot gain access to it via a file manager.
The localStorage was used for storage before output, it has same id name on the span fields in the output html for that specific section, for example section 3 in the javascript had some signatures and some text boxes to output, the localStorage for one textfield in the output is...
getItem('cwiRiskAccesAsessName')
the html output is...
<tr><td>Assessor Name:</td><td><span id="EXPcwiRiskAccesAsessName"></span></td></tr>
I used jquery to pre-populate the span fields by building the html ready for output and adding a prefix to the id of each item, once done I used this simple line to deal with auto population on keyup. note: ignore 'inpt' in onkeyup, that was for a prefix within another part of the data handling function
onKeyUp="dataHandling(this,1,'inpt');"
var saveData = localStorage.setItem(source.id,source.value);var getData = localStorage.getItem(source.id);$("#EXP"+source.id).text(getData);
Below is the full pdf output javascript
/* STORAGE-OUTPUT */
function storageOutput(){for (var i = 0; i < localStorage.length; i++){
/* do something with localStorage.getItem(localStorage.key(i));*/
$("#storageHolder").append(localStorage.key(i)+'<br/>');}
}
/* SETUP */
function setup(){
window.requestFileSystem(LocalFileSystem.PERSISTENT,0,onRequestFileSystemSuccess,null);
function onRequestFileSystemSuccess(fileSystem){
var entry=fileSystem.root;entry.getDirectory("MAIN-DIRECTORY",{create:true,exclusive:false},onGetDirectorySuccess,onGetDirectoryFail);
}
function onGetDirectorySuccess(dir){}
function onGetDirectoryFail(error){
alert('Directory Setup Fail');}
}/*CLEAR LOCALSTORAGE*/function clearLS(){
localStorage.clear();alert(localStorage.length);
}
function savePDF(id,filename) {
var folderName = 'MAIN-DIRECTORY/'+localStorage.getItem('householderAddress')+', '+localStorage.getItem('householderPostcode');
var saveData = localStorage.setItem('saveLocation',folderName);
var getData = localStorage.getItem('saveLocation');
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onRequestFileSystemSuccess, null);
function onRequestFileSystemSuccess(fileSystem) {
var entry=fileSystem.root;
entry.getDirectory(getData, {create: true, exclusive: false}, onGetDirectorySuccess, onGetDirectoryFail);
}
function onGetDirectorySuccess(dir){}
function onGetDirectoryFail(error){}
if(id==1){
var pdf = new jsPDF('p', 'pt', 'a4'),source = $('#savesec1')[0]
, specialElementHandlers = {
'#bypassme': function(element, renderer){
return true
}
}
} else if (id==2){
var pdf = new jsPDF('p', 'pt', 'a4'),source = $('#savesec2')[0]
, specialElementHandlers = {
'#bypassme': function(element, renderer){
return true
}
}
} else if (id==3){
var pdf = new jsPDF('p', 'pt', 'a4'),source = $('#savesec3')[0]
, specialElementHandlers = {
'#bypassme': function(element, renderer){
return true
}
}
}
margins = {top: 40,bottom: 60,left: 40,width: 522};
pdf.fromHTML(source, margins.left, margins.top, {
'width': margins.width // max width of content on PDF
, 'elementHandlers': specialElementHandlers
},
function(dispose){
/*SECTION 2*/
if(id==2){
pdf.addImage(localStorage.getItem('householderSig1'),'PNG',135,270,150,50);pdf.addImage(localStorage.getItem('assessSig1'),'PNG',135,410,150,50);
}
/*SECTION 3*/
else if(id==3){
pdf.addPage();pdf.setFontSize(15);pdf.setFontType("normal");pdf.text(20,30,'Assessor Name: '+localStorage.getItem('cwiRiskAccesAsessName'));pdf.text(20,45,'Assessor Agency: '+localStorage.getItem('cwiRiskAccesAsessAgency'));pdf.text(20,60, 'Date: '+localStorage.getItem('assessSig3Date'));pdf.text(20,75, 'Assessor Signature: ');pdf.addImage(localStorage.getItem('assessSig3'),'PNG',20,85,250,100);pdf.addPage();pdf.setFontSize(25);pdf.setFontType("normal");pdf.text(20,40,'Plan View:');pdf.addImage(localStorage.getItem('drawingOutput'),'PNG',20,40,500,500);pdf.addPage();pdf.setFontSize(15);pdf.setFontType("normal");pdf.text(20,30,'Front Elevation: '+localStorage.getItem('cwiRiskFrontNotes'));pdf.text(20,430,'Rear Elevation: '+localStorage.getItem('cwiRiskRearNotes'));pdf.addImage(localStorage.getItem('cwiRiskFrontOutput'),'PNG',40,40,500,350);pdf.addImage(localStorage.getItem('cwiRiskRearOutput'),'PNG', 40, 440, 500, 350);pdf.addPage();pdf.setFontSize(15);pdf.setFontType("normal");pdf.text(20,30,'Left Side Elevation: '+localStorage.getItem('cwiRiskLeftNotes'));pdf.text(20,430,'Right Side Elevation: '+localStorage.getItem('cwiRiskRightNotes'));pdf.addImage(localStorage.getItem('cwiRiskLeftOutput'),'PNG',40,40,500,350);pdf.addImage(localStorage.getItem('cwiRiskRightOutput'),'PNG',40,440,500,350);
}
/* GENERIC IMAGE OUTPUT
pdf.addImage(imgData, 'PNG', 40, 400, 400, 160);
pdf.addImage(imgData, 'PNG', 40, 600, 400, 160);
for (var i=0;i<dataSources.length;i++){
pdf.addPage();
alert(dataSources[i].text);
}
pdf.save(filename+'.pdf');*/
var pdfOutput = pdf.output();
//console.log( pdfOutput );
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
fileSystem.root.getFile(getData+'/'+filename+'.pdf', {create: true}, function(entry) {
var fileEntry = entry;
//console.log(entry);
entry.createWriter(function(writer) {
writer.onwrite = function(evt) {
alert("PDF Saved Successfully");
};
console.log("writing to file");
var data = pdfOutput;
var buffer = new ArrayBuffer(data.length);
var array = new Uint8Array(buffer);
for (var i = 0; i < data.length; i++) {
array[i] = data.charCodeAt(i);
}
writer.write(buffer);
}, function(error) {
alert(error);
});
}, function(error){
console.log(error);
});
},
function(event){
console.log( evt.target.error.code );
});
},
margins
)
}
Related
I am using dropzone to upload files to a server. When the use adds files to the dropzone, they have the option to alter the name of the file. For example; instead of D6282238752Q82.png, the file will be saved as Dog.png .
This is my code:
<script type="text/javascript">
Dropzone.autoDiscover = false;
var previewNode = document.querySelector("#template");
previewNode.id = "";
var previewTemplate = previewNode.parentNode.innerHTML;
previewNode.parentNode.removeChild(previewNode);
var myDropzone = new Dropzone('div#mydropzone', { // Make the whole body a dropzone
url: "/Upload.aspx?no=<%= Request.QueryString["no"] %>", // Set the url
parallelUploads: 10,
thumbnailWidth: 150,
thumbnailHeight: 80,
uploadMultiple: true,
previewTemplate: previewTemplate,
autoProcessQueue: false,
acceptedFiles: "image/*,application/pdf,.doc,.docx,.xls,.xlsx,.csv,.tsv,.ppt,.pptx,.pages,.odt,.rtf",
previewsContainer: "#previews", // Define the container to display the previews
clickable: [".fileinput-button", ".upload-drop-zone"], // Define the element that should be used as click trigger to select files.
init: function() {
var submitButton = document.querySelector("#submit-all")
myDropzone = this;
},
});
myDropzone.on("addedfile", function (file) {
// Hookup the start button
var filename = file.name;
var extension = filename.split('.').pop();
file.previewElement.querySelector("#txtNewFileName").value = filename.substr(0, filename.lastIndexOf('.'));
file.previewElement.querySelector("#txtFileExtension").innerHTML = filename.split('.').pop().toUpperCase();
var submitButton = document.querySelector("#submit-all")
submitButton.classList.remove("invisible");
submitButton.classList.add("visible");
});
// Update the total progress bar
myDropzone.on("totaluploadprogress", function (progress) {
document.querySelector("#total-progress .progress-bar").style.width = progress + "%";
});
myDropzone.on("sending", function (file, xhr, formData) {
// Show the total progress bar when upload starts
document.querySelector("#total-progress").style.opacity = "1";
var filename = file.name;
var extension = filename.split('.').pop();
var newFilename = file.previewElement.querySelector("#txtNewFileName").value + '.' + extension;
formData.append("newFileName", newFilename);
});
myDropzone.on("processing", function () {
myDropzone.options.autoProcessQueue = true;
});
// Hide the total progress bar when nothing's uploading anymore
myDropzone.on("queuecomplete", function (sending, progress) {
document.querySelector("#total-progress").style.opacity = "0";
});
myDropzone.on("success", function (progress, file) {
var submitButton = document.querySelector("#submit-all")
submitButton.classList.remove("visible");
submitButton.classList.add("invisible");
var refreshButton = document.getElementById("<%= btnRefresh.ClientID %>");
refreshButton.click();
});
myDropzone.on("removedfile", function (file) {
//post request to remove file from server
$.post("/Upload.aspx?no=<%= Request.QueryString["no"] %>&delete=" + file.newName);
var refreshButton = document.getElementById("<%= btnRefresh.UserID %>");
refreshButton.click();
});
myDropzone.on('dragover', function (e) {
this.className = 'upload-drop-zone drop';
return false;
})
$(document).on('click', '#submit-all', function (file) {
myDropzone.processQueue();
});
</script>
It works fine on Chrome, Edge and android, but not on Iphone or Ipad. I have tried to find an answer online, but to no avail.
I found an answer that helped me, in case anyone has the same problem.
I couldn't find a way to solve it in dropzone, so opted for C# instead. I used a $POST method to change the filenames.
$(document).on('click', '#submit-all', function (file) {
myDropzone.processQueue();
var newFilenames = [...document.querySelectorAll("#txtNewFileName")].map(sel => sel.value).join(',');
$.post("/Upload.aspx?no=<%= Request.QueryString["no"] %>&rename=" + newFilenames);//changeFileNames);
});
In Upload.aspx.cs I have the following code:
if (!String.IsNullOrEmpty(Request.QueryString["rename"]))
{
string renameF = Request.QueryString["rename"];
string[] renames = renameF.Split(',');
var di = new DirectoryInfo(fileArchivePath);
var filess = di.GetFiles().OrderByDescending(d => d.LastWriteTime).ToArray();
int count = 0;
foreach (string name in renames)
{
string inn = filess[count].FullName;
string ext = filess[count].Extension;
string ny = name + ext;
string inDir = Path.Combine(fileArchivePath, inn);
string nynavn = Path.Combine(fileArchivePath, ny);
if (File.Exists(inDir))
{
File.Copy(inDir, nynavn, true);
File.Delete(inDir);
}
count++;
}
return;
}
I already have code that uploads the files, but the additional Post method changes the existing filenames.
I am trying to upload an image file from Apex File browser, as image files are huge so I am using a Chunked upload technique to upload an image into the database. Everything is working fine as the chunked file is being used in Apex Collections to pass in ajax call back process to update in the database. Here is my code in javascript to Upload image as chunked
var fileInputElem = document.getElementById('P130_FILE_UPLOAD');
var fileIndex = 0;
// builds a js array from long string
function clob2Array(clob, size, array) {
loopCount = Math.floor(clob.length / size) + 1;
for (var i = 0; i < loopCount; i++) {
array.push(clob.slice(size * i, size * (i + 1)));
}
return array;
}
// converts binaryArray to base64 string
function binaryArray2base64(int8Array) {
var data = "";
var bytes = new Uint8Array(int8Array);
var length = bytes.byteLength;
for (var i = 0; i < length; i++) {
data += String.fromCharCode(bytes[i]);
}
return btoa(data);
}
// a recursive function that calls itself to upload multiple files synchronously
function uploadFile(pFileIndex) {
var file = fileInputElem.files[pFileIndex];
var reader = new FileReader();
reader.onload = (function(pFile) {
return function(e) {
if (pFile) {
var base64 = binaryArray2base64(e.target.result);
var f01Array = [];
f01Array = clob2Array(base64, 30000, f01Array);
apex.server.process(
'UPLOAD_FILE',
{
x01: file.name,
x02: file.type,
f01: f01Array
},
{
dataType: 'json',
success: function(data) {
if (data.result == 'success') {
fileIndex++;
if (fileIndex < fileInputElem.files.length) {
// start uploading the next file
uploadFile(fileIndex);
} else {
// all files have been uploaded at this point
spinner.stop();
fileInputElem.value = '';
$('#uploadedFilesRpt').trigger('apexrefresh');
}
} else {
alert('Oops! Something went terribly wrong. Please try again or contact your application administrator.');
}
}
}
);
}
}
})(file);
reader.readAsArrayBuffer(file);
}
// variables for spin.js
var spinner;
var spinTargetElem = document.getElementById('wwvFlowForm');
var spinOptions = {
lines: 13
, length: 28
, width: 14
, radius: 42
, scale: 1
, corners: 1
, color: '#000'
, opacity: 0.25
, rotate: 0
, direction: 1
, speed: 1
, trail: 60
, fps: 20
, zIndex: 2e9
, className: 'spinner'
, top: '50%'
, left: '50%'
, shadow: false
, hwaccel: false
, position: 'absolute'
}
Ajax Call back to Process at the Server level
declare
lco_collection_name constant apex_collections.collection_name%type := 'UPLOADED_FILES';
l_blob blob;
l_filename varchar2(200);
l_mime_type varchar2(200);
l_token varchar2(32000);
begin
l_filename := apex_application.g_x01;
l_mime_type := nvl(apex_application.g_x02, 'application/octet-stream');
-- build BLOB from f01 30k array (base64 encoded)
dbms_lob.createtemporary(l_blob, false, dbms_lob.session);
for i in 1 .. apex_application.g_f01.count loop
l_token := wwv_flow.g_f01(i);
if length(l_token) > 0 then
dbms_lob.append(
dest_lob => l_blob,
src_lob => to_blob(utl_encode.base64_decode(utl_raw.cast_to_raw(l_token)))
);
end if;
end loop;
-- add collection member (only if BLOB is not null)
if dbms_lob.getlength(l_blob) is not null then
apex_collection.add_member(
p_collection_name => lco_collection_name,
p_c001 => l_filename,
p_c002 => l_mime_type,
p_blob001 => l_blob
);
end if;
apex_json.open_object;
apex_json.write(
p_name => 'result',
p_value => 'success'
);
apex_json.close_object;
exception
when others then
apex_json.open_object;
apex_json.write(
p_name => 'result',
p_value => 'fail'
);
apex_json.close_object;
end;
The only thing I want to resize the uploaded image like if the size is more than 800x600 then it should be resized to 800x600 at client-side, not on the server-side. Please suggest some best way how I can resize an image in my javascript code.
I have a button in my page to generate PDF I use JSPDF to perform the task, my problem is that I have to retrieve the content in other pages ... I retrieve the html in string format and I do not Know how to handle it....
any ideas
Thank you
jQuery(document).ready(function () {
var inner_content1;
var page_title = "ExternalPage";
$.ajax({
url: "https://site.sharepoint.com/sites/sites/site/_api/web/Lists/getbytitle('Pages')/items?$filter=Title eq '" + page_title +"'",
type: "GET",
headers: {
"ACCEPT": "application/json;odata=verbose"
},
success: function (data) {
if (data.d.results[0]) {
inner_content1 = data.d.results [0].HtmlContenu;
str = "<div id='someID'>" + inner_content1 + "<div/>";
//alert(inner_content.replace(/(<([^>]+)>) /ig,""));
html = $.parseHTML( str ),
nodeNames = [];
//var $newDiv = $("<div/>") // creates a div element
//.attr("id", "someID"); // adds the id
//$(html).append($newDiv);
jQuery(document).ready(function () {
var doc = new jsPDF();
var specialElementHandlers = {
'#someID': function (element, renderer) {
return true;
}
};
$('#cmd').click(function () {
doc.fromHTML($("#someID").get(0), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
doc.save('sample-file.pdf');
});
});
}
},
error: function(){ //Error }
}});
});
I'm new to PhoneGap and I'm trying to create an application that will include a feature that will take a photo and store the file path(?) in local storage so that the image can then be retrieved along with other data. I know that local storage doesn't allow a user to store a large amount of data but for this app I'm just looking to use local storage only for now. Here is a dulled down version of my local storage saving the text data:
$(function () {
$('[type=submit]').on('click', function (e) {
userList.addUser(
$('#name').val(),
$('#address').val(),
$('#message').val(),
);
$('input:text').val('');
return false;
});
$('#users').on('click', '.delete', function (e) {
userList.deleteUser(parseInt($(this).parent().find('.key').text()));
return false;
});
$('#users').on('click', '.update', function (e) {
var name = $(this).parent().find('.name').text();
var address = $(this).parent().find('.address').text();
var type = $(this).parent().find('.message').text();
var key = parseInt($(this).parent().find('.key').text());
userList.updateUser(name,address,message,key);
return false;
});
userList.open();
});
userList = {};
userList.open = function() {
this.list = { };
if (localStorage.userList) {
this.list = JSON.parse(localStorage.userList);
}
userList.getAllUsers();
};
userList.addUser = function(name,address,message) {
console.log(arguments.callee.name, arguments);
key = new Date().getTime();
this.list[key] = {
'name':name,'address':address,'message':message
};
localStorage.userList = JSON.stringify(this.list);
this.getAllUsers();
};
userList.getAllUsers = function() {
$('#users').html('');
for (var key in this.list) {
renderUser(key, this.list[key]);
}
};
userList.deleteUser = function(id) {
console.log(arguments.callee.name, arguments);
delete this.list[id];
localStorage.userList = JSON.stringify(this.list);
this.getAllUsers();
};
userList.updateUser = function(name,address,message,key) {
console.log(arguments);
this.list[key]['name'] = name;
this.list[key]['address'] = address;
this.list[key]['message'] = message;
localStorage.userList = JSON.stringify(this.list);
this.getAllUsers();
};
function renderUser(key,value) {
console.log(arguments);
var li = '<li><span class="name" contenteditable="true">'+value.name+'</span> ';
li += '<span class="address" contenteditable="true">'+value.address+'</span> ';
li += '<span class="message" contenteditable="true">'+value.message+'</span> ';
li += '[Update] ';
li += '[Delete]<span class="key">'+key+'</span></li>';
$('#users').append(li);
}
...and here is the code I have that takes an photo and stores the photo in the users photo album...
var pictureSource;
var destinationType;
function onPhotoDataSuccess(imageData) {
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = "data:image/jpeg;base64," + imageData;
}
function capturePhotoEdit() {
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
destinationType: destinationType.DATA_URL, saveToPhotoAlbum: true});
}
function onFail(message) {
alert('Failed because: ' + message);
}
If anyone could shed some light on how I can retrieve an image by perhaps storing its file path along with some other text data I'd be extremely grateful! I've looked all over for a helpful tutorial but nothing seems to work out for my problem.
Thank you!! (PS. Sorry for this long post!)
var pictureSource;
var destinationType;
function onPhotoDataSuccess(imageData) {
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = "data:image/jpeg;base64," + imageData;
photo = "data:image/jpeg;base64," + imageData;
localStorage.setItem('photo', photo);
}
function capturePhotoEdit() {
navigator.camera.getPicture(onPhotoDataSuccess, onFail,
{
quality: 20,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY,
encodingType: Camera.EncodingType.JPEG
});
}
function onFail(message) {
alert('Failed because: ' + message);
}
I've made use of the cdn for jsZip, and after referring to the official documentation tried to generate PDF files and compress them into .zip format.
Code:-
var zip = new JSZip();
zip.file("Hello.pdf", "Hello World\n");
zip.file("Alphabet.pdf", "abcdef\n");
zip.generateAsync({type:"blob"})
.then(function(content) {
saveAs(content, "example.zip");
});
But, the problem I'm facing here is that although I'm able to finally generate the .zip file. I'm not able to read the PDF file, as it keeps saying that the format is corrupted. (The same thing happens even for .xls/xlsx format, I don't face the same issue for .doc and .txt format files.)
the error message on trying to open PDF file
What am I doing wrong? What do I need to additionally do? This has got me in a fix! Any help would be appreciated.
EDIT:-
#Fefux - I tried something along these lines i.e generating pdf content first and then compressing to .zip, but it's not working either!
function create_zip() {
var dynamicSITHtml = '<div class="container"><div class="row margin-top">';
dynamicSITHtml = dynamicSITHtml + '<table><thead><tr><th>Target Date/Time</th><th>Referred To Role</th><th>Description</th><th>Priority</th><th>Status</th></tr></thead><tbody>';
dynamicSITHtml = dynamicSITHtml + '</tbody></table></div></div>';
$scope.dymanicSITHtml = dynamicSITHtml;
var pdf1 = new jsPDF('p', 'pt', 'letter');
var ElementHandlers = {
'#editor': function (element, renderer) {
return true;
}
};
pdf1.fromHTML($scope.dymanicSITHtml, 10, 10, {
'width': 1000,
'elementHandlers': ElementHandlers
});
//pdf1.save($scope.operation.ReferenceNumber + '_task_summary_report.pdf');
var zip = new JSZip();
zip.file("Hello.pdf", pdf1.save($scope.operation.ReferenceNumber + '_task_summary_report.pdf'));
zip.generateAsync({ type: "blob" })
.then(function (content) {
saveAs(content, "example.zip");
});
Please help!!
Here's an updated code copy.....
I've tried to make use of js-xlsx library - https://github.com/SheetJS/js-xlsx - to generate xls file and then zip it.
Please refer the below code..
function Create_Zip() {
function datenum(v, date1904) {
if (date1904) v += 1462;
var epoch = Date.parse(v);
return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
}
function sheet_from_array_of_arrays(data, opts) {
var ws = {};
var range = { s: { c: 10000000, r: 10000000 }, e: { c: 0, r: 0 } };
for (var R = 0; R != data.length; ++R) {
for (var C = 0; C != data[R].length; ++C) {
if (range.s.r > R) range.s.r = R;
if (range.s.c > C) range.s.c = C;
if (range.e.r < R) range.e.r = R;
if (range.e.c < C) range.e.c = C;
var cell = { v: data[R][C] };
if (cell.v === null) continue;
var cell_ref = XLSX.utils.encode_cell({ c: C, r: R });
if (typeof cell.v === 'number') cell.t = 'n';
else if (typeof cell.v === 'boolean') cell.t = 'b';
else if (cell.v instanceof Date) {
cell.t = 'n'; cell.z = XLSX.SSF._table[14];
cell.v = datenum(cell.v);
}
else cell.t = 's';
ws[cell_ref] = cell;
}
}
if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
return ws;
}
var data = [[1, 2, 3], [true, false, null, "sheetjs"], ["foo", "bar", new Date("2014-02-19T14:30Z"), "0.3"], ["baz", null, "qux"]];
var ws_name = "SheetJS";
function Workbook() {
if (!(this instanceof Workbook)) return new Workbook();
this.SheetNames = [];
this.Sheets = {};
}
var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);
/* add worksheet to workbook */
wb.SheetNames.push(ws_name);
wb.Sheets[ws_name] = ws;
var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'binary' });
function s2ab(s) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
var jsonse = JSON.stringify([s2ab(wbout)]);
var testblob = new Blob([jsonse], { type: "application/json" });
console.log(testblob);
var zip = new JSZip();
zip.file("trial.xls", testblob);
var downloadFile = zip.generateAsync({ type: "blob" });
saveAs(downloadFile, 'test.zip');
}
But, the problem here is that I keep getting this error: 'The data of 'trial.xls' is in an unsupported format !' in the console :(.
Is there any way I can make this work?
You have an error because you don't zip pdf file. You zip a file named Hello.pdf and the content of the file is "Hello world\n" but this is not a valid PDF content (same things for Alphabet.pdf).
You need to generate a valid PDF content and after zip it.
EDIT : working jsFiddle : https://jsfiddle.net/55gdt8ra/
$(function() {
var doc = new jsPDF();
doc.setFontSize(40);
doc.text(35, 25, "Octonyan loves jsPDF");
var zip = new JSZip();
zip.file("Hello.pdf", doc.output());
zip.generateAsync({ type: "blob" })
.then(function (content) {
saveAs(content, "example.zip");
});
})