Giter Club home page Giter Club logo

jsreport-chrome-pdf's Introduction

jsreport

Join the chat at https://gitter.im/jsreport/jsreport NPM Version NPM Downloads Docker Pulls build status

An open-source platform for designing and rendering various reports.

jsreport is a reporting server letting developers define reports using javascript templating engines like handlebars. It supports various report output formats like html, pdf, excel, docx, and others. It also includes advanced reporting features like user management, REST API, scheduling, designer, or sending emails.

You can find more information on the official project website https://jsreport.net

studio

Installation

Basic installation from the npm

npm install -g @jsreport/jsreport-cli
jsreport init
jsreport configure
jsreport start

You can also download compiled binary or pull from the official docker images. See https://jsreport.net/on-prem for the details.

Documentation

See the https://jsreport.net/learn for an overview of concepts, guides, clients, and general documentation.

Extensions

The jsreport official distribution in npm, docker, or compiled binary includes the most commonly used extensions. However, the list of available extensions is much longer, and you may want to install some of the missing ones as well. See the list of available packages here or in the documentation.

You are also not limited to extensions we provide to you. You can implement your extensions. See the Implementing custom extension article.

Node.js

You can find documentation for adapting this jsreport distribution using nodejs and also information for integrating it into an existing nodejs application in the article adapting jsreport.

The official jsreport distribution wires the most popular extensions into the ready-to-use package. However, if you are skilled, you are free to start from the ground using jsreport-core.

Development

We use yarn to manage the monorepo. The basic workflow is the following

git clone https://github.com/jsreport/jsreport
yarn install
yarn start

The tests for the individual package runs the following way

yarn workspace @jsreport/jsreport-scripts test

The studio extensions development with the hot reload can be started using

set NODE_ENV=jsreport-development&&yarn start

Roadmap

  • adding more features to docx/pptx/xlsx recipes
  • pdf compression
  • version control extension direct git integration and improvements
  • studio editor intellisense
  • html-to-xlsx - images, filters...

More in the backlog.

Missing a feature? Submit a feature request.

Vulnerabilities

We update vulnerable jsreport dependencies based on npm and Snyk audits during every release. Please wait until we release the next version when you notice a security warning in your audit. There is no need to create a ticket for it. In case you see a direct impact on jsreport security that you can replicate, please send us an email to [email protected] and we will make sure it's fixed ASAP. Note there is no need to panic when there is a vulnerability mentioned in the audit because it is the most likely in the code path that is not used. A typical example of a vulnerability is an eventual DDoS attack through a dependency parsing some internal config, which in fact can't happen and isn't a vulnerability at all.

Licensing

Copyright (C) 2024 Jan Blaha

Do you want to use jsreport for a personal purpose, in a school project or a non-profit organization? Then you don't need the author's permission, just go on and use it. You can use jsreport without the author's permission also when having a maximum 5 templates stored in jsreport storage.

For commercial projects using more than 5 stored report templates see Pricing page.

Under any of the licenses, free or not, you are allowed to download the source code and make your own edits.

In every case, there are no warranties of any kind provided:

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

jsreport-chrome-pdf's People

Contributors

abenhamdine avatar bjrmatos avatar charlieknoll avatar pofider avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

jsreport-chrome-pdf's Issues

Landscape mode - width, height do not work

Hi everyone.

I have html page with fixed size width: 842px, height: 595px. I am trying to build a pdf report for that page, however the page is just part of the final report (see picture below)
image

Blue background is my page I expect being full sized.

Here is an example I have created (width and height do not work and do nothing when I change them):

https://playground.jsreport.net/w/NameGrey/BspPcQG7

Additionally I tried to use "scale". And set it to "1.5" or "1.33333333" or any similar value, but in that case I could see an additional 1px white line in the bottom and right borders.

image

Please assist me with that problem.

Allow setting media type

Using bootstrap to print pdf is usually pain because it applies some custom styles for print media. This usually unwanted.

Puppeteer supports changing media type when printing pdf.

page.emulateMedia('screen')

The default print makes sense. However we could introduce new option chrome.mediaType and let user change to normal screen.

Reuse puppeteer page object

The chrome-pool strategy reuses puppeteer browser object.
That is great but we could go even further and reuse page object to get even better performance.

Issue with landscape-mode

Hello,
I'm not sure if this is jsreport-chrome-pdf related but I'm having issues with the landscape mode. Everything else if working finde, however the landscape option doesn't seem to do anything.

my script:

module.exports = function (callback, html, header, footer, settings, js) {
	var jsreport = require('jsreport-core')();	
	jsreport.use(require('jsreport-jsrender')())
	jsreport.use(require('jsreport-chrome-pdf')())

	//210 mm ร— 297 mm 
	jsreport.init().then(() => {
	return jsreport.render({
		template: {
			content: html,
			engine: 'jsrender',
			helpers: js,
			recipe: 'chrome-pdf',
			chrome: {
			  landscape: true,
			  displayHeaderFooter: true,
			  format: 'A4',
			  headerTemplate: header,
			  footerTemplate: footer,
			  marginTop: '130px',
			  marginBottom: '110px',
			  marginLeft: '105px',
			  marginRight: '105px'
			 }			
		},
		data: null
	}).then((resp) => {
		callback(null, resp.content.toJSON().data);
 	});
	}).catch((e) => {
		callback(e, null);
	});
}

I also tried the scale option once with scale: 1 (basically the default) but that resulted in a

Protocol error (Page.printToPDF): Target closed.
Error: Protocol error (Page.printToPDF): Target closed.

really hope you guys might have an idea.

Edit: thought I should mention I'm on these versions:
"jsreport-chrome-pdf": "1.0.2",
"jsreport-core": "2.0.1",
"jsreport-jsrender": "2.0.0",

emulateMedia option no longer supported in puppeteer

It appears that the latest version of puppeteer 5.3.1 does not support the emulateMedia option.
It looks as though they have renamed the method to emulateMediaType

This block of code will cause the pdf creation to fail if chrome.mediaType is set to screen or print

    if (optionsToUse.mediaType) {
      if (optionsToUse.mediaType !== 'screen' && optionsToUse.mediaType !== 'print') {
        throw reporter.createError(`chrome.mediaType must be equal to 'screen' or 'print'`, { weak: true })
      }

      await page.emulateMedia(optionsToUse.mediaType)
    }

Break page and repeat background

Hi guys! Awesome work with jsreport.

I'm facing an issue here.
I have a document that are divided like this:

  • SOME INFO LIKE CUSTOM HEADER (not standard chrome pdf header)
  • SOME INFO LIKE BODY
  • SOME INFO LIKE CUSTOM FOOTER (not standard chrome pdf footer)

This document have a background on the entire page. This background have some limitations. So, when some values are about to break the limit of the page, I need to go to a new page, with the same background than the previous page.
But, more than this, on the next page I need to repeat CUSTOM HEADER and CUSTOM FOOTER.

What I did so far:

  • Using beforeRender to try implement some template validation
function beforeRender(req, res, done) {
    let layout = '{#asset bl_cover.html @encoding=string}'
    req.template.content = layout.replace('$$$bl_data$$$', req.template.content)
    done();
}
  • Using some html template and only making an injection of a div (ugly as f*ck, actually)
<body>
    <div class="cover">$$$bl_data$$$</div>
    <div class="no-show {{showOtherPages model.PROCESS.SHOW_SECOND_PAGE}}">
        <div class="break"></div>
    </div>
    <div class="cover no-show {{showOtherPages model.PROCESS.SHOW_SECOND_PAGE}}">$$$bl_data$$$</div>
</body>

After all this (just a little context) what I need is create new pages automatically. If data will break my document, I break the page and than set data continuation on new page. And so on.

If you guys need more info, pls tell me. Help me, pls.

Embedded CSS in HTML headers and footer is ignored

I am trying to switch from PhantomPDF to Chrome in .NET and having some issues. I used to pass HTML / embedded CSS to headers and footers to Phantom and it worked perfectly. In Chrome embedded CSS is ignored. The documentation is not clear about what is exactly supported as header/footer content.

Here is my HTML header (this is Razor syntax, but you will understand what I want to achieve here):

<html>
<head>
    @Html.EmbedCss("css/documents/page-headers/report-page-header.css", hostingEnvironment)
</head>
<body>
    <div class="page-header">
        <img class="logo" src="data:image/png;base64, @Html.EmbedBase64("img/company-logo.png", hostingEnvironment)" />
        <table class="details">
            <tr>
                <td>@Localizer["GeneratedOn"]:&nbsp;</td>
                <td>@Model.GeneratedOn.ToString("G")</td>
            </tr>
            <tr>
                <td>@Localizer["GeneratedBy"]:&nbsp;</td>
                <td>@Model.GeneratedBy?.ToDisplayString() (@Model.GeneratedBy?.Username)</td>
            </tr>
        </table>
        <div class="title">
            @Model.Name
        </div>
    </div>
</body>
</html>

Here the PhantomPDF rendering result:

commandes_dachat_avec_items_2018_07_18_10_10_08.pdf

Here the Chrome rendering result with the same code:

commandes_dachat_avec_items_2018_07_18_09_43_03.pdf

Version 1.7.0 breaks ability to generate report in container

Similar to jsreport/jsreport-html-to-xlsx#27, starting from 1.7.0 it is no longer possible to use the plugin in a container.
Error message:

TypeError: reporter.getAvailableRenderTimeout is not a function
    at execute (/app/node_modules/jsreport-chrome-pdf/lib/dedicatedProcessStrategy.js:8:32)
    at /app/node_modules/jsreport-chrome-pdf/lib/chrome.js:69:26
    at async executeRecipe (/app/lib/processor.js:136:5)
`
`` 

can not render when html contains url encoded characters

original problem described here: https://forum.jsreport.net/topic/432/azure-sas-url-images-render-in-html-phantom-pdf-but-not-chrome-pdf/3

live preview of the problem: https://playground.jsreport.net/studio/workspace/ryMZv1UdM/5

this is a simplified version of the code that we use inside the recipe to render html (modified to test the case of this bug):

(async () => {
  const USE_INLINE_URI = true
  const waitUntil = undefined
  const HEADLESS = true

  const util = require('util')
  const url = require('url')
  const fs = require('fs')
  const path = require('path')
  const puppeteer = require('puppeteer')
  const browser = await puppeteer.launch({ headless: HEADLESS })
  const page = await browser.newPage()

  const html = `
    <img
      src="https://pcslive.blob.core.windows.net/maps/Narhwal1.jpg?st=2018-03-01T03%3A21%3A00Z&se=2019-03-17T03%3A21%3A00Z&sp=rl&sv=2017-04-17&sr=b&sig=DylFLy7o5x3wNBbVamJaNx4oK5m1gsLK7crrHrC6j9k%3D"
    />
    <br />
    <img
      src="https://pcslive.blob.core.windows.net/maps/Narhwal2.jpg?st=2018-02-28T19%3A21%3A00Z&se=2019-03-16T20%3A21%3A00Z&sp=rl&sv=2017-04-17&sr=b&sig=ObohekgytO%2FzDi3xzWYukJg1imM9U%2FWFd1oUqQ5hM%2BA%3D"
    />
  `

  let htmlUrl = ''

  if (!USE_INLINE_URI) {
    const writeFileAsync = util.promisify(fs.writeFile)
    const localHtmlFilePath = path.join(__dirname, 'tmp.html')

    await writeFileAsync(localHtmlFilePath, html)

    htmlUrl = url.format({
      protocol: 'file',
      pathname: localHtmlFilePath
    })
  }

  await page.goto(
    USE_INLINE_URI ? `data:text/html,${html}` : htmlUrl,
    waitUntil != null ? { waitUntil } : {}
  )

  await page.pdf({
    path: path.join(__dirname, 'image.pdf')
  })

  // await page.screenshot({
  //   path: path.join(__dirname, 'image.png')
  // })

  if (HEADLESS) {
    await browser.close()
  }
})()

when running this code you will see that pdf shows one broken image (Narhwal1.jpg loads fine, Narhwal2.jpg broken), but if you change the USE_INLINE_URI to false you will see that the pdf now contains correct images. the problem is that our implementation right now loads the html from an inline uri data:text/html,...., if some part of the html contains a url encoded string then chrome fails to load the resource that contains the encoded string.

not sure why chrome is able to load just one image and not the other but the issue dissapears if we change the loading of the html from inline data uri to a local file uri. also the problem with inline data uri is more visible if you change the HEADLESS var to false in above test code, the chrome process becomes visible and the url loaded (inline data uri) and dom nodes inspector show different url sources for the images.

compatibility with puppeteer 2.0

I saw that in package.json puppeteer is listed as peerDependency with range 1.x.x

but puppeteer 2.0 has been released in october (https://github.com/puppeteer/puppeteer/releases) and the only breaking change seems to be end of support for node 6.x
Thus do you think/know if this module could work reliably with puppeteer 2.x ? Do you plan to support it and change peerDependency range ?

thx by advance

Attempting to run on heroku

No problem running this recipe locally, but I'm trying to run this recipe on heroku and receiving this issue.

screen shot 2018-07-10 at 2 59 23 pm

Any ideas?

Parameter value type "scale" for recipe chrome-pdf not compatible?

I started running into this issue, whenever I pass the parameter option scale to 1, 1.0 or "1.0" to the recipe 'chrome-pdf' through jsreport.

Here the list of options how it's being received by jsreport:

{ scale: '1.0',
  format: 'Letter',
  displayHeaderFooter: true,
  headerTemplate: '<div></div>',
  footerTemplate: '<div class="page-information"\n\t\t\tstyle="font-family: Helvetica, Arial, sans-serif;font-size:7pt!important;\n\t \t\tcolor:grey!important;padding:0;margin-left:.15in;">\n\t\t\tPage&nbsp;<span class="pageNumber"></span>&nbsp;of&nbsp;<span class="totalPages"></span>\n\t\t</div>',
  marginTop: '.25in',
  marginBottom: '.5in',
  marginLeft: '.25in',
  marginRight: '.25in' }

This is the error output I get in the jsreport console:

2018-06-25T16:30:58.779Z - error: Error when processing render request Protocol error (Page.printToPDF): Invalid parameters scale: double value expected Error: Protocol error (Page.printToPDF): Invalid parameters scale: double value expected at Promise (jsreports/node_modules/puppeteer/lib/Connection.js:200:56) at new Promise (<anonymous>) at CDPSession.send jsreports/node_modules/puppeteer/lib/Connection.js:199:12) at Page.pdf (jsreports/node_modules/puppeteer/lib/Page.js:798:39) at runWithTimeout (jsreports/node_modules/jsreport-chrome-pdf/lib/chrome.js:169:36) at <anonymous> at process._tickCallback (internal/process/next_tick.js:188:7)

Looking at the source code inside chrome.js on this commit - b92b9ec#diff-a7c88e4bf351928799b9036ef131dc57R73

The scale value type is causing problems in my case.

Replacing the EMD.String type with EDM.Int32 (which was the original type set previous to that commit), fixes the issue.
Seems like the function Page.printToPdf doesn't like the value type on the scale param to be passed as String for some reason. I haven't dug too deep into the code, but this is symptom I'm getting.

Operative System: Mac OS Sierra 10.12.6
NodeJs: 8.9.1

Thanks!

ENOENT: no such file or directory: \Temp\jsreport\autocleanup\

Hello,

After rendering some templates, this error starts to happen, then I'm unable to render reports until I restart the jsreport service.

Error: ENOENT: no such file or directory, open 'C:\Users\GUSTAV~1.MAS\AppData\Local\Temp\jsreport\autocleanup\8054d58c-0f12-4e9d-b40d-7ef56df600f1-chrome-pdf.html'

Re-use Chrome instances for performance

I noticed that as part of the recipe, Chrome is launched and then closed each time a PDF is generated.

Would it not be better to try and keep Chrome alive once it has first been launched. Or, if you wanted to be really fancy, have a swarm of Chromes to connect to?

Add chromium launch options

Hello,

I'm having a lot of issues regarding chromium on CentOS 7:
puppeteer/puppeteer#391

I'm facing this error:
pupeteer Running as root without --no-sandbox is not supported

So I'm installing pupeteer manually like this:

cd /home/chromium
git clone https://github.com/scheib/chromium-latest-linux .
./update.sh

cd /home/chromium/latest
chown yourID:yourID *
# Need root permission
chown root:root chrome_sandbox && chmod 4755 chrome_sandbox
export CHROME_DEVEL_SANDBOX="/home/chromium/latest/chrome_sandbox"

export PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true
npm install puppeteer

Now I need the launch options to pass the executablePath:
https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md

Something passed directly to jsreport-chrome-pdf:

jsreport.use(require('jsreport-chrome-pdf')(
{
 executablePath: './home/chromium-linux/latest',
 args: ['lala', 'lele']
}
));

The arg '--no -sandbox' should resolve the issue.
Please let me know if exists any other ways of resolving this issue.

Thanks!

PDF File size increases dramatically when HTML contains bold text

Hello,
I am generating a PDF from an html template that i build. As part of the template i mark a few words as bold in the middle of a sentence. However, when i do this the output PDF is massively larger. Here's some examples:

  1. First file: surrounded 8 words with <b> or <span style="text-weight: bold;">. Resulting file size went up from 27k to 72k
  2. Second file: surrounded 12 words with same tags. Result file size went up to 125k from 31k
  3. I have replaced the tags with <u> tag and the file did not increase (27k/31k)

This happens on my ASP.Net Core service. I use jsreport.AspNetCore (2.0.1) with jsreport.Binary (2.4.0), jsreport.Local (2.0.1) and jsreport.Client (3.0.1).
Any idea what can cause this scenario?

issue with PDF

I'm trying to generate a PDF and upload to a third party, but I get an error when I download from the download button, that is like if I download from API.
screenshot_2018-12-28_at_10_08_47

If I generate the file in jsreport previewer and I download it "printing", I works fine.
screenshot_2018-12-28_at_10_11_36

Checking the differences, the first one (which fails) it is generated in 1.3 pdf version, and the one that works fine has 1.7 version

screenshot 2018-12-28 at 10 20 49

Could the version it generates be updated?

Access template data in scripts

Hi there.
Can somebody advice me, how to access data of template in script tags? I would like to build charts, based on data, but can't get it inside
Something like:

<script>
const ctx = document.getElementById("myChart").getContext('2d');
const myChart = new Chart(ctx, {
 type: 'bar',
 data: transformed template.data 
}
</script>

Thank you in advance

Chrome Driver Scale Parameter only accepts Integers

Was curious if there was a reason in lib/chrome.js that the scale is being parsed as an Int:

function numberOrUndefined (param) {
  try {
    return parseInt(param)
  } catch (e) {
    return undefined
  }
}

When setting the scale to 0.8, it rounds to a 1.
Could this use parseFloat() instead so the scale can be a float?

Thanks!

puppeteer/chrome version

Was curious if there is a reason that the chrome-pdf plugin is current using puppeteer 0.13.0

The version of chrome/chromium that it's installing is crashing on a highchart that I'm rendering, which is rendering fine in current chrome. As a test I upgraded the local puppeteer to ^1.0.0 and the latest version of chrome/chromium it installs does not crash in this scenario.

I can provide details on the actual crash if necessary, just wondering if it's possible at this point to upgrade the internal dependency of puppeteer to the 1.x release.

Thanks

Images not rendering in header/footer

Hey guys,

Trying to render some reports with header and footer containing images, but I can't seem to get it working.
The images show up as "broken"... e.g.
broken_image

Same images are working perfectly in main template.
Any idea's what I could be doing wrong?

Sidenote 1: I'm using js-report core directly in a node app. Images are referenced using absolute http urls (not using "assets"...)
Sidenote 2: when switching to phantom-pdf recipe, all images are showing correctly in header and footer.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.