Passing very long url to Puppeteer - is there a better way?

徘徊边缘 提交于 2020-06-29 04:31:23

问题


So a git issue had me roll back about two weeks of work -

Im currently trying to pass an array of about 3300 string to a handlebars template then trying to print that as a pdf - my issue is I'm pretty sure my pupepteer URL is being cut off at 3000 characters. Im at a loss for a workaround.

 <<<< my data logs as -----> Array(3330) [Object, Object, Object, Object, Object, Object, Object, Object, …] >>>

 var templateHtml = fs.readFileSync(path.join(process.cwd(), 'template.html'), 'utf8');
    var template = handlebars.compile(templateHtml);
    var html = template(data);

await page.goto(`data:text/html;charset=UTF-8,${html}`, {
        waitFor:10000
    });

before my git meltdown I was printing out 90 page PDF's and I just cant figure out what I did before.


回答1:


Answer

Your problem seems to be the Data URI length limitation. It is 2MB in case of Chromium. So if your html exceeds the limit it will be trimmed or even not rendered at all.

I suggest to use page.setContent with the same content as it has no upper limit.

Example

Note: setContent needs a string as input, I've just copied the source of example.com.

const puppeteer = require('puppeteer')

async function fn() {
  const browser = await puppeteer.launch({ headless: true })

  const page = await browser.newPage()
  await page.goto('data:text/html,<h1>Template</h1>')
  await page.waitFor(2000)
  await page.setContent(
    '<!doctype html> <html> <head> <title>Example Domain</title> <meta charset="utf-8" /> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style type="text/css"> body { background-color: #f0f0f2; margin: 0; padding: 0; font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; } div { width: 600px; margin: 5em auto; padding: 2em; background-color: #fdfdff; border-radius: 0.5em; box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02); } a:link, a:visited { color: #38488f; text-decoration: none; } @media (max-width: 700px) { div { margin: 0 auto; width: auto; } } </style> </head> <body> <div> <h1>Example Domain</h1> <p>This domain is for use in illustrative examples in documents. You may use this domain in literature without prior coordination or asking for permission.</p> <p><a href="https://www.iana.org/domains/example">More information...</a></p> </div> </body> </html>'
  )

  await page.pdf({ path: 'page.pdf' })

  await browser.close()
}
fn()


来源:https://stackoverflow.com/questions/62492393/passing-very-long-url-to-puppeteer-is-there-a-better-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!