Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 568 Vote(s) - 3.52 Average
  • 1
  • 2
  • 3
  • 4
  • 5
HTML to PDF with Node.js

#11
You can also use pdf node creator package

Package URL -

[To see links please register here]


Reply

#12
In my view, the best way to do this is via an API so that you do not add a large and complex dependency into your app that runs unmanaged code, that needs to be frequently updated.

Here is a simple way to do this, which is free for 800 requests/month:

var CloudmersiveConvertApiClient = require('cloudmersive-convert-api-client');
var defaultClient = CloudmersiveConvertApiClient.ApiClient.instance;

// Configure API key authorization: Apikey
var Apikey = defaultClient.authentications['Apikey'];
Apikey.apiKey = 'YOUR API KEY';



var apiInstance = new CloudmersiveConvertApiClient.ConvertWebApi();

var input = new CloudmersiveConvertApiClient.HtmlToPdfRequest(); // HtmlToPdfRequest | HTML to PDF request parameters
input.Html = "<b>Hello, world!</b>";


var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
apiInstance.convertWebHtmlToPdf(input, callback);

With the above approach you can also install the API on-premises or on your own infrastructure if you prefer.
Reply

#13
In addition to @Jozzhart Answer, you can make a local html; serve it with express; and use phantom to make PDF from it; something like this:

const exp = require('express');
const app = exp();
const pth = require("path");
const phantom = require('phantom');
const ip = require("ip");

const PORT = 3000;
const PDF_SOURCE = "index"; //index.html
const PDF_OUTPUT = "out"; //out.pdf

const source = pth.join(__dirname, "", `${PDF_SOURCE}.html`);
const output = pth.join(__dirname, "", `${PDF_OUTPUT}.pdf`);

app.use("/" + PDF_SOURCE, exp.static(source));
app.use("/" + PDF_OUTPUT, exp.static(output));

app.listen(PORT);

let makePDF = async (fn) => {
let local = `http://${ip.address()}:${PORT}/${PDF_SOURCE}`;
phantom.create().then((ph) => {
ph.createPage().then((page) => {
page.open(local).then(() =>
page.render(output).then(() => { ph.exit(); fn() })
);
});
});
}

makePDF(() => {
console.log("PDF Created From Local File");
console.log("PDF is downloadable from link:");
console.log(`http://${ip.address()}:${PORT}/${PDF_OUTPUT}`);
});

and index.html can be anything:

<h1>PDF HEAD</h1>
<a href="#">LINK</a>

result:

[![enter image description here][1]][1]


[1]:
Reply

#14
const fs = require('fs')
const path = require('path')
const utils = require('util')
const puppeteer = require('puppeteer')
const hb = require('handlebars')
const readFile = utils.promisify(fs.readFile)

async function getTemplateHtml() {

console.log("Loading template file in memory")
try {
const invoicePath = path.resolve("./invoice.html");
return await readFile(invoicePath, 'utf8');
} catch (err) {
return Promise.reject("Could not load html template");
}
}


async function generatePdf() {

let data = {};

getTemplateHtml()
.then(async (res) => {
// Now we have the html code of our template in res object
// you can check by logging it on console
// console.log(res)

console.log("Compiing the template with handlebars")
const template = hb.compile(res, { strict: true });
// we have compile our code with handlebars
const result = template(data);
// We can use this to add dyamic data to our handlebas template at run time from database or API as per need. you can read the official doc to learn more

[To see links please register here]

const html = result;

// we are using headless mode
const browser = await puppeteer.launch();
const page = await browser.newPage()

// We set the page content as the generated html by handlebars
await page.setContent(html)

// we Use pdf function to generate the pdf in the same folder as this file.
await page.pdf({ path: 'invoice.pdf', format: 'A4' })

await browser.close();
console.log("PDF Generated")

})
.catch(err => {
console.error(err)
});
}

generatePdf();
Reply

#15

[To see links please register here]


I use dynamic-html-pdf, this is simple and also able to pass dynamic variable to html.

```
var html = fs.readFileSync('./uploads/your-html-tpl.html', 'utf8');
var options = {
format: "A4",
orientation: "portrait"
// border: "10mm"
};
var document = {
type: 'file', // 'file' or 'buffer'
template: html,
context: {
'your_key':'your_values'
},
path: '/pdf/1.pdf' // pdf save path
};

pdf.create(document, options)
.then(res => {
console.log(res)
}).catch(error => {
console.error(error)
});
```

On html you can use {{your_key}}
Reply

#16
I've written [hpdf][1] lib for generating PDF from HTLM or URL.
It supports configurable pool of headless browsers (as resources) in the background.

```typescript
import fs from 'fs';
import { PdfGenerator } from './src';

const start = async () => {
const generator = new PdfGenerator({
min: 3,
max: 10,
});

const helloWorld = await generator.generatePDF('<html lang="html">Hello World!</html>');
const github = await generator.generatePDF(new URL('https://github.com/frimuchkov/hpdf'));

await fs.promises.writeFile('./helloWorld.pdf', helloWorld);
await fs.promises.writeFile('./github.pdf', github);

await generator.stop();
}
```


[1]:

[To see links please register here]

Reply

#17
The best solution I found is html-pdf. It's simple and work with big html.

[To see links please register here]


Its as simple as that:

pdf.create(htm, options).toFile('./pdfname.pdf', function(err, res) {
if (err) {
console.log(err);
}
});

NOTE:
-----
**This package has been deprecated**

>**Author message: Please migrate your projects to a newer library like puppeteer**
Reply

#18
I wanted to add to this since I did not see the option to created pdfs from liquid templates yet, but the solution also works with normal html or urls as well.

Lets say this is our html template. Which could be anything really but see that the code include double curly braces. The key inside the braces will be looked up in the *liquid_data* parameter of the request and replaced by the value.

<html>
<body>
<h1>{{heading}}</h1>
<img src="{{img_url}}"/>
</body>
</html>

The corresponding *liquid_data* object looks like this:

{
"heading":"Hi Stackoverflow!",
"img_url":"https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.svg"
}

This is the example I want to create a PDF for. Using [pdfEndpoint][1] and the [Playground][2] creating a pdf from that template from above is very simple.

const axios = require("axios");

const options = {
method: "POST",
url: "https://api.pdfendpoint.com/v1/convert",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer SIGN-UP-FOR-KEY"
},
data: {
"delivery_mode": "json",
"page_size": "A4",
"margin_top": "1cm",
"margin_bottom": "1cm",
"margin_left": "1cm",
"margin_right": "1cm",
"orientation": "vertical",
"html": "<html><body> <h1>{{heading}}</h1> <img src=\"{{img_url}}\"/> </body>\</html>",
"parse_liquid": true,
"liquid_data": "{ \"heading\":\"Hi Stackoverflow!\", \"img_url\":\"https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.svg\"}"
}
};

axios.request(options).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.error(error);
});

The service will the return a rendered pdf like this:
[![Html to pdf rendered with pdfendpoint.com][3]][3]


[1]:

[To see links please register here]

[2]:

[To see links please register here]

[3]:
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through