question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

creating pdf from html+css creates empty files

See original GitHub issue

Steps to reproduce

I want to generate a pdf document from html and css (also images and files in general). For now I am using phantomjs which is compared to puppeteer rather easy and straight forward, but due to maintenance reasons I want to move away from phantomjs. My pdfs are for some reason only blank. What is strange is, that when i remove all the <h#>-tags atleast a part of the html is correctly converted to the pdf. So there might be a bug for headlines? Also, how can multi-page pdfs created, the generated file consists of at most 1 page for me.

Tell us about your environment:

  • Puppeteer version: 5.3.0
  • Platform / OS version: Ubuntu 20.04
  • Node.js version: 10.19.0
var browser = await puppeteer.launch();
        var page = await browser.newPage(); //only 1 page, but i cannot add pages manually all the time obviously
        await page.emulateMediaType('print');
        await page.goto(`data:text/html,${html}`, {waitUntil: 'domcontentloaded'});
        await page.pdf({path: `/tmp/${filename}`, format: 'A4'});
        await browser.close();

What is the expected result?

Multi-page pdf which is generated from my html and css and embeds my local files correctly.

What happens instead?

  • files are not embedded (do not really know how to set them as resources for the generation?)
  • only one empty page is generated (unless I remove all headline-tags from the html
  • css is not applied

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:5

github_iconTop GitHub Comments

1reaction
katunchcommented, Oct 21, 2020

I have the same issue with blank pdfs. I’m not using page.goto since there is the page.setContent() method. But it doesn’t render the pdfs.

Here is my code:

'use strict'

const chromium = require('chrome-aws-lambda');
const fs = require('fs');
const path = require('path');
const Mustache = require('mustache');

let response;

module.exports.render = async (event, context) => {
    const body = JSON.parse(event.body);
    if (!(body.template === null && body.data === null)) {
        const template = body.template;
        const templateData = body.data;

        const renderedTemplateHtml = Mustache.render(template, templateData);
        const fileName = `pdf.pdf`;

        let browser = null;
        try {
            browser = await chromium.puppeteer.launch({
                args: chromium.args,
                defaultViewport: chromium.defaultViewport,
                executablePath: await chromium.executablePath,
                headless: chromium.headless,
                dumpio: false,
                ignoreHTTPSErrors: true,
            });

            const page = await browser.newPage();
            await page.setContent(renderedTemplateHtml, {
                waitUntil: ['networkidle0','load','domcontentloaded'],
                timeout: 30000
            })

            const pdf = await page.pdf({
                format: 'A4',
                printBackground: true,
                margin: {
                    top: '1cm',
                    right: '1cm',
                    bottom: '1cm',
                    left: '1cm'
                }
            });

            response = {
                headers: {
                    'Content-Type': 'application/pdf',
                    // 'content-disposition': `attachment; filename=${fileName}`,
                    'Content-Length': Buffer.byteLength(pdf, 'utf-8')
                },
                statusCode: 200,
                body: pdf.toString('base64'),
                isBase64Encoded: true
            };
        }
        catch (error) {
            response = {
                statusCode: 500,
                body: JSON.stringify({
                    statusCode: 500,
                    message: error.message
                })
            };
        }
        finally {
            if (browser !== null) {
                await browser.close();
            }
        }
    }
    else {
        response = {
            'statusCode': 400,
            'body': JSON.stringify({
                statusCode: 400,
                message: 'Bad Request'
            })
        };
    }

    return response;
};

Puppeteer version: puppeteer-core: ^5.3.1 Platform: macOS / AWS Lambda Node.js version : 12.x

Full repo: https://github.com/softwarebrauerei/pdf-renderer

0reactions
stale[bot]commented, Jul 25, 2022

We are closing this issue. If the issue still persists in the latest version of Puppeteer, please reopen the issue and update the description. We will try our best to accomodate it!

Read more comments on GitHub >

github_iconTop Results From Across the Web

html - PDF::FromHTML creates empty PDF - Stack Overflow
my $pdf = PDF::FromHTML->new( encoding => 'utf-8' ); # Loading from a file: $pdf->load_file('source.html'); # Perform the actual conversion: $ ...
Read more >
Convert HTML to PDF not working - Power Platform Community
Hey guys,. I'm trying to convert an html to pdf, my html is fine but my pdf file is always blank. What am...
Read more >
empty PDF - Google Groups
Hi there, For an unknown reason the PDF I generate from an XHML is just empty. The XHTML is apparently well parsed, the...
Read more >
HTML to PDF Javascript: Export HTML/CSS To PDF Using ...
I will show you guys step by step procedure to export the content of HTML/CSS into Pdf Document (HTML to pdf javascript).
Read more >
How To Create a Download Link - W3Schools
Learn how to create a download link with HTML. ... automatically detect the correct file extension and add it to the file (.img,...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found