Error when merging multiple pdf files into one file in Google Drive - pdf

I used the following code (taken from PDF.CO) to merge multiple pdf files in Google Drive:
/**
* Initial Declaration and References
*/
// Get the active spreadsheet and the active sheet
ss = SpreadsheetApp.getActiveSpreadsheet();
ssid = ss.getId();
// Look in the same folder the sheet exists in. For example, if this template is in
// My Drive, it will return all of the files in My Drive.
var ssparents = DriveApp.getFileById(ssid).getParents();
// Loop through all the files and add the values to the spreadsheet.
var folder = ssparents.next();
/**
* Add PDF.co Menus in Google Spreadsheet
*/
function onOpen() {
var menuItems = [
{name: 'Get All PDF From Current Folder', functionName: 'getPDFFilesFromCurFolder'},
{name: 'Merge PDF URLs Listed In Cell', functionName: 'mergePDFDocuments'}
];
ss.addMenu('PDF.co', menuItems);
}
/**
* Get all PDF files from current folder
*/
function getPDFFilesFromCurFolder() {
var files = folder.getFiles();
var pdfUrlCell = ss.getRange("A4");
var allFileUrls = [];
while (files.hasNext()) {
var file = files.next();
var fileName = file.getName();
if(fileName.endsWith(".pdf")){
// Make File Pulblic accessible with URL so that it can be accessible with external API
var resource = {role: "reader", type: "anyone"};
Drive.Permissions.insert(resource, file.getId());
// Add Url
allFileUrls.push(file.getDownloadUrl());
}
pdfUrlCell.setValue(allFileUrls.join(","));
}
}
function getPDFcoApiKey(){
// Get PDF.co API Key Cell
let pdfCoAPIKeyCell = ss.getRange("B1");
return pdfCoAPIKeyCell.getValue();
}
/**
* Function which merges documents using PDF.co
*/
function mergePDFDocuments() {
// Get Cells for Input/Output
let pdfUrlCell = ss.getRange("A4");
let resultUrlCell = ss.getRange("B4");
let pdfUrl = pdfUrlCell.getValue();
// Prepare Payload
const data = {
"async": true, // As we have large volumn of PDF files, Enabling async mode
"name": "result",
"url": pdfUrl
};
// Prepare Request Options
const options = {
'method' : 'post',
'contentType': 'application/json',
'headers': {
"x-api-key": getPDFcoApiKey()
},
// Convert the JavaScript object to a JSON string.
'payload' : JSON.stringify(data)
};
// Get Response
// https://developers.google.com/apps-script/reference/url-fetch
const resp = UrlFetchApp.fetch('https://api.pdf.co/v1/pdf/merge', options);
// Response Json
const respJson = JSON.parse(resp.getContentText());
if(respJson.error){
console.error(respJson.message);
}
else{
// Job Success Callback
const successCallbackFn = function(){
// Upload file to Google Drive
uploadFile(respJson.url);
// Update Cell with result URL
resultUrlCell.setValue(respJson.url);
}
// Check PDF.co Job Status
checkPDFcoJobStatus(respJson.jobId, successCallbackFn);
}
}
/**
* Checks PDF.co Job Status
*/
function checkPDFcoJobStatus(jobId, successCallbackFn){
// Prepare Payload
const data = {
"jobid": jobId
};
// Prepare Request Options
const options = {
'method' : 'post',
'contentType': 'application/json',
'headers': {
"x-api-key": getPDFcoApiKey()
},
// Convert the JavaScript object to a JSON string.
'payload' : JSON.stringify(data)
};
// Get Response
// https://developers.google.com/apps-script/reference/url-fetch
const resp = UrlFetchApp.fetch('https://api.pdf.co/v1/job/check', options);
// Response Json
const respJson = JSON.parse(resp.getContentText());
if(respJson.status === "working"){
// Pause for 3 seconds
Utilities.sleep(3 * 1000);
// And check Job again
checkPDFcoJobStatus(jobId, successCallbackFn);
}
else if(respJson.status == "success"){
// Invoke Success Callback Function
successCallbackFn();
}
else {
console.error(`Job Failed with status ${respJson.status}`);
}
}
/**
* Save file URL to specific location
*/
function uploadFile(fileUrl) {
var fileContent = UrlFetchApp.fetch(fileUrl).getBlob();
folder.createFile(fileContent);
}
It runs perfectly the first time, but then gives an error:
Exception: Request failed for https://api.pdf.co returned code 402. Truncated server response: {"status":"error","errorCode":402,"error":true,"message":"Not enough credits, subscription expired or metered use is not allowed. Please review cre... (use muteHttpExceptions option to examine full response).

Related

Suitescript error: TypeError: Cannot set property "JSZipSync" of undefined

I have the following script where I am getting an error message:
org.mozilla.javascript.EcmaError: TypeError: Cannot set property
"JSZipSync" of undefined to
"org.mozilla.javascript.InterpretedFunction#6e57e155"
(/SuiteScripts/Suitelet to Excel.js#17(eval)#2)
According to Netsuite support, there are no issues with the script and they are not getting this error message
/**
*#NApiVersion 2.x
*#NScriptType Suitelet
*/
define(["N/search", "N/file", "N/https"], function (search, file, https) {
function onRequest(context) {
// Load the xlsx library from the CDN
var response = https.get({
url: "https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.0/xlsx.full.min.js",
});
var script = response.body;
eval(script);
// Replace this with the ID of the saved search you want to run
var searchId = "customsearch_my_saved_search";
// Run the search and get the results
var searchResult = search.load({
id: searchId,
});
var searchRows = searchResult.run().getRange({
start: 0,
end: 1000,
});
// Create an array to hold the data for the Excel file
var data = [];
// Add the column names as the first row
var columnNames = [];
searchResult.columns.forEach(function (column) {
columnNames.push(column.label);
});
data.push(columnNames);
// Add the search results to the data array
searchRows.forEach(function (row) {
var rowData = [];
searchResult.columns.forEach(function (column) {
rowData.push(
row.getValue({
name: column.name,
})
);
});
data.push(rowData);
});
// Create the Excel file
var ws = XLSX.utils.aoa_to_sheet(data);
var wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
var binaryData = XLSX.write(wb, {
type: "binary",
bookType: "xlsx",
});
var fileName = "search_results.xlsx";
var folderId = -4; // -4 represents the "Home" folder in the file cabinet
var file = file.create({
name: fileName,
fileType: file.Type.EXCEL,
contents: binaryData,
folder: folderId,
});
// Send the file as a response to the user
context.response.writeFile({
file: file,
isInline: true,
});
});
}
return {
onRequest: onRequest,
};
});
I can't tell where I am going wrong?
The JSZipSync is a function in the xlsx.full.min.js library which I believe I have loaded correctly.
I have also tried storing this file in the filing cabinet and referencing that instead of a link to the CDN website.
The same error message is generated in both cases

Google Sheets integrate with Mailerlite using API - to add multiple subscribers from Google Sheet to Mailerlite

I would like help with a google apps script. I would like to connect a Google sheet to the Mailerlite API in order to add multiple subscribers.
I would like to post each individual row from the google sheet as a subscriber in Mailerlite.
I would like a google sheet updated with the log of API responses with each trigger.
Here is the code I am using but can't get it to work. Thanks for your help!
function postUsersData() {
function getDataFromSpreadsheet() {
var usersSheetId = 11111111 // // Put your SHEET ID here
var usersSheet = getSheetById(usersSheetId)
// Users data
var values = usersSheet.getDataRange().getValues()
return values.map(function(value) {
return makePayload(values[0], value)
})
}
function postDataToMailerlite(payload) {
// API data
var url = 'https://api.mailerlite.com/api/v2/groups/'
var token = 'xxxxxxxxxxxxxxxxx' // // Put your TOKEN here
var groupId = 11111111 // // Put your GROUP ID here
var groupUrl = url + groupId + '/subscribers/import'
var params = {
'method': 'POST',
'muteHttpExceptions': true,
'headers': {
'Authorization': 'apikey ' + token,
'Content-Type': 'application/json'
},
'payload': JSON.stringify({'subscribers': payload, 'resubscribe': false, 'autoresponders': true})
};
var response = UrlFetchApp.fetch(groupUrl, params)
return JSON.parse(response.getContentText())
}
function logAction(json) {
var logsSheetId = 11111111 // // Put your SHEET ID here
var logsSheet = getSheetById(logsSheetId)
var logsSheetValues = logsSheet.getDataRange().getValues()
var payload = {
'datetime': Date(),
'imported': json.imported.length,
'unchanged': json.unchanged.length,
'updated': json.updated.length,
'errors': json.errors.length,
'errors log': json.errors
}
Object.keys(payload).forEach(function(key) {
logsSheet.getRange(logsSheetValues.length + 1, logsSheetValues[0].indexOf(key) + 1).setValue(payload[key])
})
Logger.log('Done ' + Date())
}
function getSheetById(id) {
// Get sheet by ID
return SpreadsheetApp.getActive().getSheets().filter(
function(s) {return s.getSheetId() === id;})[0];
}
function makePayload(headers, value) {
// Make single user data JSON from data based on row number
return {
'email': value[headers.indexOf('email')],
'fields': {
'full_name': value[headers.indexOf('name')],
'job': value[headers.indexOf('job')],
'trigger': value[headers.indexOf('trigger')]
}
}
}
// Perform
const data = getDataFromSpreadsheet()
const response = postDataToMailerlite(data)
logAction(response)
}

Merge PDF in ConvertAPI using Google Apps Script

I'm attempting to merge two PDF files from Google Drive via ConvertAPI with the following code. Both pdf1 and pdf2 are file objects.
function mergePDFs(pdf1,pdf2){
const formData = ""
formData['Files[0]'] = pdf1.getBlob();
formData['Files[1]'] = pdf2.getBlob();
Logger.log(formData['Files[0]']);
Logger.log(formData);
endpoint = "https://v2.convertapi.com/convert/pdf/to/merge?Secret=XXXXXXXXXXXXX&StoreFile=true"
var options = {
'method' : 'post',
'payload' : formData,
'muteHttpExceptions': true
};
Logger.log(UrlFetchApp.fetch(endpoint,options));
}
To which I receive the following error code:
{"Code":4000,"Message":"Parameter validation error.","InvalidParameters":{"Files":["Files array item count must be greater than 0."]}}
It should be noted both Logger.log() statement come up empty. It appears to me that assignments of pdf1 and pdf2 to formData['Files[index]'] are not
I have modified the following lines considerably as I'm not familiar with this syntax, but it was referenced on another Stack Overflow post.
formData['Files[0]'] = pdf1.getBlob();
formData['Files[1]'] = pdf2.getBlob();
I'm also finding that the declaration of formData is inconsequential regardless of whether it's declared as an array or as a string.
Lastly, the pertinent documentation from ConvertAPI says:
Files to be converted. Value can be URL or file content. If used in >query or multipart content parameter must be suffixed with index >e.g. Files[0], Files1, Files[2]...
The following lines from the main function are the pertinent ones to the function in question:
//lodgingRecieptId is set to a url
const receiptFile = DriveApp.getFileById(lodgingReceiptId);
...
const copyID = frontPage.makeCopy().getId();
const copyDoc = DocumentApp.openById(copyID)
copyDoc.setName("MPD | " + sheet.getLastRow());
const body = copyDoc.getBody();
//find and replace in template copy
body.replaceText("{{AMOUNT}}",amount)
body.replaceText("{{CURRENT_DATE}}",current_date)
body.replaceText("{{LOCATION}}",location)
body.replaceText("{{PURPOSE}}",purpose);
body.replaceText("{{DEPART_DATE}}",formatLeaveDate);
body.replaceText("{{RETURN_DATE}}",formatReturnDate);
body.replaceText("{RSB} ",rsb);
body.replaceText("{{DAYS}}",days);
body.replaceText("{{MPD_AMOUNT}}",mpdAmount);
const docBlob = copyDoc.getAs('application/pdf');
docBlob.setName(copyDoc.getName() + ".pdf");
const copyPdf = DriveApp.createFile(docBlob);
//merge lodging receipt and template copy ——> Save id
mergePDFs(copyPdf,receiptFile)
From your showing script and your showing official document, how about the following modification?
Modified script:
Please replace <YOUR SECRET HERE> with your secret.
function mergePDFs(pdf1, pdf2) {
var fileValues = [pdf1.getBlob(), pdf2.getBlob()].map((e, i) => ({
"Name": e.getName() || `sample${i + 1}`,
"Data": Utilities.base64Encode(e.getBytes())
}));
var data = { "Parameters": [{ "Name": "Files", "FileValues": fileValues }, { "Name": "StoreFile", "Value": true }] };
var endpoint = "https://v2.convertapi.com/convert/pdf/to/merge?Secret=<YOUR SECRET HERE>";
var options = {
'method': 'post',
'payload': JSON.stringify(data),
'contentType': "application/json",
'muteHttpExceptions': true
};
var res = UrlFetchApp.fetch(endpoint, options);
var outputPDFURL = JSON.parse(res.getContentText()).Files[0].Url;
var outputFile = UrlFetchApp.fetch(outputPDFURL).getBlob().setName("sampleOutput.pdf");
DriveApp.createFile(outputFile);
}
Note:
In this modification, it supposes that your secret is valid for using this API and pdf1 and pdf2 are the file object or the HTTPResponse object of the PDF data. Please be careful about this.
References:
Merge PDF API
fetch(url, params)

Open pdf from bytes array in angular 5

I was following the below links for displaying pdf page in new tab in my angular 5 application. But unable to achieve the result.
I am consuming the bytes array from spring controller api.
PDF Blob is not showing content, Angular 2
PDF Blob - Pop up window not showing content
Angular2 Displaying PDF
I tried the below options but none of them is working.
Trial 1
Consumed the response as json
component.ts
clickEvent(){
this.service.getPDF().subscribe((response)=>{
let file = new Blob([response.byteString], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
})
}
service.ts
getPDF(){
const url = `${this.serviceUrl}/pdf`;
const httpOptions = {
headers: new HttpHeaders(
{
'Accept': 'application/json',
'responseType':'blob'
}
)
};
return this.http.get<any>(url, httpOptions);
}
Trial 2
Consumed the response as json
component.ts
clickEvent(){
this.service.getPDF().subscribe((response)=>{
let file = new Blob([response.byteArray], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
})
}
service.ts
getPDF(){
const url = `${this.serviceUrl}/pdf`;
const httpOptions = {
headers: new HttpHeaders(
{
'Accept': 'application/json',
'responseType':'arraybuffer'
}
)
};
return this.http.get<any>(url, httpOptions);
}
Trial 3
Consumed the response as bytes
component.ts
clickEvent(){
this.service.getPDF().subscribe((response)=>{
let file = new Blob([response], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
})
}
service.ts
getPDF(){
const url = `${this.serviceUrl}/pdf`;
const httpOptions = {
headers: new HttpHeaders(
{
'responseType':'blob' //both combination
//'responseType' : 'arraybuffer'
}
)
};
return this.http.get<any>(url, httpOptions);
}
By all the combination I am only getting two results.
Empty pdf document or Failed to load PDF document.
For understanding posting java spring controller code.
controller.java
#GetMapping(value = "/pdf")
public ResTest generatePDF(HttpServletResponse response) throws IOException {
ResTest test = new ResTest();
ByteArrayOutputStream baos = docTypeService.createPdf();
test.setByteArray(baos.toByteArray());
test.setByteString(new String(baos.toByteArray()));
return test;
}
At last, I was able to render pdf. There were two small mistakes from my side.
1 st Problem was, I gave 'responseType' inside HttpHeaders which was wrong.
It should be outside as below.
2 nd Problem was, even though if you mention as responseType : 'arraybuffer', it was unable to take it. For that you need to mention as responseType : 'arraybuffer' as 'json'.(Reference)
The corrected and working code below.
Trial 3
component.ts (nochanges)
clickEvent(){
this.service.getPDF().subscribe((response)=>{
let file = new Blob([response], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
})
service.ts
getPDF(){
const url = `${this.serviceUrl}/pdf`;
const httpOptions = {
'responseType' : 'arraybuffer' as 'json'
//'responseType' : 'blob' as 'json' //This also worked
};
return this.http.get<any>(url, httpOptions);
}
Referred from the below link
https://github.com/angular/angular/issues/18586
I had the same problem with angular and pdf display. I will describe my solution - use base64 encoded string. All modern browsers support base64.
Use import java.util.Base64 to decode your byte array
byte[] bytes = baos.toByteArray();
String string = Base64.getEncoder().encodeToString(bytes);
test.setByteString(string);
On the frontend side use standard mime type for pdf and indicate that you are using base64 data:application/pdf;base64,.
Ref. to mime types: https://en.wikipedia.org/wiki/Media_type
If you need to open document in a new window:
let newPdfWindow = window.open("","Print");
let content = encodeURIComponent(response.byteString);
let iframeStart = "<\iframe width='100%' height='100%' src='data:application/pdf;base64, ";
let iframeEnd = "'><\/iframe>";
newPdfWindow.document.write(iframeStart + content + iframeEnd);
If you need to open in a new tab, you may simply provide to your html href:
let pdfHref = this.sanitizer.bypassSecurityTrustUrl('data:application/octet-stream;base64,' + content);
bypassSecurityTrustUrl will sanitize your url. As I remember there was some problem with angular security, that prevented me from seeing the content.
PS. before checking how it works with angular I would like to recommend you to store the pdf file on a drive and try to open it. I mean, that you should be certainly sure that you file is valid and you may open it with simple reader.
Update. The simpliest solution is to use pdf.js library https://github.com/mozilla/pdf.js
Have you looked for an angular component to wrap pdf.js?
https://github.com/VadimDez/ng2-pdf-viewer
Sample usage:
<pdf-viewer [src]="pdfSrc"
[render-text]="true"
style="display: block;">
</pdf-viewer>
pdfSrc can be a url string or a UInt8Array
When you make AJAX call to get PDF/file stream
var req = this.getYourPDFRequest(fd);
this.postData(environment.previewPDFRFR, req).then(res => {
res.blob().then(blob => {
const fileURL = URL.createObjectURL(blob);
window.open(fileURL, '', 'height=650,width=840');
})
});
If ur byte array comes from a .net backend u have to return
return File(doc.BinaryData, "application/pdf"); // page visible in typescript
, and not this :
return Ok(doc.BinaryData); // page blank in typescript

Win 8 Apps : saving and retrieving data in roamingfolder

I'm trying to store few user data into a roamingFolder method/property of Windows Storage in an app using JavaScript. I'm following a sample code from the Dev Center, but no success. My code snippet is as follows : (OR SkyDrive link for the full project : https://skydrive.live.com/redir?resid=F4CAEFCD620982EB!105&authkey=!AE-ziM-BLJuYj7A )
filesReadCounter: function() {
roamingFolder.getFileAsync(filename)
.then(function (filename) {
return Windows.Storage.FileIO.readTextAsync(filename);
}).done(function (data) {
var dataToRead = JSON.parse(data);
var dataNumber = dataToRead.count;
var message = "Your Saved Conversions";
//for (var i = 0; i < dataNumber; i++) {
message += dataToRead.result;
document.getElementById("savedOutput1").innerText = message;
//}
//counter = parseInt(text);
//document.getElementById("savedOutput2").innerText = dataToRead.counter;
}, function () {
// getFileAsync or readTextAsync failed.
//document.getElementById("savedOutput2").innerText = "Counter: <not found>";
});
},
filesDisplayOutput: function () {
this.filesReadCounter();
}
I'm calling filesDisplayOutput function inside ready method of navigator template's item.js file, to retrieve last session's data. But it always shows blank. I want to save upto 5 data a user may need to save.
I had some trouble running your code as is, but that's tangential to the question. Bottom line, you're not actually reading the file. Note this code, there's no then or done to execute when the promise is fulfilled.
return Windows.Storage.FileIO.readTextAsync(filename);
I hacked this in your example solution and it's working... typical caveats of this is not production code :)
filesReadCounter: function () {
roamingFolder.getFileAsync(filename).then(
function (filename) {
Windows.Storage.FileIO.readTextAsync(filename).done(
function (data) {
var dataToRead = JSON.parse(data);
var dataNumber = dataToRead.count;
var message = "Your Saved Conversions";
//for (var i = 0; i < dataNumber; i++) {
message += dataToRead.result;
document.getElementById("savedOutput1").innerText = message;
//}
//counter = parseInt(text);
//document.getElementById("savedOutput2").innerText = dataToRead.counter;
}, function () {
// readTextAsync failed.
//document.getElementById("savedOutput2").innerText = "Counter: <not found>";
});
},
function () {
// getFileAsync failed
})
},