All Projects β†’ schibsted β†’ Jsx Pdf

schibsted / Jsx Pdf

Licence: mit
Generate PDFs using JSX! 🎯

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Jsx Pdf

Satysfi
A statically-typed, functional typesetting system
Stars: ✭ 815 (+1047.89%)
Mutual labels:  pdf, pdf-generation
Unipdf
Golang PDF library for creating and processing PDF files (pure go)
Stars: ✭ 1,171 (+1549.3%)
Mutual labels:  pdf, pdf-generation
Itext7
iText 7 for Java represents the next level of SDKs for developers that want to take advantage of the benefits PDF can bring. Equipped with a better document engine, high and low-level programming capabilities and the ability to create, edit and enhance PDF documents, iText 7 can be a boon to nearly every workflow.
Stars: ✭ 913 (+1185.92%)
Mutual labels:  pdf, pdf-generation
Clj Pdf
PDF generation library for Clojure
Stars: ✭ 571 (+704.23%)
Mutual labels:  pdf, pdf-generation
Pdfsave
Convert websites into readable PDFs
Stars: ✭ 46 (-35.21%)
Mutual labels:  pdf, pdf-generation
Html Pdf Chrome
HTML to PDF converter via Chrome/Chromium
Stars: ✭ 629 (+785.92%)
Mutual labels:  pdf, pdf-generation
Asciidoctor Pdf
πŸ“ƒ Asciidoctor PDF: A native PDF converter for AsciiDoc based on Asciidoctor and Prawn, written entirely in Ruby.
Stars: ✭ 868 (+1122.54%)
Mutual labels:  pdf, pdf-generation
Printable Mockups
Create printable UI mockups & wireframes templates
Stars: ✭ 479 (+574.65%)
Mutual labels:  pdf, pdf-generation
Mkdocs With Pdf
Generate a single PDF file from MkDocs repository.
Stars: ✭ 39 (-45.07%)
Mutual labels:  pdf, pdf-generation
Alivepdf
[Official AlivePDF] - AlivePDF is a client side AS3 PDF generation library for Adobe Flash, Flex and AIR
Stars: ✭ 29 (-59.15%)
Mutual labels:  pdf, pdf-generation
Pikepdf
A Python library for reading and writing PDF, powered by qpdf
Stars: ✭ 566 (+697.18%)
Mutual labels:  pdf, pdf-generation
Openhtmltopdf
An HTML to PDF library for the JVM. Based on Flying Saucer and Apache PDF-BOX 2. With SVG image support. Now also with accessible PDF support (WCAG, Section 508, PDF/UA)!
Stars: ✭ 1,096 (+1443.66%)
Mutual labels:  pdf, pdf-generation
Combine pdf
A Pure ruby library to merge PDF files, number pages and maybe more...
Stars: ✭ 552 (+677.46%)
Mutual labels:  pdf, pdf-generation
Itext7 Dotnet
iText 7 for .NET is the .NET version of the iText 7 library, formerly known as iTextSharp, which it replaces. iText 7 represents the next level of SDKs for developers that want to take advantage of the benefits PDF can bring. Equipped with a better document engine, high and low-level programming capabilities and the ability to create, edit and enhance PDF documents, iText 7 can be a boon to nearly every workflow.
Stars: ✭ 698 (+883.1%)
Mutual labels:  pdf, pdf-generation
Dart pdf
Pdf creation module for dart/flutter
Stars: ✭ 500 (+604.23%)
Mutual labels:  pdf, pdf-generation
Hexapdf
Versatile PDF creation and manipulation for Ruby
Stars: ✭ 852 (+1100%)
Mutual labels:  pdf, pdf-generation
Printpdf
An easy-to-use library for writing PDF in Rust
Stars: ✭ 404 (+469.01%)
Mutual labels:  pdf, pdf-generation
One File Pdf
A minimalist Go PDF writer in 1982 lines. Draws text, images and shapes. Helps understand the PDF format. Used in production for reports.
Stars: ✭ 429 (+504.23%)
Mutual labels:  pdf, pdf-generation
Html Pdf Service
LGPL V3. Java Spring Boot microservice with RESTful webconsole and service endpoints that convert HTML to PDF, optionally styling with CSS and templating with JSON using Flying Saucer, PDF Box and Jackson libraries. Available on Docker Hub.
Stars: ✭ 12 (-83.1%)
Mutual labels:  pdf, pdf-generation
Sile
Simon’s Improved Layout Engine
Stars: ✭ 1,032 (+1353.52%)
Mutual labels:  pdf, pdf-generation

jsx-pdf logo

npm version Build Status Coverage Status

Generate modular PDFs via pdfmake using JSX.

import PDFMake from 'pdfmake';
import JsxPdf from 'jsx-pdf';
import { OpenSans } from './font-descriptors';

const pdfMake = new PDFMake({
  OpenSans,
});

const stream = pdfMake.createPdfKitDocument(
  JsxPdf.renderPdf(
    <document defaultStyle={{ font: 'OpenSans', fontSize: 12 }}>
      <content>This will appear in my PDF!</content>
    </document>,
  ),
);

// write the stream to a file; this could also be streamed to an HTTP connection, stdout etc
stream.on('finish', () => console.log('PDF generated'));
stream.pipe(fs.createWriteStream('~/Desktop/test.pdf'));
stream.end();

Quick start

Javascript

  • yarn add jsx-pdf @babel/plugin-transform-react-jsx
  • Configure the part of your build that transpiles your JSX to use JsxPdf.createElement as the element factory.
    • For babel, add the configuration below to your .babelrc.
    "plugins": [
      [
        "@babel/plugin-transform-react-jsx",
        { "pragma": "JsxPdf.createElement", "pragmaFrag": "JsxPdf.Fragment" }
      ]
    ]
    

Typescript

  • yarn add -D @types/jsx-pdf
  • For TypeScript, add the configuration below to your tsconfig.json. Setting jsx to react configures TypeScript to handle JSX transpiling for you, and the jsxFactory option specifies the element factory to use. Setting jsxFragmentFactory allows you to use JSX Fragments.
"compilerOptions": {
  "jsx": "react",
  "jsxFactory": "JsxPdf.createElement",
  "jsxFragmentFactory": "JsxPdf.Fragment",
},
  • Code away! See the examples below.

You can also run our example script by running yarn demo and opening the generated pdf at example/example.pdf. Check the console logs for additional information.

Components

Similar to modern front-end frameworks, you can define your own components using declarative syntax.

Basic example:

import JsxPdf from 'jsx-pdf';

const Greeting = ({ name }) => <text>Hello, {name}!</text>;

const doc = (
  <document>
    <content>
      <Greeting name="Bob" />
    </content>
  </document>
);

List example:

import JsxPdf from 'jsx-pdf';

const GroupGreeting = ({ names }) => (
  <>
    {names.map((name) => (
      <Greeting name={name} />
    ))}
  </>
);

const doc = (
  <document>
    <content>
      <GroupGreeting names={['Bob', 'Alice']} />
    </content>
  </document>
);

Inline If example:

import JsxPdf from 'jsx-pdf';

const Signature = () => <text>JSX-PDF, Inc.</text>;

const SignedGreeting = ({ name }) => (
  <>
    {name && <Greeting name={name} />}
    <Signature />
  </>
);

const doc = (
  <document>
    <content>
      <SignedGreeting />
    </content>
  </document>
);

Inline If-Else example:

import JsxPdf from 'jsx-pdf';

const AnonymousGreeting = () => <text>We don't know you.</text>;

const SignedGreeting = ({ name }) => (
  <>
    {name ? <Greeting name={name} /> : <AnonymousGreeting />}
    <Signature />
  </>
);

const doc = (
  <document>
    <content>
      <SignedGreeting />
    </content>
  </document>
);

Element variable example:

import JsxPdf from 'jsx-pdf';

const SignedGreeting = ({ name }) => {
  let greeting;

  if (name) {
    greeting = <Greeting name={name} />;
  } else {
    greeting = <AnonymousGreeting />;
  }

  return (
    <>
      {greeting}
      <Signature />
    </>
  );
};

const doc = (
  <document>
    <content>
      <SignedGreeting />
    </content>
  </document>
);

Styling

Styling can be done by adding appropriate attributes to tags. It's often helpful for readability to group style-related attributes together and use the spread syntax.

import JsxPdf from 'jsx-pdf';

const Greeting = ({ name }) => {
  const styles = {
    italics: true,
    fontSize: 10,
  };

  return <text {...styles}>Hello, {name}!</text>;
};

const doc = (
  <document>
    <content>
      <Greeting name="Bob" />
    </content>
  </document>
);

Context

Each component has access to global context and can update it if necessary.

import JsxPdf from 'jsx-pdf';

const AllowedUsersProvider = (attributes, context, updateContext) => {
  updateContext({
    allowedUsers: ['Alice'],
  });

  return attributes.children[0];
};

const SecureGreeting = ({ name }, { allowedUsers }) =>
  allowedUsers.includes(name) ? (
    <text>Hello, {name}!</text>
  ) : (
    <text>You are not allowed.</text>
  );

const doc = (
  <AllowedUsersProvider>
    <document>
      <content>
        <SecureGreeting name="Bob" />
      </content>
    </document>
  </AllowedUsersProvider>
);

Document primitives

This section describes basic elements provided by the library. More information about supported attributes and advanced examples can be found here.

Top elements

Each document has to be enclosed within document tag with nested content, and optional header and footer. The document is the place for configuration that affects the whole PDF, such as page margins, page size, default style, and metadata.

import JsxPdf from 'jsx-pdf';

const doc = (
  <document
    pageMargins={[20, 20, 20, 20]}
    pageSize="A4"
    defaultStyle={{
      font: 'OpenSans',
    }}
    info={{
      author: 'Buzz Lightyear',
    }}
  >
    <header>Greeting</header>
    <content>Hello, Bob!</content>
    <footer>JSX-PDF, Inc.</footer>
  </document>
);

Dynamic Header and Footer

If you want to use the dynamic header functionality in pdfmake, simply pass a render function as the only child of the header or footer:

const doc = (
  <document>
    <header>
      {(currentPage, pageCount) => (
        <text>
          Page {currentPage} of {pageCount}.
        </text>
      )}
    </header>
    <content>{/* ... */}</content>
  </document>
);

The parameters are:

  • currentPage - the 1-indexed page for which the content is being rendered
  • pageCount - the total number of pages in the document
  • pageSize - an object containing information about the dimensions of the page.

Paragraphs

Paragraphs are defined using text tag.

import JsxPdf from 'jsx-pdf';

const doc = (
  <document>
    <content>
      <text>
        This sentence will be rendered as one paragraph,

        even though there are

        line


        breaks.
      </text>
      <text>This is another paragraph.</text>
    </content>
  </document>
);

In order to apply styling to a group of paragraphs, they can be wrapped with a stack tag.

import JsxPdf from 'jsx-pdf';

const doc = (
  <document>
    <content>
      <stack color="red">
        <text>First red parahraph.</text>
        <text>Second red parahraph.</text>
      </stack>
      <text color="blue">Blue parahraph.</text>
    </content>
  </document>
);

Columns

Elements nested in columns tag will be stacked horizontally.

import JsxPdf from 'jsx-pdf';

const doc = (
  <document>
    <content>
      <columns columnGap={10}>
        <column width={100}>Fixed width column</column>
        <column width="10%">Percentage width column</column>
        <column width="auto">
          Column that adjusts width based on the content
        </column>
        <column width="*">Column that fills the remaining space</column>
      </columns>
    </content>
  </document>
);

Lists

Both ordered and unordered lists are supported.

import JsxPdf from 'jsx-pdf';

const docWithOrderedList = (
  <document>
    <content>
      <ol reversed start={10} separator={['(', ')']} type="lower-roman">
        <text>Item 1</text>
        <text>Item 2</text>
        <text>Item 3</text>
      </ol>
    </content>
  </document>
);

const docWithUnorderedList = (
  <document>
    <content>
      <ul color="blue" markerColor="red" type="square">
        <text>Item 1</text>
        <text>Item 2</text>
        <text>Item 3</text>
      </ul>
    </content>
  </document>
);

Tables

table tag provides a simple way of creating table layouts.

const leftCellStyle = {
  color: 'grey',
};

const doc = (
  <document>
    <content>
      <table widths={[100, '*', 'auto']} headerRows={1} layout="headerLineOnly">
        <row>
          <cell>Fixed width column</cell>
          <cell>Column that fills the remaining space</cell>
          <cell>Column that adjusts width based on the content</cell>
        </row>
        <row>
          <cell {...leftCellStyle}>Cell 1.1</cell>
          <cell>Cell 1.2</cell>
          <cell>Cell 1.3</cell>
        </row>
        <row>
          <cell {...leftCellStyle}>Cell 2.1</cell>
          <cell>Cell 2.2</cell>
          <cell>Cell 2.3</cell>
        </row>
      </table>
    </content>
  </document>
);

Images

image supports JPEG and PNG formats.

import JsxPdf from 'jsx-pdf';

const doc = (
  <document>
    <content>
      <image src="/home/bob/photos/Bob.png" width={150} height={150} />
    </content>
  </document>
);

SVGs

The svg tag can be used to render SVG images. The width, height and fill attributes can be used to control the size of the image as described in the pdfmake docs.

import JsxPdf from 'jsx-pdf';

const doc = (
  <document>
    <content>
      <svg
        content={`
          <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
            <circle fill="red" cx="50" cy="50" r="50"/>
          </svg>
        `}
      />
    </content>
  </document>
);

QR Codes

The qr tag can be used to render QR codes. There are various options available as described in the pdfmake docs.

import JsxPdf from 'jsx-pdf';

const doc = (
  <document>
    <content>
      <qr content="My text" />
    </content>
  </document>
);

API

renderPdf

Accepts JSX and returns a PDF JSON representation in the format expected by pdfmake.

createElement

This function converts JSX to object representation. Every time JSX syntax is used, the function has to be made available. The functionality depends on the babel plugin @babel/plugin-transform-react-jsx (or equivalent), and Babel must be set up in the project in order to transpile the JSX correctly.

Example .babelrc file:

{
  "presets": [
    [
      "env",
      {
        "targets": {
          "node": "6"
        }
      }
    ]
  ],
  "plugins": [
    [
      "transform-react-jsx",
      {
        "pragma": "JsxPdf.createElement"
      }
    ]
  ]
}

Disclaimer

Copyright 2018 Schibsted

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

License

By contributing to this project, you agree that your contributions will be licensed under its MIT license.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].