Giter Site home page Giter Site logo

react-to-pdf's Introduction

React to PDF

Easily create PDF documents from React components.

Install

# Yarn
yarn add react-to-pdf

# NPM
npm install --save react-to-pdf

Important Notes

  • Not vectorized - the pdf is created from a screenshot of the component and therefore is not vectorized. If you are looking for something more advanced to generate pdf using React components, please check out other popular alternatives packages listed below.
  • No SSR

Alternatives and Similars Packages

  • @react-pdf/renderer - React renderer to create PDF files on the browser and server
  • react-pdf - Display PDFs in your React app as easily as if they were images.

Examples

Usage

Using usePDF hook

import { usePDF } from 'react-to-pdf';

const Component = () => {
   const { toPDF, targetRef } = usePDF({filename: 'page.pdf'});
   return (
      <div>
         <button onClick={() => toPDF()}>Download PDF</button>
         <div ref={targetRef}>
            Content to be generated to PDF
         </div>
      </div>
   )
}

Code Sandbox demo

Using default function

import { useRef } from 'react';
import generatePDF from 'react-to-pdf';

const Component = () => {
   const targetRef = useRef();
   return (
      <div>
         <button onClick={() => generatePDF(targetRef, {filename: 'page.pdf'})}>Download PDF</button>
         <div ref={targetRef}>
            Content to be included in the PDF
         </div>
      </div>
   )
}

Code Sandbox demo

Advanced options

import generatePDF, { Resolution, Margin } from 'react-to-pdf';

const options = {
   // default is `save`
   method: 'open',
   // default is Resolution.MEDIUM = 3, which should be enough, higher values
   // increases the image quality but also the size of the PDF, so be careful
   // using values higher than 10 when having multiple pages generated, it
   // might cause the page to crash or hang.
   resolution: Resolution.HIGH,
   page: {
      // margin is in MM, default is Margin.NONE = 0
      margin: Margin.SMALL,
      // default is 'A4'
      format: 'letter',
      // default is 'portrait'
      orientation: 'landscape',
   },
   canvas: {
      // default is 'image/jpeg' for better size performance
      mimeType: 'image/png',
      qualityRatio: 1
   },
   // Customize any value passed to the jsPDF instance and html2canvas
   // function. You probably will not need this and things can break, 
   // so use with caution.
   overrides: {
      // see https://artskydj.github.io/jsPDF/docs/jsPDF.html for more options
      pdf: {
         compress: true
      },
      // see https://html2canvas.hertzen.com/configuration for more options
      canvas: {
         useCORS: true
      }
   },
};

// you can use a function to return the target element besides using React refs
const getTargetElement = () => document.getElementById('content-id');

const Component = () => {
   return (
      <div>
         <button onClick={() => generatePDF(getTargetElement, options)}>Generate PDF</button>
         <div id="content-id">
            Content to be generated to PDF
         </div>
      </div>
   );
}

Code Sandbox demo

react-to-pdf's People

Contributors

cbarraford avatar dependabot[bot] avatar ivmarcos avatar mark-prins avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

react-to-pdf's Issues

html2canvas error

Hello
Actually i want to show pdf after click without show html view.
it is posible

pdf quality issue

actually, this was not an issue. I like this library a lot. but in here I mention that downloaded pdf files characters are with some kind of blur or less quality issu. can you fix it up

Scaling error on generate file .

Some times the PDF is generated with an escalation, which sometimes leaves the PDF, this changes depending on the size and redemption of the screen.

Images of the code in sandbox that have in the documentation:

Captura de Pantalla 2020-03-04 a la(s) 23 31 29

Captura de Pantalla 2020-03-04 a la(s) 23 32 21

Cdn?

Looked into unpkg and jscdn but can't find the library anywhere

Cannot make pdf full width

Hey! really liking this package :) Found a bit of an issue though and I'm not sure how to combat it.

So I've been trying to get my react component page to react full height and width of the PDF. This is an example of my code

<div className="options">
          <Pdf targetRef={ref} filename="invoice.pdf" options={{
            orientation: 'p',
            unit: 'px',
            format: [595, 842],
          }}>
            {({ toPdf }) => <button onClick={toPdf}>Generate Pdf</button>}
          </Pdf>
        </div>
        <div className="innerDoc" ref={ref}>
          <div className="section">
            <div className="columns">
              <div className="column">
                <h3 className="title is-size-7">From</h3>
                <p>Test</p>
                <p>Test Test</p>
                <p>jk hgf jk</p>
                <p>Rayjkhjkleigh</p>
                <p>jhj</p>
                <p>TEst</p>
              </div>
              <div className="column">
                <h3 className="title is-size-7">For</h3>
                <p>jjh jhk jkh</p>
                <p>jkjkhhj jk kj</p>
                <p>jkh</p>
                <p>kjhj kjhkjh</p>
              </div>
              <div className="column">
                <h5 className="title is-size-7">Details</h5>
                <p>Date: 14/02/19</p>
                <p>Due Date: 28/02/19</p>
                <p>Invoice No: A001001</p>
              </div>
            </div>
            
            <table className="table is-fullwidth">
              <tr>
                <th>Item no</th>
                <th>Description</th>
                <th>Quantity</th>
                <th>Unit Price</th>
                <th>Amount</th>
              </tr>
              <tr>
                <td></td>
                <td>Jeff</td>
                <td>3</td>
                <td>&pound;20</td>
                <td>&pound;60</td>
              </tr>
              <tr>
                <td></td>
                <td>Bob</td>
                <td>1</td>
                <td>&pound;10</td>
                <td>&pound;10</td>
              </tr>
              <tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
              </tr>
              <tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
              </tr>
              <tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
              </tr>
              <tr>
                <td colSpan="4" style={{textAlign: 'right'}}>Sub total</td>
                <td>&pound;70</td>
              </tr>
              <tr>
                <td colSpan="4" style={{textAlign: 'right'}}>Discount</td>
                <td>0%</td>
              </tr>
              <tr>
                <td colSpan="4" style={{textAlign: 'right'}}>Amount Due</td>
                <td>&pound;70</td>
              </tr>
            </table>
            <hr />
            <h3 className="title is-size-7">Notes</h3>
            <p className="notes"></p>
          </div>
        </div>

this is the result of my react component. the .innerDoc class is 595px wide by 842px high.
screenshot 2019-02-15 at 14 18 19

When generating my PDF I can't seem to make my component react full width or height of the PDF?
screenshot 2019-02-15 at 14 18 33

Any ideas how I can resolve this? I haven't yet dived into your package code. Thought I'd best ask first

Unit/format options not working

Hello.

I love this tool, it really helped me out with a feature I was working on, so thanks a lot!

One issue I'm having is that the 'unit'/'format' keys on the settings object do not seem to be having the desired effect. I keep getting tiny little files rather than the measurements I input.

Here's an example:

<Pdf 
  options={{
    orientation:"landscape", 
    unit:"in", format:[cover_width, cover_height]
   }} 
   onComplete={()=>setLoading(false)} 
   targetRef={ref} 
   filename={`${projectTitle}_cover.pdf`}>

The input values are:
cover_width: 12.316756756756757
cover_height: 9.25

It is orientated correctly, document is 0.43cm x 0.43cm!

Any ideas what I'm doing wrong??

Many thanks

Left side is offset and right side is cut off

I forked sample sandbox given in the readme and generated pdf. But, texts got cut off and its was off the alignment.

I referred and added CSS properties to match a4 paper size and it rendered pdf. But, still there is a offset in the left side with white space and right side is cut off.

image

How could this be rectified so that the content is not lost.

Forked and edited sandbox Link

Forked URL

error when installing react-to-pdf package

when i try to install react-to-pdf package using this command : npm install react-to-pdf
i get this errors :

npm ERR! code ENOENT 
npm ERR! syscall spawn git
npm ERR! path git
npm ERR! errno -4058
npm ERR! enoent Error while executing:
npm ERR! enoent undefined ls-remote -h -t ssh://[email protected]/eligrey/FileSaver.js.git
npm ERR! enoent 
npm ERR! enoent
npm ERR! enoent spawn git ENOENT
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

could someone tell me what the problem is ?

xmldom needs an update

                   === npm audit security report ===                        


                             Manual Review                                  
         Some vulnerabilities require your attention to resolve             
                                                                            
      Visit https://go.npm.me/audit-guide for additional guidance           

Low Misinterpretation of malicious XML input

Package xmldom

Patched in >=0.5.0

Dependency of react-to-pdf

Path react-to-pdf > jspdf > canvg > xmldom

More info https://nodesecurity.io/advisories/1650

window is not defined

As soon as I: import reactToPdf from 'react-to-pdf';
I get: ReferenceError: window is not defined
Seems to be an issue with jspdf?
The error message pointed here:node_modules/jspdf/dist/jspdf.min.js:37:30237

multiple section

multiple section

how to include multiple react components to a single pdf

Its possible add a content to the pdf?

I, i need add a header and a footer only to the pdf, not to the component but i am having difficulty
Its possible do something like this?

thanks for the lib

My PDF is getting cut off

I have the following code

import Pdf from 'react-to-pdf'
...
return (
 <Layout>
      <Pdf targetRef={ref} filename="code-example.pdf">
        {({ toPdf }) => <Button onClick={toPdf}>Generate Pdf</Button>}
      </Pdf>
      <Container ref={ref}>
        <Section0 fluid={data.resumePic.childImageSharp.fluid} />
        <Section1 />
      </Container>
    </Layout>
)

my PDF keeps getting cut off in width though. Ie. it only shows the left half of the page that is contained inside container...
How can I fix this?

Iframe inside div is not getting captured

Iframe inside div is not getting captured. to avoid cors i deployed iframe on localhost:8000 and my code is on localhost:5000
In screenshot u can see blue color is div inside that iframe( localhost:8000 ) is there. only div is getting captured with blue color not iframe contents

Screen Shot 2020-09-24 at 2 39 18 AM

React 17 compatibility

Hi! Thanks for this very useful package. I was wondering, do you have any plans to make this compatible with React 17?

render pdf in list

Hi. I have a list with 50> items. In each item I have a some unique information and button "Print me".
If I try download/print first item - everything is ok. But if i try download/print second item I got white area in a top, (100-200px maybe)
If I try download/print tenth item(for example), i got white page.

Maybe you know what is wrong with it?

Thank you)

package.json "module" value points to missing file

Currently using node v.14.15.4 and snowpack in my dev environment. After install, I received the following error:

[snowpack] ! building dependencies...
[snowpack] Cannot find module ' ... react-app/app/node_modules/react-to-pdf/umd/index.js'
Require stack:
- ... react-app/app/node_modules/snowpack/lib/index.js
-  ... react-app/app/node_modules/snowpack/index.bin.js

It looks like this file is missing from the build.

I was able to fix this locally by changing the following value in package.json:

{
...
    "module": "umd/react-to-pdf.js",
...
}

blank pdf generated in production

in development everything work fine but in production i only see a blank page

const ref = React.createRef();

<div>
// code of the ui that will be printed 
</div>

<Pdf targetRef={ref} filename="code-example.pdf">
        {({ toPdf }) => <button onClick={toPdf}>Generate Pdf</button>}
 </Pdf>

Development :
Screen Shot 2021-01-16 at 16 54 32

Production :
Screen Shot 2021-01-16 at 16 54 41

General Fixes

Upgrad eslint
Conflicted code in source
Const to var in index
Support UMD

Convert only One Page

Hi ,

I am converting the Invoice Page to Pdf using react-to-pdf plugin.
Its Converted Particular Height of the Page Only.My Invoice Contains Two Number of Pages.
But this plugin only Convert a single Page with the Paticular Height.

PDF is not responsive

While I'm generating the pdf with resolution 1920x1080 it is generating perfectly fine pdf, But when I'm trying to generate the same on 1366x768 the context is being zoomed in pdf.

const options = {
      orientation: 'p',
      unit: 'px',
      format: [1176, 860],
};

These are the options I'm using, let me know if I'm doing something wrong here!

Generating Blank pdf file

when i click on export button library generates blank pdf file

<ReactToPdf targetRef={reference1} x={5} y={5} scale={1} filename="my-stocks.pdf" options={pdfOptions} > {({ toPdf }) => ( <IconButton onClick={toPdf} reactIcon={ <AiOutlineImport className="orange-icon-btn" /> } className="orange-react-icon" btnText="Export File" /> )} </ReactToPdf>

<div className="my-stock-table" ref={reference1}> <StockTable loading={allPortfolio} id={portfolio?.id} OnDelete={DeleteSymbol} stock={portfolio} /> </div>

Images

I'm trying to implement your tool, but I have problem with downloading pdfs with images (set both as background-image and img). Img is dynamic and set with img={example} Do you have any idea how to fix it?

How to upload the generated pdf to server?

Thank you for providing awesome plugin.
I really like this package.
just I want to upload the generated pdf to my server so that I can send pdf via email.
Is it possible?

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.