Generating PDF from a web page with Phantom

Asked

Viewed 84 times

0

I am developing on Node an application where I have an html page, which I fill with database data and then need to save this page in PDF. I’m trying to use Phatom, I’ve tried following several tutorials, but when I pass the page URL it saves the PDF several times, it does not finish the process and always overwrites the generated PDF. What can I do to fix this?

const timeout = ms => new Promise(resolve => setTimeout(resolve, ms));

(async function() {
    const instance = await phantom.create();
    const page = await instance.createPage();

    await page.property('viewportSize', { width: 1920, height: 1024 });

    const status = await page.open('http://localhost/gerar_diploma?id_aluno='+_id);

    console.time('wait');

    await timeout(500);

    console.timeEnd('wait');

    await page.render('docs/result.pdf');

    await instance.exit();
})();
  • Good afternoon, if you follow the documentation and recreate this Example your pdf will be created successfully. The phantom methods are promises, no need to create a counter to return the promises.

1 answer

0

If you have difficulty here this the method, if you wanted to just export the method createPDF and import and pass url by parameter.

const phantom = require('phantom');

async function createPDF(url) {
  const instance = await phantom.create();
  const page = await instance.createPage();

  await page.property('viewportSize', { width: 1600, height: 900 });
  const status = await page.open(url);
  console.log(`Page opened with status [${status}].`);
  await page.render(new Date().getTime()+'-'+'newPDF.pdf');
  await instance.exit();
};


createPDF('/questions/348094/gerando-pdf-de-uma-p%C3%A1gina-da-web-com-o-phantom')
  • Hello, thanks for the reply, the code you showed works for any url I pass, except for an application url, the page I’d like to save is in a url like: http://localhost/gerar_diploma? id_student=5c03314741550317208e0784, when I pass this address the problem persists and it leaves generating successive pdf files..

  • Good evening, the content of this pdf is the page? This page is in a protected url or something? Could give details of the page. I did some url testing similar to yours and succeeded.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.