data:application/pdf;base64,undefined (pdf-generation problem) - pdf

I was creating a pdf generator following guidelines from this website "https://www.wix.com/velo/forum/coding-with-velo/pdf-generator-api-npm-demo"
code screenshot
I copy every code from the guideline, but when I click the submit button, error of [data:application/pdf;base64,undefined] occur, and no record is saved at the pdf generator.
Check the link of the website here: website link
I believe it should be something wrong with the code below
//code start
import { pdf } from 'backend/pdf.jsw';
$w.onReady(function () {
var base64;
$w('#btnSubmit').onClick(() => {
let name = $w('#inName').value;
let detail = $w('#inDetail').value;
pdf(name, detail).then( e => {
base64 = e;
base64 = 'data:application/pdf;base64,' + base64
let msg = {
"conv": true,
"dataUrl": base64
}
$w('#html1').postMessage(msg);
});
});
});
// Code end
I search through the internet and some mentioned open data URl directly function is not supported since 2020 (see website). I am new in programme or codes, it would be greatful if someone could provide me the adjusted code.
Sorry for the trouble

Related

React Native cheerio.load() not working properly neither is JSDOM library

Well I'm new to this app development thing especially react-native and I wanted to know when I'm trying to scrap a website using cheerio and axios in react-native and then save it to firebase realtime database in the following way:
and yes i have done all the imports and also initalized my app using firebaseConfig
const db = firebase.database();
async function loadFurniture() {
const Url = 'https://hoid.pk/product-category/bedroom/beds-bedroom/';
const html = await axios.get(Url); // fetch page
const $ = cheerio.load(html); //parse html String
const furniture = [];
$('.product-wrapper ').each((i, element) => {
const title = $(element).find('h2.product-name').text();
const imageUrl = $(element).find('img.primary_image').attr('src');
const price = $(element).find('span.woocommerce-Price-amount amount').text();
console.log(title);
furniture.push({ title, imageUrl, price });
});
// Save the furniture to the Firebase Realtime Database
db
.ref('/furniture/bed')
.set({
title: furniture.title,
price: furniture.price,
object_image : furniture.imageUrl,
})
.then(() => console.log('Data set.'));
console.log(furniture);
// Return the extracted information
return furniture;
}
and then calling this function in a button
<Button
title="Fetch"
onPress = {() => loadFurniture() }
/>
The data was not being scraped so I tried to console.log() the data being fetched.
Whenever I click the button there is no error but just a log [ Function initialize ] with respect to console.log(title)
And before anyone says yup I've looked into the structure and 9it does returns me my desired classes after axios.get()
I just want to know that if there's some error in my code or if I'm going wrong somewhere.
I tried to scrap furniture titles, images and prices from certain website and then save it to database for any further use but it's just not working.
I've checked my network issues the html page being scraped and everything else one can think of. Now i just want to know either my code is accurate or if there's some mistake.
I tired to scrap the data of same website using python and it scraps it perfectly.
Edit:
I found out that the cheerio.load() function is not working there was no problem with the database... Is there some problem with cheerio.load() in it's latest version "1.0.0-rc.12" ?? If so what's the solution... I've tried number of libraries and each is giving a different kind of error so cheerio might be the only possible solution so if there's an alternative way of using cheerio.load() in react native do let me know.

Adobe PDF Embed API Save Content To Base64

Using Adobe PDF Embed API, you can register a callback:
this.adobeDCView = new window.AdobeDC.View(config);
this.adobeDCView.registerCallback(
window.AdobeDC.View.Enum.CallbackType.SAVE_API, (metaData, content, options) => {
})
Content is according to the docs here: https://www.adobe.io/apis/documentcloud/dcsdk/docs.html?view=view
content: The ArrayBuffer of file content
When I debug this content using chrome inspector, it shows me that content is a Int8Array.
Normally when we upload a pdf file, the user selects a file and we read as dataURI and get base64 and push that to AWS. So I need to convert this PDF's data (Int8Array) to Base64, so I can also push it to AWS.
Everything I have found online uses UInt8Array to base64, and I don't understand how to go from Int8Array to UInt8Array. I would think you can just add 128 to the signed int to get a ratio between 0-256, but this doesn't seem to work.
I have tried using this:
let decoder = new TextDecoder('utf8');
let b64 = btoa(decoder.decode(content));
console.log(b64);
But I get this error:
ERROR DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.
Please help me figure out how to go from Int8Array to Base64.
I use the function in this answer.
For Embed API, use the "content" parameter from the save callback as the input to the function.
You can see a working example at this CodePen. The functional part is below.
adobeDCView.registerCallback(
AdobeDC.View.Enum.CallbackType.SAVE_API,
function (metaData, content, options) {
/* Add your custom save implementation here...and based on that resolve or reject response in given format */
var base64PDF = arrayBufferToBase64(content);
var fileURL = "data:application/pdf;base64," + base64PDF;
$("#submitButton").attr("href", fileURL);
/* End save code */
return new Promise((resolve, reject) => {
resolve({
code: AdobeDC.View.Enum.ApiResponseCode.SUCCESS,
data: {
/* Updated file metadata after successful save operation */
metaData: { fileName: urlToPDF.split("/").slice(-1)[0] }
}
});
});
},
saveOptions
);

How to load an existing pdf and print using printing in flutter

I've been been trying to print an existing pdf file which is in sd card.
So i added printing package to my flutter project to print pdf files.
Printing package link
I checked their documentation and i can't find a way to load and print pdf.
Fyi, i can create a pdf from image, text or whaetever it is and pass it to the Printing function. That works as anticipated.
final pdf = Document();
pdf.addPage(Page(
pageFormat: PdfPageFormat.a4,
build: (Context context) {
return Center(
child: Text("Hello World"),
);
})
);
await Printing.layoutPdf(onLayout: (PdfPageFormat format) async => pdf.save());
Any help to load existing pdf and print would be appreciable
Thanks
I finally find a way to print pdf using printing plugin.
You can directly print pdf by giving the online pdf url
To do so, just use the following dart snippet
http.Response response = await http.get('http://www.africau.edu/images/default/sample.pdf');
var pdfData = response.bodyBytes;
await Printing.layoutPdf(onLayout: (PdfPageFormat format) async => pdfData);
Don't forget to import http plugin
import 'package:http/http.dart' as http;
Thanks everyone for the help
Including the other answers:
BTW, I have an another answer regarding this topic
Directly print from a URL
var data = await http.get(url);
await Printing.layoutPdf(onLayout: (_) => data.bodyBytes);
SharePdf function
var data = await http.get(url);
await Printing.sharePdf(bytes: data.bodyBytes, filename: 'your-document.pdf');
This one needs an extra one step to print.
View from the browser
Use this package url_launcher, open in a browser view, then print it
import 'package:url_launcher/url_launcher.dart';
if (await canLaunch(url)) {
await launch(url);
}
This solution needs an extra one step to print as well.
The flutter_pdf_printer package.
Use this package flutter_pdf_printer and path_provider
var data = await http.get(url);
final output = await getTemporaryDirectory();
final file = File('${output.path}/your_file_name_${new DateTime.now().microsecondsSinceEpoch}.pdf');
await file.writeAsBytes(data.bodyBytes);
await FlutterPdfPrinter.printFile(file.path);
*** this package will have channel registrant issue, please run flutter clean after installation ***
This package is a little bit outdated, but it works for me to print with a roller 80 size pdf. It uses the Swift UIKit package, which has good compatibility.
Welcome add comments.
This will help you to load the pdf on the screen.
import 'package:native_pdf_view/native_pdf_view.dart';
Widget pdfView() => FutureBuilder<PDFDocument>(
// Open document
future: PDFDocument.openAsset('assets/sample.pdf'),
builder: (_, snapshot) {
if (snapshot.hasData) {
// Show document
return PDFView(document: snapshot.data);
}
if (snapshot.hasError) {
// Catch
return Center(
child: Text(
'PDF Rendering does not '
'support on the system of this version',
),
);
}
return Center(child: CircularProgressIndicator());
},
);
To print the pdf file, use this package.
await FlutterPdfPrinter.printFile(file.path);
Here you can find a sample.
final Uint8List bytes = await pdf.save();
Printer? pri = await Printing.pickPrinter(context: context);
await Printing.directPrintPdf(
printer: pri!, onLayout: (PdfPageFormat format) async => bytes);
With this code you can view your printer and print the document for this i use
printing 5.9.3

Download a PDF generated by Apps Script via web app

I'm trying to figure out how to make a Google Apps Script deployed as a web app download a PDF that's generated on a click. It almost works, but the resulting file isn't valid. I can't figure out if it's an encoding issue or something else.
In Apps Script the code looks simple:
function makePDF() {
...
var pdfBlob = doc.getAs('application/pdf');
return Utilities.base64Encode(pdfBlob.getBytes());
}
In the browser, there's a click handler:
function clickHandler(ev) {
ev.preventDefault();
google.script.run
.withSuccessHandler(function(data) {
var pdf = new Blob([window.atob(data)]);
var href = window.URL.createObjectURL(pdf);
var link = document.querySelector('#hiddenLink');
link.href = href;
link.click();
})
.makePDF();
}
Any suggestions?
Thanks!
I figured it out, so posting the answer if anyone else is trying to pass a PDF from Apps Script to the client javascript. It's all much simpler than I had made it.
Rather than messing around with base64 encodings, just pass back the bytes array:
function makePDF() {
...
var pdfBlob = DocumentApp.openById('1234').getAs('application/pdf');
return pdfBlob.getBytes();
}
Now, on the client side, construct a new Blob from an ArrayBuffer. That's easy too:
function clickHandler(ev) {
google.script.run
.withSuccessHandler(function(data) {
var arr = new Uint8Array(data);
var blob = new Blob([arr.buffer], {type: 'application/pdf'});
var obj_url = window.URL.createObjectURL(blob);
var hiddenLink = document.getElementById('hiddenPDFLink');
hiddenLink.setAttribute('href', obj_url);
hiddenLink.setAttribute('download', 'filename.pdf');
hiddenLink.click();
})
.makePDF();
}
And that's it! Hope someone else finds this helpful.
I assume that your makePDF function is doing some other stuffs/Calculation and at the end you need that document to be downloaded to local computer.
What you can do is inside success handler
var link = document.querySelector('#hiddenLink');
link.href = "https://docs.google.com/feeds/download/documents/export/Export?id=**TheIdOfDocumenToBeDownloaded**&exportFormat=pdf";
link.click();
It will then give you a prompt to save document on to local computer.

KeystoneJS Cloudinary image upload

I am using the latest version of KeystoneJS and have a form working to add a record to the database.
I'm having trouble getting image uploads to work.
My model conatains:
heroImage: { type: Types.CloudinaryImage, autoCleanup : true },
My form includes:
<input type="file" accept="image/*" id="heroImage" name="heroImage_upload" className='field-upload'>
and my middleware for saving the form simply includes:
view.on('post', {action: 'save'}, function(next)
{
var newProperty = new Property.model(req.body);
console.log(newProperty);
newProperty.save(function(err, body)
{});
});
which works great for all field's except the file upload.
I've tried adding:
newProperty.heroImage = req.files['heroImage'];
which leaves heroImage as null.
I also tried creating a cloudinaryImage but this causes an error:
var img = new CloudinaryImage(req.files['heroImage']);
It all works fine when I use the KeystoneJS admin dashboard to upload images. Can someone please explain how I should use the cloudinaryImage field type in my own form?
Thanks
Not sure if this will help, but there is a note at the bottom of the docs:
http://keystonejs.com/docs/database/#fieldtypes-cloudinaryimage
"Remember that if you are uploading images to a CloudinaryImage field using an HTML form, you need to specify enctype="multipart/form-data" in your form tag."
Have you included that in your form?
Update:
So, the following should work, assuming your model is called MyModel, and your form data uses the same object keys as your model. (i.e. the image for your heroImage field should be provided as heroImage in the POST data).
var MyModel = keystone.list('MyModel');
view.on('post', {action: 'save'}, function(next)
{
var item = new MyModel.model();
data = req.body;
item.getUpdateHandler(req).process(data, function(err) {
// Handle error
}
}
Keystone should then handle all the specific cloudinary stuff internally.
Here is a way to do it with cloudinary.v2
untested keystone
cloudinary.v2.uploader.upload(base64_file_data, (err, result) => {
var newMyModel = new MyModel.model(model_data);
newMyModel.image = result;
let updater = newMyModel.getUpdateHandler(req);
updater.process(newMyModel, {
fields: image
}, err => {...})
})
tested mongoose
cloudinary.v2.uploader.upload(base64_file_data, (err, result) => {
var newMyModel = new MyModel.model(model_data);
newMyModel.image = result;
newMyModel.save(err => {...})
})