NodeJS. How to create and save pdfs on the fly [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
i have a form with multiple inputs. The user should insert all inputs and send it. If the form is send a PDF should be created with the inputs informations and the pdf should be saved on the Server (No display is needed).
My Question is now, if somebody knew a good plugin/ module for node.JS which can
1) Create PDF with input informations
2) Save this PDF (on Server) (This can maybe be handled with fs)
Greetings

Here is the sample code whenever you run the node server it saves the pdf file into your directory from where you are running the server.Hope this helps for you.
var express=require('express');
var fs = require('fs');
var pdf = require('html-pdf');
var html = fs.readFileSync('C:/Users/nodejs/tasks/file.html', 'utf8');
var options = { format: 'Letter' };
var app=express();
var file=fs.writeFileSync('C:/Users/nodejs/tasks/businesscar.pdf');
app.get('/file',function(request,response)
{
pdf.create(html, options).toFile('./businesscaw.pdf', function(err, res) {
if (err) return console.log(err);
console.log(res);
var file= 'C:/Users/nodejs/tasks/businesscaw.pdf';
fs.readFile(file,function(err,data){
response.contentType("application/pdf");
response.send(data);
});
});
});
app.listen(3000,function(){
console.log("Server listening on port http://loalhost:3000");
});
See the output in browser :
localhost:3000/file

Related

Access a page's HTML [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Is it possible to take a link and access its HTML code through that link? For example I would like to take a link from Amazon and put it within my own HTML code, use JavaScript to getElementsByClassName to get the price from that link and display it back into my HTML code.
It is possible. You could do a GET request to the Amazon page that will give you the html in the response from there you'll have a string now you'll need to format it, last time I used the node module jsdom to do that.
In more detail:
HTTP is a protocol that we use to request data from the server, I've wrote an explanatory node js script:
const https = require('https');
const JSD = require('jsdom');
const { JSDOM } = JSD;
const zlib = require('zlib');
// The http get request
https.get('https://www.amazon.com', (response) => {
html = '';
// we need this because amazon is tricky and encodes the response so it is smaller hence it is faster to send
let gunzip = zlib.createGunzip();
response.pipe(gunzip);
// we need this to get the full html page since it is too big to send in one amazon divides it to chunks
gunzip.on('data', (chunk) => {
html += chunk.toString();
});
// when the transmittion finished we can do wathever we want with it
gunzip.on('end', () => {
let amazon = new JSDOM(html);
console.log(amazon.window.document.querySelector('html').innerHTML);
});
});

Download a file from a webpage based on the file saved date [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am still very new at web development, I need some suggestions please. I am busy creating a page with a date selector, then I have a folder with one file saved every day. What I am trying to do is: The user needs to select the date of the file he wants and click download and the file saved on that date needs to be downloaded. Can someone please give me an idea how I can get this to work. I have tried some things with JavaScript and php and could not get a working solution.
This code should do the job.
First we scan path provided and list all files, then check creation date and find our target file.
<?php
$Path = './'; // Set path of files here
$TargetDate = '2016-08-11'; // We find the first file with thi date
$TargetFile = null; // Store result here
// Lets Do It
foreach (glob("$Path/*") as $File) {
$Stat = stat($File);
if (date("Y-m-d", $Stat['ctime']) == $TargetDate) {
$TargetFile = $File;
break;
}
}
// Your File!
if (is_null($TargetFile)) {
echo 'No file found';
} else {
echo $TargetFile;
}

Loading contents from another page into a variable as a string [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Is it possible to get the HTML of a div from another page in a variable as a string, so I can run a regex search to find a specific number?
If that other page is in your own domain:
jsBin demo
$('<div />').load("otherpage.html", function(data){
var num = /\d+/.exec( $(this).find("#number").text() );
console.log( num ); // 45
});
Note: the above presumes the desired number is somewhere inside the #number element. The regex /\d+/ is used to get all the numbers from that element.
If the page is not in your domain:
jQuery load external site page
you'll first need to get that page content using PHP with file_get_contents. After the desired content is on your server you'll not run any more into security issues and you can than respond to AJAX with the grabbed content.
If you're loading content from the same domain, the answer #lawrence overflow linked to in his comment will do the trick:Load content from external page into another page using Ajax/jQuery
JS with jQuery:
$(document).ready(function() {
$("#main").load('sourcePage.html #content');
});
Otherwise, you'll need to use server-side technology. Here's a Node.js server that proxies for another site:
JS (Node and Express):
var request=require('request');
var express = require('express');
var app = express();
//Put the source URL here:
var URL='http://www.nytimes.com';
app.get('/', function (req, res) {
res.type('.html');
request(URL,function(err,response,body){
res.send(body);
});
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('listening at http://%s:%s', host, port);
});

The Right Way? Including JS in both NodeJS and HTML [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Currently I have a object that is used for passing message from client to server.
var JSONMessage = function() {
this.sender = "";
this.method = "";
this.arguments = "";
}
I want this object to be available both to the server (NodeJS) as well as the client (HTML). Currently I am doing the following below the above object.
if ( typeof module === 'undefined' ) {
console.log("must be client side!");
}
else {
module.exports = JSONMessage;
}
And in the nodeJS file I do the following
var JSONMessage = require('./public/js/message');
While in the HTML I can simply include the js file.
My question is, is this the best way sharing code between Node and Javascript?
You should check out the umdjs patterns hosted in this Github Repo:
https://github.com/umdjs/umd
What you are doing will work, but you can eliminate the guess work by using one from that repo.

JavaScript or Query library to work with paths/URIs [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
Could someone suggest a library to work with paths like : /a/b/c.jpg or http://asdf/sdf/fd.jpg
I need get directory or just filename string, similar to what the following PHP filesystem functons offers:
dirname
basename
Have a look at the parseURI function of Flagrant Badassery's blog. It can parse any well formed URIs.
Using jQuery or any Javascript you cannot list a directory and the files within it for security reasons.
You can get a filename using regex by using:
var path = "/a/b/c.jpg",
filename = path.replace(/^.*(\\|\/|\:)/, '');
To get the extension and basename of a file you can use (Note: you will need to use this with the above code as well):
var basename = filename.substr(0, filename.lastIndexOf( "." )),
extension = filename.substr(filename.lastIndexOf( "." )+1, filename.length);
If you really need to get a directories list, you can get it with PHP and return it to the client with an AJAX request. This is definitely not recommended because it could very easily be abused to list secure or private files. The only instance I would recommend this is if the directory you are listing will definitely only ever contain files you know are safe to display such as a directory of images that have been uploaded. To do this you would do:
PHP file in directory (index.php)
<?
// Set JSON headings
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
// The directory to list
$this_directory = opendir(".");
// Loop through each file
while($file_name = readdir($this_directory)) {
// Add the files to an array
if($file_name != "." && $file_name != "..") $return_array[] = $file_name;
}
// Return the array as JSON
echo json_encode($return_array);
// Close the directory
closedir($this_directory);
?>
Javascript
// Get the JSON from the PHP file
$.getJSON("img/", function(data){
// Loop through each file
for(var i = 0, j = data.length; i < j; i++) {
// Do whatever you want with the filename
console.log(data[i]);
}
});
Again, only do this on a directory that you know will contain files that are OK to display to the world. NEVER pass in to the PHP file an option to specify which directory to list. For example, don't allow the PHP to take an input such as "/home/site.com/sensitive_data/" because it will allow an attacker to arbitrarily list any directory on your server.

Categories

Resources