Examples Using Wkhtmltopdf Node Js
Creating pdf documents is a fairly common task. It is successfully handled by a whole family of libraries that allow literally "collecting" pdf in parts or filling it out on the basis of a pre-prepared template. This approach is reliable because we can count on the fact that by changing the text of one inscription pagination on some pages will not disappear. On the other hand, adding new pages to pdf takes some time from the developer, and the more different visual elements, the more time it takes.
However, there is another way to create pdf documents: converting from a certain markup language using the appropriate tool. This method will be effective and take less time to make changes to pdf, if the selected tool works quite predictably. There are several similar solutions, but on our project we opted for Wkhtmltopdf , which generates a pdf document from HTML. After a year of using this tool, I can say that the choice was made right, because all needs were covered headlong.
In this article I want to share libraries that simplify the work with wkhtmltopdf in Node.JS.
Currently there are several packages in npm that allow you to integrate wkhtmltopdf. However, they have their drawbacks:
- All options to wkhtmltopdf are passed as an object. Wkhtmltopdf really has a lot of options and you need to constantly ply between the documentation and the code to form the correct object, so I would like to have tips from the IDE when filling out the options.
- Not all wkhtmltopdf functionality is covered by most libraries. For example, not everywhere there is the possibility of generating pdf documents from several HTML sources or there is no way to configure the table of contents
As a result, the libraries wkhtmltopdf-nodejs-options-wrapper , which is a wrapper for wkhtmltopdf parameters, and wkhtmltopdf-nodejs-pdfapi , designed to create pdf documents, were developed.
Consider an example of their use:
var wkhtmlToPdfOptions = require('wkhtmltopdf-nodejs-options-wrapper'), PdfApi = require('wkhtmltopdf-nodejs-pdfapi'); var pdfApi = new PdfApi(), request = new wkhtmlToPdfOptions.CreateRequest(); //Добавим главную страницу гугла var googlePage = new wkhtmlToPdfOptions.Page(); googlePage.setInput('http://google.com'); //Добавим главную страницу хабра var habrPage = new wkhtmlToPdfOptions.Page(); habrPage.setInput('http://habrahabr.ru'); habrPage.getOptions().setZoom(0.5); //уменьшим масштаб до 50% request.addPage(googlePage); request.addPage(habrPage); request.getGlobalOptions().setImageDpi(300); //установим разрешение загружаемых изображений в 300dpi request.getHeadersAndFooterOptions().setFooterCenter('Footer text'); //в футере будет выводится данный текст //метод createPdf запустит команду создания pdf и вернет promise pdfApi.createPdf(request, 'result.pdf') .then(function(data, debug) { console.log('Pdf документ готов'); }, function(data, debug) { console.log('Произошла ошибка: ' + data); });
As you can see from the example, to create a pdf document you need to create a CreateRequest object , fill it with the necessary data and pass it to pdfApi .
The IDE (WebStorm in my case) tells you what methods you can use:
This functionality is already enough for use on the server, but it would be even more useful to be able to start creating pdf from the client. To do this, we need to have a web service that accepts requests and provides ready-made pdf files.
As such a service, you can use the WebSocket server wkhtmltopdf-nodejs-ws-server , which can be easily launched as follows:
var WsServer = require('wkhtmltopdf-nodejs-ws-server'); var server = new WsServer(3000); // <- сервер будет "слушать" запросы по адресу *:3000 server.start();
Client code might look like this:
//необходимо воспользоваться webpack или browserify, чтобы подключить библиотеки с помощью require var wkhtmlToPdf = require('wkhtmltopdf-nodejs-options-wrapper'), io = require('socket.io-client'); var socket = io('http://ip_адрес_сервера:3000'); var page = new wkhtmlToPdf.Page(), request = new wkhtmlToPdf.CreateRequest(); page.setInput('http://google.com'); //снова сгенерируем pdf из главной страницы гугла request.addPage(page); request.getGlobalOptions().setPageSize('Letter'); socket.on('pdf:create:success', function(response) { console.log('Pdf created: http://ip_адрес_сервера:3000/result_' + response.handle + '.pdf'); }); socket.on('pdf:create:fail', function(response) { console.log('Pdf creation failed!'); console.log(response); }); socket.emit('create', request.toObject());
All. This is already enough to create pdf documents.
I hope the npm packages and examples provided in this article are helpful.
Thanks for attention.
PS Documentation: wkhtmltopdf-nodejs-options-wrapper , wkhtmltopdf-nodejs-pdfapi , wkhtmltopdf-nodejs-ws-server
Examples Using Wkhtmltopdf Node Js
Source: https://sudonull.com/post/95298-Wkhtmltopdf-NodeJS
0 Response to "Examples Using Wkhtmltopdf Node Js"
Post a Comment