I want to download and upload a pdf after creating it from html using javascript - pdfmake

HERE is the code i used to download the file.
I want to upload the same file to server.
The file was created from html.
$scope.callPdf = function (studentId) {
html2canvas(document.getElementById('download'), {
onrendered: function (canvas) {
var data = canvas.toDataURL();
var docDefinition = { content: [{ image: data, width: 450 }] };
pdfMake.createPdf(docDefinition).download(studentId + ".pdf");
}
});
}`

You can use getDataURL method and receive store it in variable and then use it for upload.
pdfMake.createPdf(docDefinition).getDataUrl(function(dataUrl){
var pdfFile = dataUrl;
//upload code goes here
});

Related

PDFTron webviewer - how to save the whole redacted pdf to server using ASP.net MVC Core

I am currently a developing an application in MVC Core that is using a PDFTron webviewer. Is there anyway to save the edited pdf edited with pdftron webviewer to the server?
There is a feature of pdftron that saves annotations to the server, but I need to save the whole pdf with the edits to the server.
WebViewer({
path: '/lib/WebViewer',
initialDoc: '/StaticResource/Music.pdf', fullAPI: !0, enableRedaction: !0
}, document.getElementById('viewer')).then(
function(t) {
samplesSetup(t);
var n = t.docViewer;
n.on('documentLoaded', function() {
document.getElementById('apply-redactions').onclick = function() {
t.showWarningMessage({
title: 'Apply redaction?',
message: 'This action will permanently remove all items selected for redaction. It cannot be undone.',
onConfirm: function () {
alert( );
t.docViewer.getAnnotationManager().applyRedactions()
debugger
var options = {
xfdfString: n.getAnnotationManager().exportAnnotations()
};
var doc = n.getDocument();
const data = doc.getFileData(options);
const arr = new Uint8Array(data);
const blob = new Blob([arr], { type: 'application/pdf' });
const data = new FormData();
data.append('mydoc.pdf', blob, 'mydoc.pdf');
// depending on the server, 'FormData' might not be required and can just send the Blob directly
const req = new XMLHttpRequest();
req.open("POST", '/DocumentRedaction/SaveFileOnServer', true);
req.onload = function (oEvent) {
// Uploaded.
};
req.send(data);
return Promise.resolve();
},
});
};
}),
t.setToolbarGroup('toolbarGroup-Edit'),
t.setToolMode('AnnotationCreateRedaction');
}
);
When i send the request to the Controller i am not getting the file it is coming null
[HttpPost]
public IActionResult SaveFileOnServer(IFormFile file)
{
return Json(new { Result="ok"});
}
Can any one suggest me where i am going wrong
Thanks in adavance
For JavaScript async function, you need to wait for it completes before doing other things. For example, AnnotationManager#applyRedactions() returns a Promise, the same for AnnotationManager#exportAnnotations() and Document#getFileData().
For JS async functions, you can take a look at:
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
So here you may want to use await to wait for the Promise completes.

Ruby Shrine - crop & direct upload Safari issue

I am implementing direct upload with Shrine, jquery.fileupload and cropper.js
in the add portion I am loading the image from the file upload to modal, define the cropper and show the modal
if (data.files && data.files[0]) {
var reader = new FileReader();
var $preview = $('#preview_avatar');
reader.onload = function(e) {
$preview.attr('src', e.target.result); // insert preview image
$preview.cropper({
dragMode: 'move',
aspectRatio: 1.0 / 1.0,
autoCropArea: 0.65,
data: {width: 270, height: 270}
})
};
reader.readAsDataURL(data.files[0]);
$('#crop_modal').modal('show', {
backdrop: 'static',
keyboard: false
});
}
Then on the modal button click I get the cropped canvas call on it toBlob and submit to S3
$('#crop_button').on('click', function(){
var options = {
extension: data.files[0].name.match(/(\.\w+)?$/)[0], // set extension
_: Date.now() // prevent caching
};
var canvas = $preview.cropper('getCroppedCanvas');
$.getJSON('/images/cache/presign', options).
then(function (result) {
data.formData = result['fields'];
data.url = result['url'];
data.paramName = 'file';
if (canvas.toBlob) {
canvas.toBlob(
function (blob) {
var file = new File([blob], 'cropped_file.jpeg');
console.log('file', file);
data.files[0] = file;
data.originalFiles[0] = data.files[0];
data.submit();
},
'image/jpeg'
);
}
});
});
After the upload to S3 is done I am writing to image attributes to hidden field, closing the modal and destroying the cropper
done: function (e, data) {
var image = {
id: data.formData.key.match(/cache\/(.+)/)[1], // we have to remove the prefix part
storage: 'cache',
metadata: {
size: data.files[0].size,
filename: data.files[0].name.match(/[^\/\\]*$/)[0], // IE returns full path
// mime_type: data.files[0].type
mime_type: 'image/jpeg'
}
};
console.log('image', image);
$('.cached-avatar').val(JSON.stringify(image));
$('#crop_modal').modal('hide');
$('#preview_avatar').cropper('destroy');
}
An chrome everything worked fine from the very beginning, but then I figured out the safari has no toBlob functionality.
I found this one:
https://github.com/blueimp/JavaScript-Canvas-to-Blob
And toBlob is not a function error was gone..
Now I can not save the image due to some mime type related issue.
I was able to find out the exact location where it fails on safari but not chrome.
determine_mime_type.rb line 142
on line 139 in the options = {stdin_data: io.read(MAGIC_NUMBER), binmode: true}
the stdin_data is empty after the io.read
Any ideas?
Thank you!
UPDATE
I was able to figure out that the url to the cached image returned by the
$.getJSON('/images/cache/presign', options)
returns empty file when cropped and uploaded from safari.
So as I mentioned in the question safari uploaded empty file once it was cropped by cropper.js.
The problem clearly originated from this block:
if (canvas.toBlob) {
canvas.toBlob(
function (blob) {
var file = new File([blob], 'cropped_file.jpeg');
console.log('file', file);
data.files[0] = file;
data.originalFiles[0] = data.files[0];
data.submit();
},
'image/jpeg'
);
}
I found in some comment on one of the articles I read that safari does some thing like "file.toString" which in my case resulted in empty file upload.
I appended the blob directly without creating a file from it first and everything worked fine.
if (canvas.toBlob) {
canvas.toBlob(
function (blob) {
data.files[0] = blob;
data.files[0].name = 'cropped_file.jpeg';
data.files[0].type = 'image/jpeg';
data.originalFiles[0] = data.files[0];
data.submit();
},
'image/jpeg'
);
}

Titanium add photo to specific gallery

So I have the following which works real nice as is:
button.addEventListener("click", function(e){
Titanium.Media.showCamera({
success:function(e){
if(e.mediaType === Titanium.Media.MEDIA_TYPE_PHOTO){
var imageView = Titanium.UI.createImageView({
image: e.media,
width: 'auto',
height: 'auto',
top: 50,
zIndex: 1
});
win.add(imageView);
} else {
alert("Only Photos aloud");
}
},
error:function(e){
alert("There was an error");
},
cancel:function(e){
alert("The event was cancelled");
},
allowEditing: true,
saveToPhotoGallery: true,
mediaTypes:[Titanium.Media.MEDIA_TYPE_PHOTO,Titanium.Media.MEDIA_TYPE_VIDEO],
videoQuality:Titanium.Media.QUALITY_HIGH
});
});
saveToPhotoGallery just adds the taken photo to the default gallery in the iOS Photos App.
I need to add the photo to a specific folder in the iOS Photos App though.
Has anyone an idea how I could do this from with Titanium ?
I have been searching the intewebs but have not found anything on how to add a taken photo to a specific folder.
Thank for the help guys
Chris
But, let me specify that the file can be save in the Application Directory only in IOS but in android you can save it in the externalStorage. You can have look at the documentation through the below link :
https://docs.appcelerator.com/platform/latest/#!/guide/Filesystem_Access_and_Storage
You can easily save the file to your folder using the following code :
if (OS_ANDROID) {
var f12 = Titanium.Filesystem.getFile(Titanium.Filesystem.externalStorageDirectory);
} else {
var f12 = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory);
}
var galleryImg = e.media;
var fileToSave = null;
var fileName = 'IMG' + todayDate + "HB" + Ti.App.Properties.getInt('imgCounter') + '.jpg';
if (OS_ANDROID) {
fileToSave = Titanium.Filesystem.getFile(f12.resolve(), fileName);
} else {
fileToSave = Titanium.Filesystem.getFile(f12.resolve(), fileName);
}
fileToSave.write(galleryImg);
If you want to create a subDirectory then use the following code :
var dir = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory,'mysubdir');
dir.createDirectory(); // this creates the directory
But, let me specify that the file can be save in the Application Directory only in IOS but in android you can save it in the externalStorage. You can have look at the documentation through the below link :
https://docs.appcelerator.com/platform/latest/#!/guide/Filesystem_Access_and_Storage
EDIT
You Could do it this way :
// get the TiBlob
var blob = img_view.toImage();
// try to save the image the image
Ti.Media.saveToPhotoGallery(blob,{
success: function(e){
if (callback == undefined) {
alert('Saved image to gallery');
} else {
callback();
}
},
error: function(e){
alert("Error saving the image");
}
});
Good Luck, Cheers

Downloaded image not shown in iOS gallery while shown in android phone gallery

I used telerik app builder platform to create application. I created download image functionality. This functionality is working on android device, but not on iOS. I don't know why it is not working.
When the user downloads an image using application in android device, then cordova filesystem creates directory and saves image into that directory and image was also shown in gallery. While user performs same action in iOS then it does not create any directory and the image is not shown in gallery. I haven't found where to save this image.
Please give suggestion on how to save downloaded image in iOS gallery.
My code is below
function onDeviceReady() {
var that = this,
App = new downloadApp(),
fileName = "sample.png",
uri = encodeURI("http://www.telerik.com/sfimages/default-source/logos/app_builder.png"),
folderName = "test";
navigator.splashscreen.hide();
App.run(uri, fileName, folderName);
}
downloadApp.prototype = {
run: function (uri, fileName, folderName) {
var that = this,
filePath = "";
document.getElementById("download").addEventListener("click", function () {
that.getFilesystem(
function (fileSystem) {
console.log(fileSystem);
that.getFolder(fileSystem, folderName, function (folder) {
filePath = folder.toURL() + "\/" + fileName;
console.log(filePath);
that.transferFile(uri, filePath)
}, function () {
console.log("failed to get folder");
});
},
function () {
console.log("failed to get filesystem");
}
);
});
},
getFilesystem: function (success, fail) {
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, success, fail);
},
getFolder: function (fileSystem, folderName, success, fail) {
fileSystem.root.getDirectory(folderName, { create: true, exclusive: false }, success, fail)
},
transferFile: function (uri, filePath) {
var transfer = new FileTransfer();
transfer.download(
uri,
filePath,
function (entry) {
var targetPath = entry.toURL();
},
function (error) {
console.log(error)
}
);
},
Try to download by using https://www.npmjs.com/package/com-cordova-image-save-to-gallery plugin. It will download a picture from a given URL and save it to IOS Photo Gallery.
Cordova plugin add https://github.com/valwinjose007/cordova-image-save-to-gallery.git
How to use:
declare var CordovaImageSaveToGallery: any;
CordovaImageSaveToGallery.downloadFromUrl('https://picsum.photos/200/300',(res)=>{
//download success
},(err)=>{
//error on download
});

Cordova / Ionic - Download file from InAppBrowser

The scenario goes like this: I open a website in InAppBrowser, after the user ends with the work over there, the site generates a .pdf for the user to download, the problem is that the pdf does not download, it opens it in the browser.
Is there a way to make it download from the InAppBrowser? I'm currently working on an iOS app, so the solution would be better for iOS.
Thanks in advance.
Following #jcesarmobile advices this is what I came up with:
First I had to install the cordova-plugin-file-transfer
Open URL
var url = "http://mi-fancy-url.com";
var windowref = window.open(url, '_blank', 'location=no,closebuttoncaption=Cerrar,toolbar=yes,enableViewportScale=yes');
Create a listener on that windowref for a loadstart event and check if what's being loaded is a pdf (that's my case).
windowref.addEventListener('loadstart', function(e) {
var url = e.url;
var extension = url.substr(url.length - 4);
if (extension == '.pdf') {
var targetPath = cordova.file.documentsDirectory + "receipt.pdf";
var options = {};
var args = {
url: url,
targetPath: targetPath,
options: options
};
windowref.close(); // close window or you get exception
document.addEventListener('deviceready', function () {
setTimeout(function() {
downloadReceipt(args); // call the function which will download the file 1s after the window is closed, just in case..
}, 1000);
});
}
});
Create the function that will handle the file download and then open it:
function downloadReceipt(args) {
var fileTransfer = new FileTransfer();
var uri = encodeURI(args.url);
fileTransfer.download(
uri, // file's uri
args.targetPath, // where will be saved
function(entry) {
console.log("download complete: " + entry.toURL());
window.open(entry.toURL(), '_blank', 'location=no,closebuttoncaption=Cerrar,toolbar=yes,enableViewportScale=yes');
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
},
true,
args.options
);
}
The problem i'm facing now is the path where it downloads, I just can't open it. But well, at least file is now downloaded. I will have to create a localStorage item to save the paths for different files.
Many validations are missing in this steps, this was just an example I made quickly to check if it works. Further validations are needed.
Open you window using IAB plugin and add an event listener
ref = window.open(url, "_blank");
ref.addEventListener('loadstop', loadStopCallBack);
In the InAppBrowser window call the action using https://xxx.pdf">documentName
Implement the loadStopCallBack function
function loadStopCallBack(refTemp) {
if(refTemp.url.includes('downloadDoc')) {
rtaParam = getURLParams('downloadDoc', refTemp.url);
if(rtaParam != null)
downloadFileFromServer(rtaParam);
return;
}
}
function getURLParams( name, url ) {
try {
if (!url)
url = location.href;
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(url);
return results == null ? null : results[1];
} catch (e) {
showSMS(e);
return null;
}
}
After create a download method
function downloadFileFromServer(fileServerURL){
try {
var Downloader = window.plugins.Downloader;
var fileName = fileServerURL.substring(fileServerURL.lastIndexOf("/") + 1);
var downloadSuccessCallback = function(result) {
console.log(result.path);
};
var downloadErrorCallback = function(error) {
// error: string
console.log(error);
};
//TODO cordova.file.documentsDirectory for iOS
var options = {
title: 'Descarga de '+ fileName, // Download Notification Title
url: fileServerURL, // File Url
path: fileName, // The File Name with extension
description: 'La descarga del archivo esta lista', // Download description Notification String
visible: true, // This download is visible and shows in the notifications while in progress and after completion.
folder: "Download" // Folder to save the downloaded file, if not exist it will be created
};
Downloader.download(options, downloadSuccessCallback, downloadErrorCallback);
} catch (e) {
console.log(e);
}
}
you can get the plugin here https://github.com/ogarzonm85/cordova-plugin-downloader
it Works and was too easy

Resources