Tiff convert to png Node js - node.js

i have to convert multiple tiff to png. For example tiff which include 3 pages i should convert to 3 png's.So i am using tiff-to-png module and i have encountered with this problem.
Error: Command failed: convert /tiffs/one.tiff -scene 1 ./png/one/page%d.png
Invalid Parameter - /tiffs.Bellow is my code
'use strict'
const tiff_to_png=require('tiff-to-png');
const options={
logLevel:1
};
const converter=new tiff_to_png(options);
const tiffsLocation=['./tiffs/one.tiff'];
const location='./png';
converter.convertArray(tiffsLocation,location);
In the error context we see -/tiffs inavliiad parameter.
tiffsLocation is the variable which conatin my tiff file.
location is variable which contain path to folder where will be converted png file.
I cant understand why i have goten this error, tiffs in this case is the directory which contain my tiff file why i have got this error.Any ideas?

1st You have to install "Imagemagick"
For windows, you will find .exe file. Keep it in your mind that on installation time, check "Install legacy utilities (e.g: convert)"
For Ubuntu:
sudo apt install imagemagick
For Cent OS:
sudo yum install ImageMagick
var fs=require('fs');
var spawn = require('child_process').spawn;
//ifile: Tiff Absolute File Path
//ofile: PNG Absolute File Path (e.g: var ofile = APP_ROOT_PATH+'/data/files/png/sample.png';)
var tiff2png = spawn('convert', [ifile, ofile]);
tiff2png.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
tiff2png.stderr.on('data', function (data) {
return res.json(Utility.output('Unable to convert tiff to png','ERROR'));
console.log('stderr: ' + data);
});
tiff2png.on('close', function (code) {
/**Check Your Converted file exist or not. If exist then Converted**/
console.log('Close: ' + data);
});
tiff2png.on('error', function (code) {
return res.json(Utility.output('ERROR: Unable to convert tiff to png','ERROR'));
});

I found 2 libraries that do this:
https://github.com/oliver-moran/jimp
https://github.com/lovell/sharp
In the end I went with sharp as jimp could not handle 16bit images

Related

Can't find the file I created by fs.writeFile

I am trying to write a file in node.js using fs.writeFile, I use the following code:
const fs = require('filer');
const jsonString = JSON.stringify(myObj)
fs.writeFile('/myFile.txt', jsonString, function (err) {
if (err) throw err;
console.log('Saved!');
});
}
I am sure the file is created, because I can read it by fs.readFile referring to the same address, but I cannot find it on the disk by using windows search. What I understood, if I change the localhost port it saves the files in another location. I already tried "process.cwd()", but it didn't work.
I really appreciate it if someone could help.
try to use : __dirname instead of process.cwd()
const fs = require('fs');
const path = require('path');
const filePath = path.join(__dirname, '/myFile.txt');
console.log(filePath);
const jsonString = JSON.stringify({ name: "kalo" })
fs.writeFile(filePath, jsonString, (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
And I would like to know why are you using 'filer' instead of default fs module?
fs module is native module that provides file handling in node js. so you don't need to install it specifically. This code perfectly worked and it prints absolute location of the file as well.Just run this code if it doesn't work, I think you should re install node js. I have updated the answer.You can also use fs.writeFileSync method as well.
From documentation: "String form paths are interpreted as UTF-8 character sequences identifying the absolute or relative filename. Relative paths will be resolved relative to the current working directory as determined by calling process.cwd()."
So in order to determine your working directory (i.e. where fs create files by default) call (works for me):
console.log(process.cwd());
Then if you would like to change your working directory, you can call (works for me as well):
process.chdir('path_to_new_directory');
Path can be relative or absolute.
This is also from documentation: "The process.chdir() method changes the current working directory of the Node.js process or throws an exception if doing so fails (for instance, if the specified directory does not exist)."

Node.js convert HEIC file

I need a way to use Node.js to convert a photo from HEIC format to either jpg or png. I have searched and cannot seem to find anything that works.
npm -i heic-convert
const convert = require('heic-convert');
async function heicToJpg(file, output) {
console.log(file, output);
const inputBuffer = await promisify(fs.readFile)(file);
const outputBuffer = convert({
buffer: inputBuffer, // the HEIC file buffer
format: 'PNG', // output format
});
return promisify(fs.writeFile)(output, outputBuffer);
}
With heic-convert as Bruno suggested, it works fine.
Here is a node utility that allows you to serially convert HEIC files present in a folder: convert-heic-files
Changing the filename is sufficient for viewing HEIC as jpg:
const fileName = photo.fileName.split(".")[0] + ".jpg";

Nodejs: Convert Doc to PDF

I found some repos, which do not look as they are still maintained:
https://github.com/gfloyd/node-unoconv
https://github.com/skmp/node-msoffice-pdf
...
I tried the approach with libreoffice, but the pdf output is so bad, that it is not useable (text on diff. pages etc.).
If possible I would like to avoid starting any background processes and/or saving the file on the server. Best would be solution where I can use buffers. For privacy reasons, I cannot use any external service.
doc buffer -> pdf buffer
Question:
How to convert docs to pdf in nodejs?
For those who might stumble on this question nowadays:
There is cool tool called Gotenberg — Docker-powered stateless API for converting HTML, Markdown and Office documents to PDF. It supports converting DOCs via unoconv.
And I am happen to be an author of JS/TS client for Gotenberg — gotenberg-js-client
I welcome you to use it :)
UPD:
Gotenberg has new website now — https://gotenberg.dev
While I was creating an application I need to convert the doc or docx file uploaded by a user into a pdf file for further analysis. I used npm package libreoffice-convert for this purpose. libreoffice-convert requires libreoffice to be installed on your Linux machine. Here is a sample code that I have used.
This code is written in javascript for nodejs based application.
const libre = require('libreoffice-convert');
const path = require('path');
const fs = require('fs').promises;
let lib_convert = promisify(libre.convert)
async function convert(name="myresume.docx") {
try {
let arr = name.split('.')
const enterPath = path.join(__dirname, `/public/Resume/${name}`);
const outputPath = path.join(__dirname, `/public/Resume/${arr[0]}.pdf`);
// Read file
let data = await fs.readFile(enterPath)
let done = await lib_convert(data, '.pdf', undefined)
await fs.writeFile(outputPath, done)
return { success: true, fileName: arr[0] };
} catch (err) {
console.log(err)
return { success: false }
}
}
You will get a very good quality of pdf.
To convert a document into PDF we can use Universal Office Converter (unoconv) command line utility.
It can be installed on your OS by any package manager e.g. To install it on ubuntu using apt-get
sudo apt-get install unoconv
As per documentation of unoconv
If you installed unoconv by hand, make sure you have the required LibreOffice or OpenOffice packages installed
Following example demonstrate how to invoke unoconv utility
unoconv -f pdf sample_document.py
It generates PDF document that contains content of sample_document.py
If you want to use a nodeJS program then you can invoke the command through child process
Find code below that demonstrates how to use child process for using the unoconv for creating PDF
const util = require('util');
const exec = util.promisify(require('child_process').exec);
async function createPDFExample() {
const { stdout, stderr } = await exec('unoconv -f pdf sample.js');
console.log('stdout:', stdout);
console.log('stderr:', stderr);
}
createPDFExample();
Posting a slightly modified version for excel, based upon the answer provided by #shubham singh. I tried it and it worked perfectly.
const fs = require('fs').promises;
const path = require('path');
const { promisify } = require('bluebird');
const libre = require('libreoffice-convert');
const libreConvert = promisify(libre.convert);
// get current working directory
let workDir = path.dirname(process.mainModule.filename)
// read excel file
let data = await fs.readFile(
`${workDir}/my_excel.xlsx`
);
// create pdf file from excel
let pdfFile = await libreConvert(data, '.pdf', undefined);
// write new pdf file to directory
await fs.writeFile(
`${workDir}/my_pdf.pdf`,
pdfFile
);
Docx to pdf
A library that converts docx file to pdf.
Installation:
npm install docx-pdf --save
Usage
var docxConverter = require('docx-pdf');
docxConverter('./input.docx','./output.pdf',function(err,result){
if(err){
console.log(err);
}
console.log('result'+result);
});
its basically docxConverter(inputPath,outPath,function(err,result){
if(err){
console.log(err);
}
console.log('result'+result);
});
Output should be output.pdf which will be produced on the output path your provided

How to convert filetype using GraphicsMagick for node.js

How do you "Convert" a file from one type to another using gm? (e.g .png > .jpg)
I found this but it doesn't seem that the node.js version has the same method:
You'll need to change the format of the output file.
var writeStream = fs.createWriteStream("output.jpg");
gm("img.png").setFormat("jpg").write(writeStream, function(error){
console.log("Finished saving", error);
});
http://aheckmann.github.io/gm/docs.html#setformat

trying to access and manipulate images with node.js and GD or imagemagick

i'm trying to create a thumbnail of an jpg that resides on the server. i tried using node-gd and/or node-imagemagick but neither could access the file:
var gd = require('node-gd');
gd.openJpeg("./test.jpeg", function (img, path) {
if (img) {
console.log("file opened ... " + img);
}
else {
console.log("failed to open file ...");
}
});
logs: failed to open file ...
imagemagick:
var im = require('imagemagick');
im.identify('./test.jpeg', function (err, features) {
if (err) throw err;
console.log(features);
});
logs: Error: Command failed: execvp(): No such file or directory
but the test.jpeg file is definitely there.
var fs = require('fs');
fs.open(filePath, 'r', function (err, fd) {
console.log("open file ... " + err + " " + fd);
});
works fine!? no error is logged.
i tried chmod 0777 on the jpeg. nothing.
From what I understand of the documentation of the imagemagick module for node is, that the module provides access to the comandline binaries of imagemagick. Do you have imagemagick (the commandline binaries) installed? Are they in the PATH of you shell?
You are looking for a binary named "identify". You can show the path to it by running "which identify". It should give you a full path - if the prompt just returns, you don't have it installed or it's not in your path.
If you are on win32 the which command won't help, you have to check for a binary called identify.exe.
(never worked with gd - so I am unsure there)
here is the imagemagick example with your code - please note, the path to identify may be different in your environment:
snowflake:Desktop rhaen$ node check_im.js
{ format: 'JPEG', width: 320, height: 250, depth: 8 }
snowflake:Desktop rhaen$ which identify
/usr/local/bin/identify
So - the node module and your code works for me.

Resources