Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Doesn't work with PhantomJS render PDF #348

Open
IAMtheIAM opened this issue Nov 14, 2016 · 7 comments
Open

Doesn't work with PhantomJS render PDF #348

IAMtheIAM opened this issue Nov 14, 2016 · 7 comments

Comments

@IAMtheIAM
Copy link

IAMtheIAM commented Nov 14, 2016

  1. What steps will reproduce the problem?
  2. Load this page to see how it should look: http://monsoonreporting-dev.azurewebsites.net/taxreports/taxsummaryreport?upid=US0401330209103
  3. POST upids=US0401330802165 to http://dev.mymonsoon.com/api/print/pdfs with Content-type:application/x-www-form-urlencoded
  4. Download the returned PDF and compare with the page in step 1
    Webfontloader does not seem to work with PhantomJS 2.1.1

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();
        });
@tiredenzo
Copy link

tiredenzo commented Nov 26, 2016

fonts have to be embed into PDF as far as i know (if PDF is vectorized) this is not a webfontloader issue,
saving to rasterized PNG should work ?

@IAMtheIAM
Copy link
Author

I'm not sure I follow you about the vectorized PDF. The text is selectable and scaled nicely. What is the option to embed the font into the PDF? That would be fine with me, but I didn't see any option from PhantomJS to do that. PNG would not work for the requirements, as it is a text based HTML document I'm converting to PDF.

@IAMtheIAM IAMtheIAM reopened this Dec 6, 2016
@IAMtheIAM
Copy link
Author

Accidentally closed :-)

@ShankyRana
Copy link

was this solved?

@IAMtheIAM
Copy link
Author

phantomjs is obsolete. Use Puppeteer or headless chrome.

@ShankyRana
Copy link

Thanks but having same issue with Puppeteer.

@frizurd
Copy link

frizurd commented Sep 3, 2020

Thanks but having same issue with Puppeteer.

did you manage to solve this issue?
I'm having the same problem with Puppeteer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
4 participants