Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html to pdf conversion at server side?

we are creating a pdf file from the html file using the package princexml pdf converter. For the Creation of the html file the data has given by the server. In the browser using jquery the input string(html code) is created for the pdf creation. After receiving the input string from the browser, the server creates a html file which is the input to the princexml pdf converter for the pdf creation.

Example for the input string
var sample = "<html>text</html>";//browser side
sample.html converted to sample.pdf //server side 

Is it possible to do the same thing at server side without help of the browser ?

like image 457
user1422892 Avatar asked Dec 09 '22 05:12

user1422892


2 Answers

I know this is a bit old question but since I found a great module I thought of sharing it with everyone.

Module named Puppeteer that can make you run the Chrome in Headless mode and also interact with it via API. So now you can create a template and take the values of the placeholders of that template via POST call and generate the PDF on the fly, in server.

I created a small POC and here is the link to it: Demo-Puppeteer

Let me do a bit explanation here:

    ...........
    const content = await compile(templateName, data);

    /***
     * Launched the headless chrome in memory.
     */
    const browser = await puppeteer.launch();

    /***
     * Created a new page(tab)
     */
    const page = await browser.newPage();

    /***
     * Set the content of the new page
     */
    await page.setContent(content, { waitUntil: 'networkidle0' });
    /***
     * Telling chrome to emulate screen i.e how the page looks if 
     * it would have been rendered in the normal browser.
     */
    await page.emulateMedia('screen');

    const byteArray = await page.pdf({
        format: "A4",
        landscape: true,
        scale: 1.29,
        printBackground: true
    });

    const buffer = Buffer.from(byteArray, 'binary');
    /**
     * We don't need the acknowledgement of this call that is the 
     * reason we are not waiting for this call to return.
     */
    browser.close();

    return buffer;
    .......

Now, this buffer is basically a binary data and you have to write it in a file using the file module of Node.

For further explanation please check out Exlpanation Link

like image 102
Ankur Verma Avatar answered Dec 29 '22 16:12

Ankur Verma


You can use a headless browser like http://phantomjs.org/ . This allows to generate images from rendered pages. See also http://www.lelesys.com/en/media/technology/phantomjs-as-screen-capture-to-generate-image-pdf-files.html

This allows you to use jquery and everything else - since it uses the acutal rendering engine. I guess you do not even need princexml then. There is also a faq page regarding capture: http://phantomjs.org/screen-capture.html

like image 45
Niko Avatar answered Dec 29 '22 15:12

Niko