convert PDF data into octet-stream for printer autodetection - mime-types

I have a printer that only accepts application/octet-stream over IPP. My program downloads binary PDF data and I need to convert that into application/octet-stream, which would (supposedly) let the printer decide what to print. However, when I send the data, it just prints binary data as text and not as formatted PDF. I'm using node with npm package 'ipp'.

I had a problem similar to that, in this link! I found a working example that, I modified a little like this to work (mixed some with the pdfkit! example, but shorted).
Here is my working version (node v16.17.0 | npm 8.15.0 | windows 11)
var ipp = require("ipp");
var concat = require("concat-stream");
var PDFDocument = require('pdfkit');
const doc = new PDFDocument();
// Pipe its output somewhere, like to a file or HTTP response
// Render some text
doc
.fontSize(25)
.text('Some text with an embedded font!', 100, 100);
// Add an image, constrain it to a given size, and center it vertically and horizontally
doc.image('./my-image.png', {
fit: [250, 300],
align: 'center',
valign: 'center'
});
doc.pipe(concat(function (data) {
//I used this url with a Brother printer, because the 631 port had some weird problem
var printer = ipp.Printer("http://<ip address>:80/ipp",{version:'2.0'});
var file = {
"operation-attributes-tag":{
"requesting-user-name": "User",
"job-name": "Print Job",
"document-format": "application/octet-stream"
},
data: data
};
printer.execute("Print-Job", file, function (err, res) {
//in case of error
console.log("Error: ",err);
console.log('res',res);
});
}));
//This last line is very important!
doc.end();
note that the version you have to check if your printer supports it
I checked that with this code: (I lost the link where I found this, so that is why there is not reference to it)
var ipp = require('ipp');
var uri = "http://<ip address>:80/ipp";
var data = ipp.serialize({
"operation":"Get-Printer-Attributes",
"operation-attributes-tag": {
"attributes-charset": "utf-8",
"attributes-natural-language": "en",
"printer-uri": uri
}
});
ipp.request(uri, data, function(err, res){
if(err){
return console.log(err);
}
console.log(JSON.stringify(res,null,2));
})

Related

How to extract the base64 from an image in Angular NGX Dropzone

Hey guys I am using NGX Dropzone and I notice when I drag an image into the viewer it is in base64, but when I try to read the console.log(event.addedFiles); I have no information being passed to me with the base64 value. Here's an example of what I get back
[File]
0: File
lastModified: 1625149167659
lastModifiedDate: Thu Jul 01 2021 10:19:27 GMT-0400 (Eastern Daylight Time) {}
name: "210534431_764639924207804_238792847075232344_n.jpeg"
size: 101133
type: "image/jpeg"
webkitRelativePath: ""
__proto__: File
length: 1
__proto__: Array(0)
I have another piece of code which I have been using that transforms a URL into a base64 string. But thats useless to me since the URL can also be shared and opened by anyone from anywhere. However my local image in my computer is only available to me, unless I transform it into base64 which is a string I can save in a database.
This is the script
imageToShow: any;
onURLinserted() {
this.getImage(this.thumb.name).subscribe(data => {
this.createImageFromBlob(data);
}, error => {
console.log("Error occured",error);
});
console.log("Data: ", this.thumb.name);
}
getImage(imageUrl: string): Observable<Blob> {
return this.http
.get<Blob>(imageUrl, { observe: 'body', responseType: 'blob' as 'json' })
}
createImageFromBlob(image: Blob) {
let reader = new FileReader(); //you need file reader for read blob data to base64 image data.
reader.addEventListener("load", () => {
this.imageToShow = reader.result; // here is the result you got from reader which I use to view the image
this.selectedRowData.photo = reader.result; // this is my ngModel read by my HTML input fields
}, false);
if (image) {
reader.readAsDataURL(image);
}
}
//In my HTML code
<img [src]="imageToShow" alt="">
All I am really trying to do is extract the base64 information from the image dragged in there into imageToShow either by using this code if it helps or something similar OR maybe the cdk drag an drop already has a prop that I dont know about
How do I know that the base64 is even available? When I drag an image in it, and I inspect it in the dev tool I can see the src="data:image/jpeg;base64,random stuff..."
Wish I could put some test code here but I will need the dropzone library for it
Looks like ngx-dropzone does not have a prop that provides bas64String.
You can use readAsDataURL to get base64String. The readAsDataURL is used to read the contents of the Blob or File. When the loadend is triggered. At that time, the result attribute contains the data as a data: URL representing the file's data as a base64 encoded string.
The below code worked for me.
html file
<div class="custom-dropzone" ngx-dropzone [accept]="'image/jpeg,image/jpg,image/png,image/gif'"
(change)="onSelect($event)">
<ngx-dropzone-label>
<div>
<h2>Upload photo</h2>
</div>
</ngx-dropzone-label>
<ngx-dropzone-image-preview ngProjectAs="ngx-dropzone-preview" *ngFor="let f of files" [file]="f"
[removable]="true" (removed)="onRemove(f)">
</ngx-dropzone-image-preview>
</div>
.ts file
onSelect(event) {
this.files.push(...event.addedFiles);
if (this.files && this.files[0]) {
for (let i = 0; i < this.files.length; i++) {
this.fileToBase64(this.files[i])
.then(result=>{
const base64String = result.replace('data:', '')
.replace(/^.+,/, ''); // To remove data url part
this.postMultimedias.push({ name:this.files[i].name,content:
base64String});//postMultimedias is a array which holds image name and bas64String
});
}
}
}
fileToBase64 = (file:File):Promise<string> => {
return new Promise<string> ((resolve,reject)=> {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result.toString());
reader.onerror = error => reject(error);
})
}
onRemove(event) {
let position = this.files.indexOf(event);
this.postMultimedias.splice(position, 1);
this.files.splice(position, 1);
}

Using TinyMCE uploading images to a backend

I am trying to use the rich text editor TinyMCE for a blog platform I am currently working on.
I am also using React with a Flask backend. A
User should be able to create a blog entry with the editor and also use/ upload images.
I got everything setup but I don't know how to store the images in my backend so you can save a blog with all it's content.
I got this callback function from their documentation but I do not really understand what's happening there and if it is enough to send the file object to my backend and store it in the database.
file_picker_callback: function (cb, value, meta) {
var input = document.createElement("input");
input.setAttribute("type", "file");
input.setAttribute("accept", "image/png , image/jpg");
input.onchange = function () {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function () {
var id = "blobid" + new Date().getTime();
var blobCache =
window.tinymce.activeEditor.editorUpload.blobCache;
var base64 = reader.result.split(",")[1];
var blobInfo = blobCache.create(id, file, base64);
blobCache.add(blobInfo);
/* call the callback and populate the Title field with the file name */
cb(blobInfo.blobUri(), { title: file.name });
};
reader.readAsDataURL(file);
console.log(file);
};
This is the console.log(file) output
File {name: "wlogLogo.png", lastModified: 1590578382000, webkitRelativePath: "", size: 4591, type: "image/png", …}

How can I get Alexa to read the contents of a single line web page

I have an external webpage that contains only the following:-
{"date":"25 December 2017"}
Using node.js, how can I get Alexa to read (and say) the date from the webpage.
You can use "http" or "https" package in Node to do this. JSON.parse(responsestring) could easily parse the content you have shown above.
Your external webpage link would replace "yourendpoint" in below code.
var http = require("http");
http.get(yourendpoint, function (response) {
// console.log("response:" + response);
// data is streamed in chunks from the server
// so we have to handle the "data" event
var buffer = "", data;
response.on("data", function (chunk) {
buffer += chunk;
});
response.on("end", function (err) {
if(err) {
speechOutput = "I am sorry, I could not get the data from webpage ."
} else {
console.log("response:" + buffer);
// Parse your response the way you want
speechOutput = "<<Your desired output>>"
}
}
this.emit(':tell', speechOutput);
});
});

Is there a way to dump a thousand images somewhere and extract them using REST Api?

Here is the thing:-
I have over a thousand images saved locally in my mac. I have a landing page that mocks an ecommerce deal site. It would be tedious to have to manually type in the src url in the img tag for a thousand pictures. Thus, i thought i could somehow have this images dumped in a cloud storage or something and use REST api get method to extract these images in a response.data. Then assign it to a $scope variable and use ng-repeat to bind the images in my landing page view. Is this possible? If not, what are the alternatives? SQL database?
Appreciate your help. P.S. I am totally a beginner at web development.
Install node.js. It's Javascript for a server which should make it pretty easy since you already know Javascript.
On a Mac, you can install node like this:
brew install node
Use this node.js code (credit to codepedia.com, tweaked a little by me):
//include http, fs and url module
var http = require('http'),
fs = require('fs'),
path = require('path'),
url = require('url');
imageDir = './images/';
//create http server listening on port 3333
http.createServer(function (req, res) {
//use the url to parse the requested url and get the image name
var query = url.parse(req.url,true).query;
pic = query.image;
if (typeof pic === 'undefined') {
getImages(imageDir, function (err, files) {
var imageList = JSON.stringify(files);
res.writeHead(200, {'Content-type':'application/json'});
res.end(imageList);
});
} else {
//read the image using fs and send the image content back in the response
fs.readFile(imageDir + pic, function (err, content) {
if (err) {
res.writeHead(400, {'Content-type':'text/html'})
console.log(err);
res.end("No such image");
} else {
//specify the content type in the response will be an image
res.writeHead(200,{'Content-type':'image/jpg'});
res.end(content, "binary");
}
});
}
}).listen(3333);
console.log("Server running at http://localhost:3333/");
//get the list of jpg files in the image dir
function getImages(imageDir, callback) {
var fileType = '.jpg',
files = [], i;
fs.readdir(imageDir, function (err, list) {
for(i=0; i<list.length; i++) {
if(path.extname(list[i]) === fileType) {
files.push(list[i]); //store the file name into the array files
}
}
callback(err, files);
});
}
Run this from the command line to start you new image server (assuming you named the file "server.js"):
node server.js
You should see this text appear on the command line:
Server running at http://localhost:3333/
You can quickly test it by going to this address in your browser and you should see a JSON object showing you an array of all the filenames in the "./images" directory. By the way, this program assumes you're putting the images folder in the same directory as "server.js". You can put the images directory anywhere and just change the path of the variable "imageDir".
Now you can load the list of files from Angular using this code in your controller:
$http.get("http://localhost:3333", function(data) {
$scope.images = data;
});
In your view, you can now use an ng-repeat like this to display all the images:
<div ng-repeat="image in images" style="padding: 8px">
<img src="http://localhost:3333/image={{ image }}">
</div>
Note: this will work if you run it locally on your Mac or if you upload all the images to a server on which you can use Node.js.

How to save WAV Blob to MongoDB, retrieve and serve correctly with Node?

I've found many posts dealing with saving binary files using the Mongoose Buffer SchemaType. However, most of them deal with image files, and I haven't been able to get them to work with a WAV audio file.
I'm using Recorder.js to save audio recordings from the built-in microphone. I use Recorder.js' exportWAV function to get a BLOB from the finished recording, then read the blob with FileReader and send it to the Node/Express backend where it is then saved to the DB. I've checked using the Mongo CLI and there is data being saved to the relevant field (starting with BinData(0,"UklGR.lotsofdatahere..="). When I try to get the recording by sentence id, the server responds with an appropriately-MIME-typed .wav file that is unplayable.
It seems that I'm missing something in the way that the files are encoded and decoded for storage in MongoDB. When reading the blob spit out by Recorder.js, it looks like it's already base64 encoded. So that's why I tried loading it as a base64 Buffer before saving to Mongo, and then decoding from a base64 buffer on output. What am I missing here? How can I fix these encoding issues? Thanks!
Note: I don't necessarily need GridFS because these files are well under 16MB. Although, if it's a lot faster to stream files from GridFS, maybe I should switch to that solution. However, I'd like to figure out what's wrong with this approach first.
Here's the relevant code from the Angular frontend:
$scope.start = function() {
$scope.rec.record();
}
$scope.export = function() {
$scope.rec.stop();
$scope.rec.exportWAV(function blobCallback(blob) {
$scope.rec.clear();
var reader = new FileReader();
reader.onload = function(event) {
$.ajax({
type: 'POST',
url: '/saveRecording',
data: {
audio: event.target.result,
text: $scope.text,
timestamp: new Date()
}
}).done(function(data) {
console.log(data);
});
}
reader.readAsDataURL(blob);
});
}
The Express routes:
router.post('/saveRecording', function(request, response, next) {
var sentence = new Sentence();
sentence.audio = new Buffer(request.body.audio, 'base64');
sentence.timestamp = request.body.timestamp;
sentence.text = request.body.text;
// Save sentence to DB with Mongoose
sentence.save(function(error, sentence) {
if (error) {
return next(error);
}
// If no error, send added sentence back to the client.
response.json(sentence);
});
});
router.get('/getRecording/:sentenceId', function(request, response, next) {
Sentence.findById(request.params.sentenceId,
function dbCallback (error, sentence) {
if (error) {
return next(error);
}
if (!sentence) {
return next(new Error('Can\'t find sentence'));
}
var base64Audio = new Buffer(sentence.audio, 'base64');
response.writeHead(200, {
'Content-Type': 'audio/x-wav',
'Content-Length': base64Audio.length
});
response.write(base64Audio);
response.end();
});
});
The Mongoose Schema for Sentences:
var SentenceSchema = new mongoose.Schema({
text: String,
audio: Buffer,
timestamp: Date
});
You can try using GridFs for storing your audio files
check that link

Resources