Error trying to encode PDF in Code by Zapier - encoding

I'm trying to read a pdf and encode it via JS Code in Zapier. Does anyone know how can I encode a Google Drive PDF file?
Trying to do this:
const fs = require('fs');
let buff = fs.readFileSync('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf');
let base64data = buff.toString('base64');
output = [{fileEncoded: base64data}];
But receivingthis error:
Error: ENOENT: no such file or directory, open 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf'
Any thoughts?

Node's fs module deals with the filesystem, so you can't use it to download files from the web.
Try adapting this example from this github issue:
async function download() {
const res = await fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png');
await new Promise((resolve, reject) => {
const fileStream = fs.createWriteStream('./octocat.png');
res.body.pipe(fileStream);
res.body.on("error", (err) => {
reject(err);
});
fileStream.on("finish", function() {
resolve();
});
});
}
You can use await in Zapier JS without any extra work

Related

Office-js Word addin, Grabbing document Text

In my code below, I am attempting to grab the current documents text, set it to a variable and then use that variable in a call. My promise may not be formatted correctly but essentially the getScanResult() function uses the docBodyText variable that I set in handleClickRun(). Everytime I call it the variable is empty. Any idea as to why the document text is not being captured correctly?
const [docBodyText, setDocBodyText] = useState('');
const handleClickRun = async () => {
return Word.run(async (context: Word.RequestContext) => {
const docBody = context.document.body;
docBody.load("text");
await context.sync();
setDocBodyText(docBody.text);
await context.sync();
})
.catch(function (error) {
console.log("Error: " + error);
if (error instanceof OfficeExtension.Error) {
console.log("Debug info: " + JSON.stringify(error.debugInfo));
}
});
};
const handleScanResults = () => {
new Promise(async (resolve) => {
await handleClickRun();
await getScanResult();
resolve('Completed')
})};
I have tried using the docs and looking for other examples but have not seen any other use cases. The docs I am using is this Perhaps I can be pointed to the correct method.
I have also tried making a variable of just plain text and passing it to my api call and it works perfectly fine, so it is not a call issue.

Upload image to firebase storage from React Dropzone (gives invalid Image)

I am using React Dropzone to upload files from React to firebase as shown below:
const onDrop = useCallback((acceptedFiles, fileRejections) => {
//Check if file type is image
//Check if file size < 5MB
//Upload
if (fileRejections.length > 0) {
setError(true);
} else setError(false);
if (acceptedFiles.length > 0) {
const file = acceptedFiles[0];
console.log(file);
setFile({
...file,
preview: URL.createObjectURL(file),
});
setFileUploaded(true);
}
}, []);
and this is my upload handler:
const handleImageUpload = () => {
//Upload Image to Firebase
//Check if file exists
if (file !== null || file !== undefined) {
const storageRef = ref(
Client.storage,
`/db-dev/user-metadata/portfolio/images/first-image.jpg`
);
console.log('Process begins');
uploadBytes(storageRef, file).then((snapshot) => {
console.log('Uploaded a blob or file!');
});
}
};
these two things do the work but I believe for some reason they're not encoding or decoding the image as in firebase storage folder I see image as invalid image.
Can someone help me to understand where things are going wrong? (To make sure file is loaded properly, I am also viewing the file using: preview: URL.createObjectURL(file), and it loads correctly in browser.
For file upload I am following the latest firebase documentation
It sets file type to octet-stream not sure what that means:
Edit 1: I tried to set metadata to image/jpeg:
uploadBytes(storageRef, file, {
contentType: 'image/jpeg',
}).then((snapshot) => {
console.log('Uploaded a blob or file!');
});
But now it shows:
The problem was in this step:
setFile({
...file,
preview: URL.createObjectURL(file),
});
for some reason it wasn't spreading correctly. I changed it to:
setFile({
file:file,
preview: URL.createObjectURL(file),
});
and the upload function to:
const handleImageUpload = () => {
//Upload Image to Firebase
//Check if file exists
if (file !== null || file !== undefined) {
const storageRef = ref(
Client.storage,
`/db-dev/user-metadata/portfolio/images/first-image.jpg`
);
console.log('Process begins');
uploadBytes(storageRef, file.file, {
contentType: file.file.type,
}).then((snapshot) => {
console.log('Uploaded a blob or file!');
});
}
};
and then it worked fine. Although this was a really silly thing on my part but hope this helps someone in future

How to preview a base64 PDF with ionic capacitor

I am trying to open and preview a PDF from a capacitor application.
Here is my code :
const { Browser } = Plugins;
let base64Pdf = "";
var contentType = "application/pdf";
var dataBlob = this.b64toBlob(base64Pdf, contentType);
await Browser.open({ url: URL.createObjectURL(dataBlob) }).then(() => {
console.log("PDF OK");
}).catch(err => {
console.log(err);
})
This is working great on web, but does not work on iOS. I get an error saying that the URL is invalid. I also tried to use
window.open(URL.createObjectURL(dataBlob), '_blank');
and
window.open(URL.createObjectURL(dataBlob), '_system');
But none of these work. I do not get any error output.
When using self, the PDF is opening well, but since it opens inside the webview, there is no more control and the user is stuck :
window.open(URL.createObjectURL(dataBlob), '_system');
Thanks in advance for any help

How do I copy files from within a VSCode extension to the workspace?

I have certain files within the VSCode extension src folder that I would like to copy into the root of the workspace on running a certain command. Once this is working I would also like to extend this to copy other static files with specific content into other sub-folders within the workspace. I found a way to create new files here. However, I am unable to find a way to copy entire files bundled within the extension into the workspace. Looking at the MSFT documentation here, I cannot find anything that would work for my use case. Any pointers are appreciated.
I created a function copyFile that can copy file from within a VSCode extension to the workspace at the provided destination.
You can use WorkspaceEdit and FileSystem VS Code API to achieve this task as shown below.
async function copyFile(
vscode,
context,
outputChannel,
sourcePath,
destPath,
callBack
) {
try {
const wsedit = new vscode.WorkspaceEdit();
const wsPath = vscode.workspace.workspaceFolders[0].uri.fsPath;
const data = await vscode.workspace.fs.readFile(
vscode.Uri.file(context.asAbsolutePath(sourcePath))
);
const filePath = vscode.Uri.file(wsPath + destPath);
wsedit.createFile(filePath, { ignoreIfExists: true });
await vscode.workspace.fs.writeFile(filePath, data);
let isDone = await vscode.workspace.applyEdit(wsedit);
if(isDone) {
outputChannel.appendLine(`File created successfully: ${destPath}`);
callBack(null, true);
}
} catch (err) {
outputChannel.appendLine(`ERROR: ${err}`);
callBack(err, false);
}
}
Sample function call:
function activate(context) {
...
let testChannel = vscode.window.createOutputChannel("TestChannel");
// copy tasks.json file from vs code extension to the destination workspace
copyFile(vscode, context, testChannel,
'assets/tasks.json', '/.vscode/tasks.json', function(err, res) {});
...
}

Looking for a good sample working code for downloading any file from URL in flutter. If its with native downloader then this will be very good

Looking for a good sample working code for downloading any file from URL in flutter. If its with native downloader then this will be very good. Please help me with sample of code to download any file using native downloader in flutter.
I have used few libraries but didn't turned out well.
For a mobile device, I used the http package to download a file to the applications document directory
First, create a httpClient object
static var httpClient = new HttpClient();
Then you can create a function like this to download the file:
Future<void> _downloadFile({
required String fileName,
}) async {
String url = ...;
var request = await httpClient.getUrl(Uri.parse(url));
var response = await request.close();
var bytes = await consolidateHttpClientResponseBytes(response);
String dir = (await getApplicationDocumentsDirectory())!.path;
File file = new File('$dir/$fileName'); // Note: Filename must contain the extension of the file too, like pdf, jpg etc.
await file.writeAsBytes(bytes);
}
For a flutter web application, I felt the url_launcher package was the easiest to work with.
_launchURL() async {
String url = ...;
if (await canLaunch(url)) {
await launch(url);
print('URL Launcher success');
} else {
throw Exception('Could not launch $url');
}
}
The url_launcher package code works even for a mobile device but it opens a new browser window to download the required file which is not a good user experience so I have used 2 approaches for the same problem.
Hope I have answered your query.