Phantomjs: PhantomJS will not render Custom Local Fonts nor Web Fonts into PDF

Created on 14 Nov 2016  路  7Comments  路  Source: ariya/phantomjs

  1. Which version of PhantomJS are you using? Tip: run phantomjs --version.
    PhantomJS 2.1.1

  2. What steps will reproduce the problem?

    1. Load this page to see how it should look: http://monsoonreporting-dev.azurewebsites.net/taxreports/taxsummaryreport?upid=US0401330209103
    2. POST upids=US0401330802165 to http://dev.mymonsoon.com/api/print/pdfs with Content-type:application/x-www-form-urlencoded
    3. Download the returned PDF and compare with the page in step 1
  3. Which operating system are you using?
    Windows 10 x64

  4. Did you use binary PhantomJS or did you compile it from source?
    Binary from website

  5. Please provide any additional information below.

I cannot get phantomJS to render any custom fonts. I have tried using WebFontsLoader.

When I load my page in the browser, it loads 2 fonts, Roboto (from google web fonts) and Roboto-Regular (from locally).

http://monsoonreporting-dev.azurewebsites.net/taxreports/taxsummaryreport?upid=US0401330209103

You will see at the top right of the page in red text:

WebFonts Active.
Font Active: Roboto-Regular N4
Font Active: Roboto N4
Font Loading: Roboto N4
Font Loading: Roboto-Regular N4
WebFonts Loading.

However, when I run my node script to fetch the page and generate it into a PDF, it does not hit Font Active. It only shows this:

Font Loading: Roboto N4
Font Loading: Roboto-Regular N4
WebFonts Loading.

And the PDF is rendered with fallback font, not Roboto. CSS is set to use Roboto. The same occurs when CSS is set to use Roboto-Regular.

What is causing this to fail loading when using PhantomJS?

Here is my NodeJS code which generates the PDF

var phantomInstance, page, thisPDFfileName = `taxSummaryReports-${randomInt}.pdf`;

    phantom.create()
        .then(function (phInstance) {
            phantomInstance = phInstance;
            return phantomInstance.createPage()
        })

        .then(function (websitePage) {
            console.log('Getting HTML...');
            page = websitePage;

            // Setting useragent for phantomjs to render webfonts - didn't change anything
            // page.property('settings.userAgent', 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36');

            return page.open(reportURL, postSettings)
        })

        .then(function (status) {
            if (status) console.log(status);

            // Create and stream the PDF to the browser
            console.log('HTML Received. Making PDF...');

            var pageOptions = {
                format: 'Letter',
                // width: '8.27in',
                // height: '11.69in',
                // directory: '/temp',
            };

            // you can't set phantom page properties directly - use page.property() to set them
            page.property('paperSize', pageOptions);

            // Setting timout for phantomjs to render webfonts - didn't work
            // setTimeout(function () {
            return page.render(thisPDFfileName)
            // }, 1600);

        })

        .then(function () {

            try {
                var filePath = thisPDFfileName;
                console.log('Page Rendered');
                console.log('PDF Saved in to disk as: ' + filePath);

                var res = responsePrintServer;

                // set headers
                res.setHeader('Content-Type', 'application/pdf');
                res.setHeader('Content-Disposition', `attachment; filename=${filePath}`);

                // need to set the cookie to trigger jquery.fileDownload.js success callback
                res.cookie('fileDownload', true, {httpOnly: false, path: '/'});

                // need to enable CORS or the cookie won't get set
                res.setHeader('Access-Control-Allow-Origin', '*');

                // Set to true if you need the website to include cookies in the requests sent to the API
                // (e.g. in case you use sessions)
                res.setHeader('Access-Control-Allow-Credentials', true);

                // read the file from disk and create a readstream
                console.log('Reading PDF from disk');
                var fileStream = fs.createReadStream(filePath);
                fileStream.on('end', function () {
                    fs.unlink(filePath, function (err) {
                        if (err) console.log('readstream html-pdf error:', err)
                    })
                });

                // send file readstream to the browser
                console.log('Streaming PDF for UPIDs: ' + UPIDs);
                fileStream.pipe(res);

                // Cleanup - delete the rendered PDF once it's sent to the browser, so it doesn't fill up the disk
                onFinished(res, function (err) {
                    if (err) return console.log(err);
                    // destroy(fileStream);
                    del.sync([thisPDFfileName]);
                    console.log(`PDF ${thisPDFfileName} destroyed.`);
                });
            }
            catch (error) {
                console.log(error);

                // Cleanup - delete the rendered PDF when errors occur, so it doesn't fill up the disk
                del.sync([thisPDFfileName]);
                console.log(`PDF ${thisPDFfileName} destroyed.`);
            }
            // Close this phantomjs instance
            phantomInstance.exit();
            console.log('PhantomJS closed. Script has finished successfully`.');
        })

        .catch(error => {
            console.log(error);
            phantomInstance.exit();
        });
stale

Most helpful comment

Has this issue been fixed in the latest build? Almost a year now. Thanks

All 7 comments

That link you provided returns 404 page not found. Can you check?

Got it, the text is correct but the hyperlink is incorrect. It is https://github.com/ariya/phantomjs/issues/13541

Hmm that issue simple says "fixed in master" yet it is not fixed in 2.1.1. Not sure what you are suggesting by providing that link, please explain with words.

It means it's a known issue and you have to build yourself or wait for the next release.

Has this issue been fixed in the latest build? Almost a year now. Thanks

Due to our very limited maintenance capacity, we need to prioritize our development focus on other tasks. Therefore, this issue will be automatically closed (see #15395 for more details). In the future, if we see the need to attend to this issue again, then it will be reopened. Thank you for your contribution!

Was this page helpful?
0 / 5 - 0 ratings