How to open a local pdf file using OpenURL in Titanium Appceleartor? - titanium

In Titanium Appcelerator, i tried to open a PDF file from local directory using OpenURL() method. It's not working properly. i tried on Android device.
My Code;
var myURL = "file:///storage/emulated/0/Android/data/com.test.testapp/cache/_tmp/sample.pdf";
Ti.Platform.openURL(myURL);

Try something like this:
try {
var f = Ti.Filesystem.getFile('your.pdf');
Ti.Android.currentActivity.startActivity(Ti.Android.createIntent({
action: Ti.Android.ACTION_VIEW,
type: 'application/pdf',
data: f.getNativePath()
}));
}
catch (err) {
var alertDialog = Titanium.UI.createAlertDialog({
title: 'No PDF Viewer',
message: 'We tried to open a PDF but failed. Do you want to search the marketplace for a PDF viewer?',
buttonNames: ['Yes','No'],
cancel: 1
});
alertDialog.show();
alertDialog.addEventListener('click', function(evt) {
if (evt.index == 0) {
Ti.Platform.openURL('http://search?q=pdf');
}
});
}

To open a remote PDF natively, you have to download it. Here is a solution which provides the user with options to preview or download the PDF.
var url = "http://www.polyu.edu.hk/iaee/files/pdf-sample.pdf";
var opts = {
cancel: 2,
options: ['Preview', 'Download', 'Cancel'],
selectedIndex: 2,
destructive: 0,
title: 'Open PDF'
};
var dialog = Ti.UI.createOptionDialog(opts);
dialog.addEventListener('click', function(e) {
if (e.index == 0) {
url = "https://docs.google.com/viewer?embedded=true&url=" + url;
var win = Ti.UI.createWindow();
var webView = Ti.UI.createWebView({url:url});
win.add(webView);
win.open();
} else if (e.index == 1) {
var filepath = url.split('/').pop();
var httpClient = Titanium.Network.createHTTPClient({
onload: function() {
var file = Titanium.Filesystem.getFile(Titanium.Filesystem.tempDirectory, filepath);
file.write(this.responseData);
try {
Ti.Android.currentActivity.startActivity(Ti.Android.createIntent({
action: Ti.Android.ACTION_VIEW,
type: 'application/pdf',
data: file.getNativePath()
}));
} catch (e) {
alert('No PDF reader found.');
}
}
});
httpClient.open('GET', url);
httpClient.send();
}
});
dialog.show();

Related

Converting a docx Node.js buffer into pdf file

I am trying to convert the docx document from my node buffer into a pdf document using pdfmake. The pdf is generating but it has no content inside of it. I really don't know where that problem is coming from. I don't mind not using pdfmake, I'm up for anything that can solve the problem really.
`
exports.Resolution = functions.https.onCall(async (data, context) => {
const file_name = 'Resolution.docx';// this is the file saved in my firebase storage
const templateRef = await admin.storage().bucket()
.file(file_name);
const template_content = (await templateRef.download())[0];
const zip = new PizZip(template_content);
let doc;
try {
doc = new Docxtemplater(zip, { linebreaks: true });
} catch (error) {
// Catch compilation errors (errors caused by the compilation of the template : misplaced tags)
errorHandler(error);
}
doc.setData({
date: data.date,
investorName: data.investorName,
companyName: data.companyName,
regNo: data.regNo,
agreements: data.agreements,
governmentEntity: data.governmentEntity,
directors: data.directors,
equityStake: data.equityStake,
governmentEntityName: data.governmentEntityName,
fccp: data.fccp,
investorDirector:data.investorDirector,
equity: data.equity
});
try {
doc.render();
} catch (error) {
errorHandler(error);
}
const contentBuffer = doc.getZip().generate({ type: "nodebuffer" });
const nameofFile = 'Resolution Approving Transaction ' + data.investorName;
const printer = new PdfPrinter(fontss);
const chunks = [];
const pdfDoc = printer.createPdfKitDocument(contentBuffer);
pdfDoc.on('data', (chunk) => {
chunks.push(chunk);
});
pdfDoc.on('end', async () => {
const result = Buffer.concat(chunks);
function mail (){
const dest = context.auth.token.email;
const mailOptions = {
from: 'MPC <mypocketcounsel#gmail.com>',
to: dest,
cc:data.extraEmail,
subject: 'Resolution Approving Transaction',
text: 'Dear ' + data.name+ ',\n\nPlease find attached your Resolution Approving Transaction.\n\nThank you for using MPC Web. \n\n Best regards,\n\n The MPC Team.',
attachments: [
{
filename: nameofFile+'.docx',
content: contentBuffer
},
{
filename: nameofFile +'.pdf',
contentType: 'application/pdf',
content: result
}
]
};
// returning result
return transporter.sendMail(mailOptions);
}
return mail();
});
pdfDoc.on('error', (err) => {
return functions.logger.log('An error occured!');
});
pdfDoc.end();
});
`
This is the function that generates both the docx file and the pdf for me.

startRecording not working using RecordRTC with RTCMultiConnection

I am trying to record every new session/user added to RTCMultiConnection.
i am using the following demo url in application
https://rtcmulticonnection.herokuapp.com/demos/Audio+Video+TextChat+FileSharing.html
Now i have added the following cdn reference to the code.
https://cdn.webrtc-experiment.com/RecordRTC.js
and this is the code i am working with but connection.streams[event.streamid].startRecording(); is not working.
// ..................RTCMultiConnection Code.............
// ......................................................
var connection = new RTCMultiConnection();
var btnStopRec = document.getElementById("btnStopRecording");
connection.socketURL = 'https://rtcmulticonnection.herokuapp.com:443/';
connection.enableFileSharing = true;
connection.session = {
audio: true,
video: true,
data: true,
};
connection.sdpConstraints.mandatory = {
OfferToReceiveAudio: true,
OfferToReceiveVideo: true,
};
connection.onstream = function (event)
{
document.body.appendChild(event.mediaElement);
console.log("stream recording starts")
connection.streams[event.streamid].startRecording();
console.log("stream recording started")
}
I included all possible situations in a single snippet, below. Please take only the code that you need:
// global object that contains multiple recorders
var recorders = {};
// auto start recorder as soon as stream starts/begins
connection.onstream = function(event) {
document.body.appendChild(event.mediaElement);
recorders[event.streamid] = RecordRTC(event.stream, {
type: 'video'
});
recorders[event.streamid].startRecording();
};
// auto stop recorder as soon as stream stops/ends
connection.onstreamended = function(event) {
if (recorders[event.streamid]) {
recorders[event.streamid].stopRecording(function() {
var blob = recorders[event.streamid].getBlob();
var url = URL.createObjectURL(blob);
window.open(url);
delete recorders[streamid]; // clear
});
}
if (event.mediaElement.parentNode) {
event.mediaElement.parentNode.removeChild(event.mediaElement);
}
};
// stop single recorder
document.getElementById('manually-stop-single-recording').onclick = function() {
var streamid = prompt('Enter streamid');
recorders[streamid].stopRecording(function() {
var blob = recorders[streamid].getBlob();
var url = URL.createObjectURL(blob);
window.open(url);
delete recorders[streamid]; // clear
});
};
// stop all recorders
document.getElementById('manually-stop-all-recordings').onclick = function() {
Object.keys(recorders).forEach(function(streamid) {
recorders[streamid].stopRecording(function() {
var blob = recorders[streamid].getBlob();
var url = URL.createObjectURL(blob);
window.open(url);
delete recorders[streamid]; // clear
});
});
};
// record outside onstream event
// i.e. start recording anytime manually
document.getElementById('record-stream-outside-the-onstream-event').onclick = function() {
var streamid = prompt('Enter streamid');
var stream = connection.streamEvents[streamid].stream;
recorders[streamid] = RecordRTC(stream, {
type: 'video'
});
recorders[streamid].startRecording();
};

Downloading a file with CasperJS from POST attachment

I almost have this working, I just can't seem to download the file when it comes up. What am I doing wrong here? When clicking the button "Download Sales Report" a CSV should download, by my console.log() never even fires off.
var casper = require('casper').create();
casper.start('http://www.waynecountyauditor.org/Reports.aspx?ActiveTab=Sales')
.waitForText("Accept")
.thenClick('#ctl00_ContentPlaceHolder1_btnDisclaimerAccept')
.waitForText("View Sales")
.thenClick('#ctl00_ContentPlaceHolder1_WeeklySales_fvSalesReport_btnViewSales')
.waitForText("Download Sales Report")
.thenClick(x('//*[#id="ctl00_blSearchLinks"]/li[4]/a'))
.wait(1000)
.on('page.resource.received', function(resource) {
console.log('here');
if (resource.stage !== "end") {
return;
}
if (resource.url.indexOf('results.csv') > -1) {
this.download(resource.url, 'D:\Jobs\Currency\testing\ExportData.csv');
}
});
casper.run();
I finally figured it out. Vaviloff had 99% of what I needed. I was just missing 2 post variables. Thanks for your help Vaviloff!
// http://stackoverflow.com/questions/33903418/downloading-a-file-with-casperjs-from-post-attachment
var casper = require('casper').create({
verbose: true,
logLevel: 'debug',
pageSettings: {
loadImages: false // The WebPage instance used by Casper will
, loadPlugins: false // use these settings
, userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4'
}
});
var x = require('casper').selectXPath;
var utils = require('utils');
casper.on('remote.message', function(message) {
this.echo('LOG: ' + message);
});
casper.start()
.open('http://clintonoh.ddti.net/Reports.aspx?ActiveTab=Sales')
.waitForText("Accept")
.thenClick('#ctl00_ContentPlaceHolder1_btnDisclaimerAccept')
.waitForText("View Sales")
.thenClick('#ctl00_ContentPlaceHolder1_WeeklySales_fvSalesReport_btnViewSales')
.waitForText("Download Sales Report", function(){
// Adapted from: http://stackoverflow.com/questions/16144252/downloading-a-file-that-comes-as-an-attachment-in-a-post-request-response-in-pha
var res = this.evaluate(function() {
document.getElementById('__EVENTTARGET').value='ctl00$blSearchLinks' /* Was missing these 2 */
document.getElementById('__EVENTARGUMENT').value='4'
var res={};
f=document.getElementById("aspnetForm");
var previous_onsubmit = f.onsubmit;
f.onsubmit = function() {
//previous_onsubmit();
//iterate the form fields
var post={};
for(i=0; i<f.elements.length; i++) {
//console.log(f.elements[i].name + " = " + f.elements[i].value);
post[f.elements[i].name]=f.elements[i].value;
}
res.action = f.action;
res.post = post;
return false; //Stop form submission
}
// Trigger the click on the link.
var link = document.evaluate('//*[#id="ctl00_blSearchLinks"]/li[5]/a', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
try {
var e = document.createEvent('MouseEvents');
e.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
link.dispatchEvent(e);
} catch(error){
console.log(error);
}
return res; //Return the form data to casper
});
//Start the download
casper.download(res.action, "./ExportData.csv", "POST", res.post);
//casper.capture("./image.png");
})
casper.run();
I finally got the answer after long time RD, we can use download node module for downloading the attachment as follows
const fs = require('fs');
const download = require('download');
download('http://unicorn.com/foo.pdf').then(data => {
fs.writeFileSync('dist/foo.pdf', data);
});`
Link to Download NPM Module

Image not displayed after camera click on some of the android devices

I am using camera in my website, in mobile phone browser I am having some problems, in some of the phone browser after clicking the camera, Image not displayed, Its show a blank image icon.
Can u plz find out what is the problem in my code?
(function () {
var takePicture = document.querySelector("#take-picture"),
showPicture = document.querySelector("#show-picture");
if (takePicture && showPicture) {
// Set events
takePicture.onchange = function (event) {
// Get a reference to the taken picture or chosen file
var files = event.target.files,
file;
if (files && files.length > 0) {
file = files[0];
try {
// Get window.URL object
var URL = window.URL || window.webkitURL;
// Create ObjectURL
var imgURL = URL.createObjectURL(file);
// Set img src to ObjectURL
showPicture.src = imgURL;
// Revoke ObjectURL
URL.revokeObjectURL(imgURL);
}
catch (e) {
try {
// Fallback if createObjectURL is not supported
var fileReader = new FileReader();
fileReader.onload = function (event) {
showPicture.src = event.target.result;
};
// fileReader.readAsDataURL(file);
fileReader.readAsBinaryString(file);
var exif = EXIF.readFromBinaryFile(new BinaryFile(this.result));
switch(exif.Orientation){
case 8:
showPicture.rotate(90*Math.PI/180);
break;
case 3:
showPicture.rotate(180*Math.PI/180);
break;
case 6:
showPicture.rotate(-90*Math.PI/180);
break;
}
}
catch (e) {
// Display error message
var error = document.querySelector("#error");
if (error) {
error.innerHTML = "Neither createObjectURL or FileReader are supported";
}
}
}
}
};
}
})();
<input type="file" id="take-picture" accept="image/*">
<div id="mobilecameraOutput"> <img src="about:blank" alt="" id="show-picture" /></div>

How to redirect to file picker

I am a freshman on skydrive. then I want to use file picker in html, and copy the demo code from Interactive Live SDK. but the running result, the open window is not direct to file picker page, just direct to my setting redirect_uri page. so what's wrong with my demo page? thanks
<script src="http://js.live.net/v5.0/wl.js" type="text/javascript"></script>
<script type="text/JavaScript">
<!--
/////////////////////////////
WL.init({ client_id: '$my appID', redirect_uri: 'http://www.learnyouwant.com' });
WL.ui({
name: "skydrivepicker",
element: "downloadFile_div",
mode: "open",
select: "multi",
onselected: onDownloadFileCompleted,
onerror: onDownloadFileError
});
WL.login({ "scope": "wl.skydrive wl.signin" }).then(
function(response) {
openFromSkyDrive();
},
function(response) {
log("Failed to authenticate.");
}
);
function openFromSkyDrive() {
WL.fileDialog({
mode: 'open',
select: 'single'
}).then(
function(response) {
log("The following file is being downloaded:");
log("");
var files = response.data.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
log(file.name);
WL.download({ "path": file.id + "/content" });
}
},
function(errorResponse) {
log("WL.fileDialog errorResponse = " + JSON.stringify(errorResponse));
}
);
}
function log(message) {
var child = document.createTextNode(message);
var parent = document.getElementById('JsOutputDiv') || document.body;
parent.appendChild(child);
parent.appendChild(document.createElement("br"));
}
function onDownloadFileCompleted(response) {
var msg = "";
// For each folder selected...
if (response.data.folders.length > 0) {
for (folder = 0; folder < response.data.folders.length; folder++) {
// Use folder IDs to iterate through child folders and files as needed.
msg += "\n" + response.data.folders[folder].id;
}
}
// For each file selected...
if (response.data.files.length > 0) {
for (file = 0; file < response.data.files.length; file++) {
// Use file IDs to iterate through files as needed.
msg += "\n" + response.data.files[file].id;
}
}
log(msg);
};
function onDownloadFileError(responseFailed) {
log(responseFailed.error.message);
}
//-->
</script>
I found the reason. the redirect_uri must same with the filling in the app registeration.