Latest repo

This commit is contained in:
Marc
2025-06-02 16:42:16 +00:00
parent 53ddf1a329
commit cde5fae175
27907 changed files with 3875388 additions and 1 deletions
+13
View File
@@ -0,0 +1,13 @@
<p align="center">
<img src="https://user-images.githubusercontent.com/5600341/27505816-c8bc37aa-587f-11e7-9a86-08a2d081a8b9.png" height="280px">
</p>
# @react-pdf/fns
> React-pdf helper functions
## How to install
```sh
yarn add @react-pdf/fns
```
+195
View File
@@ -0,0 +1,195 @@
/**
* Applies a function to the value at the given index of an array
*
* @param index
* @param fn
* @param collection
* @returns Copy of the array with the element at the given index replaced with the result of the function application.
*/
declare const adjust: (index: number, fn: (value: any) => any, collection: any[]) => any[];
type Fn$1 = (arg: any, ...args: any[]) => Promise<any> | any;
type FirstFnParameterType$1<T extends Fn$1[]> = T extends [
...any,
(arg: infer A, ...args: any[]) => Promise<any> | any
] ? A : never;
type LastFnReturnType$1<T extends Fn$1[]> = T extends [
(arg: any, ...args: any[]) => Promise<infer R> | infer R,
...any
] ? R : never;
/**
* Performs right-to-left function composition with async functions support
*
* @param fns - Functions
* @returns Composed function
*/
declare const asyncCompose: <T extends Fn$1[]>(...fns: T) => (value: FirstFnParameterType$1<T>, ...args: Parameters<T[0]> extends [any, ...infer Rest] ? Rest : []) => Promise<LastFnReturnType$1<T>>;
/**
* Capitalize first letter of each word
*
* @param value - Any string
* @returns Capitalized string
*/
declare const capitalize: (value?: string | null) => string | null | undefined;
/**
* Casts value to array
*
* @template T - The type of the value.
* @param value - The value to cast into an array.
* @returns An array containing the given value.
*/
declare const castArray: <T = any>(value: T | T[]) => T[];
type Fn = (arg: any, ...args: any[]) => any;
type FirstFnParameterType<T extends Fn[]> = T extends [
...any,
(arg: infer A, ...args: any[]) => any
] ? A : never;
type LastFnReturnType<T extends Fn[]> = T extends [
(arg: any, ...args: any[]) => infer R,
...any
] ? R : never;
/**
* Performs right-to-left function composition
*
* @param fns - Functions
* @returns Composed function
*/
declare const compose: <T extends Fn[]>(...fns: T) => (value: FirstFnParameterType<T>, ...args: any[]) => LastFnReturnType<T>;
/**
* Drops the last element from an array.
*
* @template T
* @param array - The array to drop the last element from
* @returns - The new array with the last element dropped
*/
declare const dropLast: <T = any>(array: string | T[]) => string | T[];
/**
* Applies a set of transformations to an object and returns a new object with the transformed values.
*
* @template T
* @param transformations - The transformations to apply.
* @param object - The object to transform.
* @returns The transformed object.
*/
declare function evolve<T extends Record<string, any>>(transformations: Partial<{
[K in keyof T]: (value: T[K]) => T[K];
}>, object: T): T;
/**
* Retrieves the value at a given path from an object.
*
* @param target - The object to retrieve the value from.
* @param path - The path of the value to retrieve.
* @param defaultValue - The default value to return if the path does not exist.
* @returns The value at the given path, or the default value if the path does not exist.
*/
declare const get: (target: any, path: (string | number)[], defaultValue: any) => any;
/**
* Checks if a value is null or undefined.
*
* @template T - The type of the value.
* @param value - The value to check
* @returns True if the value is null or undefined, false otherwise
*/
declare const isNil: (value: unknown) => value is null | undefined;
/**
* Returns the last character of a string.
*
* @param value - The input value
* @returns The last character of the string
*/
declare function last(value: string): string;
declare function last<T>(value: T[]): T;
type IteratorFn = (value: any, key: string, index: number) => any;
/**
* Maps over the values of an object and applies a function to each value.
*
* @param object - The object to map over
* @param fn - The function to apply to each value
* @returns A new object with the mapped values
*/
declare const mapValues: (object: Record<string, any>, fn: IteratorFn) => object;
interface PercentMatch {
percent: number;
value: number;
}
/**
* Get percentage value of input
*
* @param value
* @returns Percent value (if matches)
*/
declare const matchPercent: (value: string | number | null) => PercentMatch | null;
/**
* Creates a new object by omitting specified keys from the original object.
*
* @param keys - The key or keys to omit
* @param object - The original object
* @returns The new object without the omitted keys
*/
declare const omit: (keys: string | string[], object: Record<string, any>) => object;
/**
* Picks the specified keys from an object and returns a new object with only those keys.
*
* @param keys - The keys to pick from the object
* @param object - The object to pick the keys from
* @returns A new object with only the picked keys
*/
declare const pick: (keys: (string | number)[], obj: Record<string, any>) => object;
/**
* Repeats an element a specified number of times.
*
* @template T
* @param element - Element to be repeated
* @param length - Number of times to repeat element
* @returns Repeated elements
*/
declare const repeat: <T = any>(element: T, length?: number) => T[];
/**
* Reverses the list
*
* @template T
* @param list - List to be reversed
* @returns Reversed list
*/
declare const reverse: <T = any>(list: T[]) => T[];
/**
* Capitalize first letter of string
*
* @param value - String
* @returns Capitalized string
*/
declare const upperFirst: (value?: string | null) => string | null | undefined;
/**
* Returns a new array with all the values from the original array that are not present in the keys array.
*
* @param keys - The keys to pick from the object
* @param array - Array to filter the values from
* @returns A new array with without the omitted values
*/
declare const without: <T = any>(keys: T[], array: T[]) => T[];
/**
* Parse a string or number to a float
*
* @param value - String or number
* @returns Parsed float
*/
declare const parseFloat: (value: string | number) => number;
export { adjust, asyncCompose, capitalize, castArray, compose, dropLast, evolve, get, isNil, last, mapValues, matchPercent, omit, parseFloat, pick, repeat, reverse, upperFirst, without };
+271
View File
@@ -0,0 +1,271 @@
/**
* Applies a function to the value at the given index of an array
*
* @param index
* @param fn
* @param collection
* @returns Copy of the array with the element at the given index replaced with the result of the function application.
*/
const adjust = (index, fn, collection) => {
if (index >= 0 && index >= collection.length)
return collection;
if (index < 0 && Math.abs(index) > collection.length)
return collection;
const i = index < 0 ? collection.length + index : index;
return Object.assign([], collection, { [i]: fn(collection[i]) });
};
/* eslint-disable no-await-in-loop */
/**
* Performs right-to-left function composition with async functions support
*
* @param fns - Functions
* @returns Composed function
*/
const asyncCompose = (...fns) => async (value, ...args) => {
let result = value;
const reversedFns = fns.slice().reverse();
for (let i = 0; i < reversedFns.length; i += 1) {
const fn = reversedFns[i];
result = await fn(result, ...args);
}
return result;
};
/**
* Capitalize first letter of each word
*
* @param value - Any string
* @returns Capitalized string
*/
const capitalize = (value) => {
if (!value)
return value;
return value.replace(/(^|\s)\S/g, (l) => l.toUpperCase());
};
/**
* Casts value to array
*
* @template T - The type of the value.
* @param value - The value to cast into an array.
* @returns An array containing the given value.
*/
const castArray = (value) => {
return Array.isArray(value) ? value : [value];
};
/**
* Performs right-to-left function composition
*
* @param fns - Functions
* @returns Composed function
*/
const compose = (...fns) => (value, ...args) => {
let result = value;
const reversedFns = fns.slice().reverse();
for (let i = 0; i < reversedFns.length; i += 1) {
const fn = reversedFns[i];
result = fn(result, ...args);
}
return result;
};
/**
* Drops the last element from an array.
*
* @template T
* @param array - The array to drop the last element from
* @returns - The new array with the last element dropped
*/
const dropLast = (array) => array.slice(0, array.length - 1);
/**
* Applies a set of transformations to an object and returns a new object with the transformed values.
*
* @template T
* @param transformations - The transformations to apply.
* @param object - The object to transform.
* @returns The transformed object.
*/
function evolve(transformations, object) {
const result = {};
const keys = Object.keys(object);
for (let i = 0; i < keys.length; i += 1) {
const key = keys[i];
const transformation = transformations[key];
if (typeof transformation === 'function') {
result[key] = transformation(object[key]);
}
else {
result[key] = object[key];
}
}
return result;
}
/**
* Checks if a value is null or undefined.
*
* @template T - The type of the value.
* @param value - The value to check
* @returns True if the value is null or undefined, false otherwise
*/
const isNil = (value) => value === null || value === undefined;
/**
* Retrieves the value at a given path from an object.
*
* @param target - The object to retrieve the value from.
* @param path - The path of the value to retrieve.
* @param defaultValue - The default value to return if the path does not exist.
* @returns The value at the given path, or the default value if the path does not exist.
*/
const get = (target, path, defaultValue) => {
if (isNil(target))
return defaultValue;
const _path = castArray(path);
let result = target;
for (let i = 0; i < _path.length; i += 1) {
if (isNil(result))
return undefined;
result = result[_path[i]];
}
return isNil(result) ? defaultValue : result;
};
function last(value) {
return value === '' ? '' : value[value.length - 1];
}
/**
* Maps over the values of an object and applies a function to each value.
*
* @param object - The object to map over
* @param fn - The function to apply to each value
* @returns A new object with the mapped values
*/
const mapValues = (object, fn) => {
const entries = Object.entries(object);
const acc = {};
return entries.reduce((acc, [key, value], index) => {
acc[key] = fn(value, key, index);
return acc;
}, acc);
};
const isPercent = (value) => /((-)?\d+\.?\d*)%/g.exec(`${value}`);
/**
* Get percentage value of input
*
* @param value
* @returns Percent value (if matches)
*/
const matchPercent = (value) => {
const match = isPercent(value);
if (match) {
const f = parseFloat(match[1]);
const percent = f / 100;
return { percent, value: f };
}
return null;
};
/**
* Creates a new object by omitting specified keys from the original object.
*
* @param keys - The key or keys to omit
* @param object - The original object
* @returns The new object without the omitted keys
*/
const omit = (keys, object) => {
const _keys = castArray(keys);
const copy = Object.assign({}, object);
_keys.forEach((key) => {
delete copy[key];
});
return copy;
};
/**
* Picks the specified keys from an object and returns a new object with only those keys.
*
* @param keys - The keys to pick from the object
* @param object - The object to pick the keys from
* @returns A new object with only the picked keys
*/
const pick = (keys, obj) => {
const result = {};
for (let i = 0; i < keys.length; i += 1) {
const key = keys[i];
if (key in obj)
result[key] = obj[key];
}
return result;
};
/**
* Repeats an element a specified number of times.
*
* @template T
* @param element - Element to be repeated
* @param length - Number of times to repeat element
* @returns Repeated elements
*/
const repeat = (element, length = 0) => {
const result = new Array(length);
for (let i = 0; i < length; i += 1) {
result[i] = element;
}
return result;
};
/**
* Reverses the list
*
* @template T
* @param list - List to be reversed
* @returns Reversed list
*/
const reverse = (list) => Array.prototype.slice.call(list, 0).reverse();
/**
* Capitalize first letter of string
*
* @param value - String
* @returns Capitalized string
*/
const upperFirst = (value) => {
if (!value)
return value;
return value.charAt(0).toUpperCase() + value.slice(1);
};
/**
* Returns a new array with all the values from the original array that are not present in the keys array.
*
* @param keys - The keys to pick from the object
* @param array - Array to filter the values from
* @returns A new array with without the omitted values
*/
const without = (keys, array) => {
const result = [];
for (let i = 0; i < array.length; i += 1) {
const value = array[i];
if (!keys.includes(value))
result.push(value);
}
return result;
};
/**
* Parse a string or number to a float
*
* @param value - String or number
* @returns Parsed float
*/
const parseFloat$1 = (value) => {
return typeof value === 'string' ? Number.parseFloat(value) : value;
};
export { adjust, asyncCompose, capitalize, castArray, compose, dropLast, evolve, get, isNil, last, mapValues, matchPercent, omit, parseFloat$1 as parseFloat, pick, repeat, reverse, upperFirst, without };
+25
View File
@@ -0,0 +1,25 @@
{
"name": "@react-pdf/fns",
"version": "3.1.2",
"license": "MIT",
"description": "React-pdf helper functions",
"author": "Diego Muracciole <diegomuracciole@gmail.com>",
"homepage": "https://github.com/diegomura/react-pdf#readme",
"type": "module",
"main": "./lib/index.js",
"types": "./lib/index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/diegomura/react-pdf.git",
"directory": "packages/fns"
},
"scripts": {
"test": "vitest",
"build": "rollup -c",
"watch": "rollup -c -w",
"typecheck": "tsc --noEmit"
},
"files": [
"lib"
]
}
+5
View File
@@ -0,0 +1,5 @@
<p align="center">
<img src="https://user-images.githubusercontent.com/5600341/27505816-c8bc37aa-587f-11e7-9a86-08a2d081a8b9.png" height="280px">
</p>
# @react-pdf/font
+476
View File
@@ -0,0 +1,476 @@
import 'is-url';
import * as fontkit from 'fontkit';
import { PDFFont } from '@react-pdf/pdfkit';
// @ts-expect-error ts being silly
const STANDARD_FONTS = [
'Courier',
'Courier-Bold',
'Courier-Oblique',
'Courier-BoldOblique',
'Helvetica',
'Helvetica-Bold',
'Helvetica-Oblique',
'Helvetica-BoldOblique',
'Times-Roman',
'Times-Bold',
'Times-Italic',
'Times-BoldItalic',
];
class StandardFont {
name;
src;
fullName;
familyName;
subfamilyName;
postscriptName;
copyright;
version;
underlinePosition;
underlineThickness;
italicAngle;
bbox;
'OS/2';
hhea;
numGlyphs;
characterSet;
availableFeatures;
type;
constructor(src) {
this.name = src;
this.fullName = src;
this.familyName = src;
this.subfamilyName = src;
this.type = 'STANDARD';
this.postscriptName = src;
this.availableFeatures = [];
this.copyright = '';
this.version = 1;
this.underlinePosition = -100;
this.underlineThickness = 50;
this.italicAngle = 0;
this.bbox = {};
this['OS/2'] = {};
this.hhea = {};
this.numGlyphs = 0;
this.characterSet = [];
this.src = PDFFont.open(null, src);
}
encode(str) {
return this.src.encode(str);
}
layout(str) {
const [encoded, positions] = this.encode(str);
const glyphs = encoded.map((g, i) => {
const glyph = this.getGlyph(parseInt(g, 16));
glyph.advanceWidth = positions[i].advanceWidth;
return glyph;
});
const advanceWidth = positions.reduce((acc, p) => acc + p.advanceWidth, 0);
return {
positions,
stringIndices: positions.map((_, i) => i),
glyphs,
script: 'latin',
language: 'dflt',
direction: 'ltr',
features: {},
advanceWidth,
advanceHeight: 0,
bbox: undefined,
};
}
glyphForCodePoint(codePoint) {
const glyph = this.getGlyph(codePoint);
glyph.advanceWidth = 400;
return glyph;
}
getGlyph(id) {
return {
id,
codePoints: [id],
isLigature: false,
name: this.src.font.characterToGlyph(id),
_font: this.src,
// @ts-expect-error assign proper value
advanceWidth: undefined,
};
}
hasGlyphForCodePoint(codePoint) {
return this.src.font.characterToGlyph(codePoint) !== '.notdef';
}
// Based on empirical observation
get ascent() {
return 900;
}
// Based on empirical observation
get capHeight() {
switch (this.name) {
case 'Times-Roman':
case 'Times-Bold':
case 'Times-Italic':
case 'Times-BoldItalic':
return 650;
case 'Courier':
case 'Courier-Bold':
case 'Courier-Oblique':
case 'Courier-BoldOblique':
return 550;
default:
return 690;
}
}
// Based on empirical observation
get xHeight() {
switch (this.name) {
case 'Times-Roman':
case 'Times-Bold':
case 'Times-Italic':
case 'Times-BoldItalic':
return 440;
case 'Courier':
case 'Courier-Bold':
case 'Courier-Oblique':
case 'Courier-BoldOblique':
return 390;
default:
return 490;
}
}
// Based on empirical observation
get descent() {
switch (this.name) {
case 'Times-Roman':
case 'Times-Bold':
case 'Times-Italic':
case 'Times-BoldItalic':
return -220;
case 'Courier':
case 'Courier-Bold':
case 'Courier-Oblique':
case 'Courier-BoldOblique':
return -230;
default:
return -200;
}
}
get lineGap() {
return 0;
}
get unitsPerEm() {
return 1000;
}
stringsForGlyph() {
throw new Error('Method not implemented.');
}
glyphsForString() {
throw new Error('Method not implemented.');
}
widthOfGlyph() {
throw new Error('Method not implemented.');
}
getAvailableFeatures() {
throw new Error('Method not implemented.');
}
createSubset() {
throw new Error('Method not implemented.');
}
getVariation() {
throw new Error('Method not implemented.');
}
getFont() {
throw new Error('Method not implemented.');
}
getName() {
throw new Error('Method not implemented.');
}
setDefaultLanguage() {
throw new Error('Method not implemented.');
}
}
const fetchFont = async (src, options) => {
const response = await fetch(src, options);
const data = await response.arrayBuffer();
return new Uint8Array(data);
};
const isDataUrl = (dataUrl) => {
const header = dataUrl.split(',')[0];
const hasDataPrefix = header.substring(0, 5) === 'data:';
const hasBase64Prefix = header.split(';')[1] === 'base64';
return hasDataPrefix && hasBase64Prefix;
};
class FontSource {
src;
fontFamily;
fontStyle;
fontWeight;
data;
options;
loadResultPromise;
constructor(src, fontFamily, fontStyle, fontWeight, options) {
this.src = src;
this.fontFamily = fontFamily;
this.fontStyle = fontStyle || 'normal';
this.fontWeight = fontWeight || 400;
this.data = null;
this.options = options || {};
this.loadResultPromise = null;
}
async _load() {
const { postscriptName } = this.options;
let data = null;
if (STANDARD_FONTS.includes(this.src)) {
data = new StandardFont(this.src);
}
else if (isDataUrl(this.src)) {
const raw = this.src.split(',')[1];
const uint8Array = new Uint8Array(atob(raw)
.split('')
.map((c) => c.charCodeAt(0)));
data = fontkit.create(uint8Array, postscriptName);
}
else {
const { headers, body, method = 'GET' } = this.options;
const buffer = await fetchFont(this.src, { method, body, headers });
data = fontkit.create(buffer, postscriptName);
}
if (data && 'fonts' in data) {
throw new Error('Font collection is not supported');
}
this.data = data;
}
async load() {
if (this.loadResultPromise === null) {
this.loadResultPromise = this._load();
}
return this.loadResultPromise;
}
}
const FONT_WEIGHTS = {
thin: 100,
hairline: 100,
ultralight: 200,
extralight: 200,
light: 300,
normal: 400,
medium: 500,
semibold: 600,
demibold: 600,
bold: 700,
ultrabold: 800,
extrabold: 800,
heavy: 900,
black: 900,
};
const resolveFontWeight = (value) => {
return typeof value === 'string' ? FONT_WEIGHTS[value] : value;
};
const sortByFontWeight = (a, b) => a.fontWeight - b.fontWeight;
class FontFamily {
family;
sources;
static create(family) {
return new FontFamily(family);
}
constructor(family) {
this.family = family;
this.sources = [];
}
register({ src, fontWeight, fontStyle, ...options }) {
const numericFontWeight = fontWeight
? resolveFontWeight(fontWeight)
: undefined;
this.sources.push(new FontSource(src, this.family, fontStyle, numericFontWeight, options));
}
resolve(descriptor) {
const { fontWeight = 400, fontStyle = 'normal' } = descriptor;
const styleSources = this.sources.filter((s) => s.fontStyle === fontStyle);
const exactFit = styleSources.find((s) => s.fontWeight === fontWeight);
if (exactFit)
return exactFit;
// Weight resolution. https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight#Fallback_weights
let font = null;
const numericFontWeight = resolveFontWeight(fontWeight);
if (numericFontWeight >= 400 && numericFontWeight <= 500) {
const leftOffset = styleSources.filter((s) => s.fontWeight <= numericFontWeight);
const rightOffset = styleSources.filter((s) => s.fontWeight > 500);
const fit = styleSources.filter((s) => s.fontWeight >= numericFontWeight && s.fontWeight < 500);
font = fit[0] || leftOffset[leftOffset.length - 1] || rightOffset[0];
}
const lt = styleSources
.filter((s) => s.fontWeight < numericFontWeight)
.sort(sortByFontWeight);
const gt = styleSources
.filter((s) => s.fontWeight > numericFontWeight)
.sort(sortByFontWeight);
if (numericFontWeight < 400) {
font = lt[lt.length - 1] || gt[0];
}
if (numericFontWeight > 500) {
font = gt[0] || lt[lt.length - 1];
}
if (!font) {
throw new Error(`Could not resolve font for ${this.family}, fontWeight ${fontWeight}, fontStyle ${fontStyle}`);
}
return font;
}
}
class FontStore {
fontFamilies = {};
emojiSource = null;
constructor() {
this.register({
family: 'Helvetica',
fonts: [
{ src: 'Helvetica', fontStyle: 'normal', fontWeight: 400 },
{ src: 'Helvetica-Bold', fontStyle: 'normal', fontWeight: 700 },
{ src: 'Helvetica-Oblique', fontStyle: 'italic', fontWeight: 400 },
{ src: 'Helvetica-BoldOblique', fontStyle: 'italic', fontWeight: 700 },
],
});
this.register({
family: 'Courier',
fonts: [
{ src: 'Courier', fontStyle: 'normal', fontWeight: 400 },
{ src: 'Courier-Bold', fontStyle: 'normal', fontWeight: 700 },
{ src: 'Courier-Oblique', fontStyle: 'italic', fontWeight: 400 },
{ src: 'Courier-BoldOblique', fontStyle: 'italic', fontWeight: 700 },
],
});
this.register({
family: 'Times-Roman',
fonts: [
{ src: 'Times-Roman', fontStyle: 'normal', fontWeight: 400 },
{ src: 'Times-Bold', fontStyle: 'normal', fontWeight: 700 },
{ src: 'Times-Italic', fontStyle: 'italic', fontWeight: 400 },
{ src: 'Times-BoldItalic', fontStyle: 'italic', fontWeight: 700 },
],
});
// For backwards compatibility
this.register({
family: 'Helvetica-Bold',
src: 'Helvetica-Bold',
});
this.register({
family: 'Helvetica-Oblique',
src: 'Helvetica-Oblique',
});
this.register({
family: 'Helvetica-BoldOblique',
src: 'Helvetica-BoldOblique',
});
this.register({
family: 'Courier-Bold',
src: 'Courier-Bold',
});
this.register({
family: 'Courier-Oblique',
src: 'Courier-Oblique',
});
this.register({
family: 'Courier-BoldOblique',
src: 'Courier-BoldOblique',
});
this.register({
family: 'Times-Bold',
src: 'Times-Bold',
});
this.register({
family: 'Times-Italic',
src: 'Times-Italic',
});
this.register({
family: 'Times-BoldItalic',
src: 'Times-BoldItalic',
});
// Load default fonts
this.load({
fontFamily: 'Helvetica',
fontStyle: 'normal',
fontWeight: 400,
});
this.load({
fontFamily: 'Helvetica',
fontStyle: 'normal',
fontWeight: 700,
});
this.load({
fontFamily: 'Helvetica',
fontStyle: 'italic',
fontWeight: 400,
});
this.load({
fontFamily: 'Helvetica',
fontStyle: 'italic',
fontWeight: 700,
});
}
hyphenationCallback = null;
register = (data) => {
const { family } = data;
if (!this.fontFamilies[family]) {
this.fontFamilies[family] = FontFamily.create(family);
}
// Bulk loading
if ('fonts' in data) {
for (let i = 0; i < data.fonts.length; i += 1) {
const { src, fontStyle, fontWeight, ...options } = data.fonts[i];
this.fontFamilies[family].register({
src,
fontStyle,
fontWeight,
...options,
});
}
}
else {
const { src, fontStyle, fontWeight, ...options } = data;
this.fontFamilies[family].register({
src,
fontStyle,
fontWeight,
...options,
});
}
};
registerEmojiSource = (emojiSource) => {
this.emojiSource = emojiSource;
};
registerHyphenationCallback = (callback) => {
this.hyphenationCallback = callback;
};
getFont = (descriptor) => {
const { fontFamily } = descriptor;
if (!this.fontFamilies[fontFamily]) {
throw new Error(`Font family not registered: ${fontFamily}. Please register it calling Font.register() method.`);
}
return this.fontFamilies[fontFamily].resolve(descriptor);
};
load = async (descriptor) => {
const font = this.getFont(descriptor);
if (font)
await font.load();
};
reset = () => {
const keys = Object.keys(this.fontFamilies);
for (let i = 0; i < keys.length; i += 1) {
const key = keys[i];
for (let j = 0; j < this.fontFamilies[key].sources.length; j++) {
const fontSource = this.fontFamilies[key].sources[j];
fontSource.data = null;
}
}
};
clear = () => {
this.fontFamilies = {};
};
getRegisteredFonts = () => this.fontFamilies;
getEmojiSource = () => this.emojiSource;
getHyphenationCallback = () => this.hyphenationCallback;
getRegisteredFontFamilies = () => Object.keys(this.fontFamilies);
}
export { FontStore as default };
+87
View File
@@ -0,0 +1,87 @@
import * as fontkit from 'fontkit';
type Font = Omit<fontkit.Font, 'type'> & {
type: 'TTF' | 'WOFF' | 'WOFF2' | 'STANDARD';
encode?: (string: string) => number[];
};
type FontStyle = 'normal' | 'italic' | 'oblique';
type FontWeight = number | 'thin' | 'ultralight' | 'light' | 'normal' | 'medium' | 'semibold' | 'bold' | 'ultrabold' | 'heavy';
type FontDescriptor = {
fontFamily: string;
fontStyle?: FontStyle;
fontWeight?: FontWeight;
};
type RemoteOptions = {
method?: 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
headers?: Record<string, string>;
body?: any;
};
type FontSourceOptions = {
postscriptName?: string;
} & RemoteOptions;
type FontSource$1 = {
src: string;
fontStyle?: FontStyle;
fontWeight?: FontWeight;
} & FontSourceOptions;
type SingleLoad = {
family: string;
} & FontSource$1;
type BulkLoad = {
family: string;
fonts: FontSource$1[];
};
interface EmojiSourceUrl {
url: string;
format?: string;
withVariationSelectors?: boolean;
}
interface EmojiSourceBuilder {
builder: (code: string) => string;
withVariationSelectors?: boolean;
}
type EmojiSource = EmojiSourceUrl | EmojiSourceBuilder;
type HyphenationCallback = (word: string) => string[];
declare class FontSource {
src: string;
fontFamily: string;
fontStyle: FontStyle;
fontWeight: number;
data: Font | null;
options: FontSourceOptions;
loadResultPromise: Promise<void> | null;
constructor(src: string, fontFamily: string, fontStyle?: FontStyle, fontWeight?: number, options?: FontSourceOptions);
_load(): Promise<void>;
load(): Promise<void>;
}
declare class FontFamily {
family: string;
sources: FontSource[];
static create(family: string): FontFamily;
constructor(family: string);
register({ src, fontWeight, fontStyle, ...options }: Omit<SingleLoad, 'family'>): void;
resolve(descriptor: FontDescriptor): FontSource;
}
declare class FontStore {
fontFamilies: Record<string, FontFamily>;
emojiSource: EmojiSource | null;
constructor();
hyphenationCallback: HyphenationCallback | null;
register: (data: SingleLoad | BulkLoad) => void;
registerEmojiSource: (emojiSource: EmojiSource) => void;
registerHyphenationCallback: (callback: HyphenationCallback) => void;
getFont: (descriptor: FontDescriptor) => FontSource;
load: (descriptor: FontDescriptor) => Promise<void>;
reset: () => void;
clear: () => void;
getRegisteredFonts: () => Record<string, FontFamily>;
getEmojiSource: () => EmojiSource | null;
getHyphenationCallback: () => HyphenationCallback | null;
getRegisteredFontFamilies: () => string[];
}
type FontStoreType = FontStore;
export { type BulkLoad, type EmojiSource, type Font, type FontDescriptor, type FontSource$1 as FontSource, type FontSourceOptions, type FontStoreType, type FontStyle, type FontWeight, type HyphenationCallback, type RemoteOptions, type SingleLoad, FontStore as default };
+479
View File
@@ -0,0 +1,479 @@
import isUrl from 'is-url';
import * as fontkit from 'fontkit';
import { PDFFont } from '@react-pdf/pdfkit';
// @ts-expect-error ts being silly
const STANDARD_FONTS = [
'Courier',
'Courier-Bold',
'Courier-Oblique',
'Courier-BoldOblique',
'Helvetica',
'Helvetica-Bold',
'Helvetica-Oblique',
'Helvetica-BoldOblique',
'Times-Roman',
'Times-Bold',
'Times-Italic',
'Times-BoldItalic',
];
class StandardFont {
name;
src;
fullName;
familyName;
subfamilyName;
postscriptName;
copyright;
version;
underlinePosition;
underlineThickness;
italicAngle;
bbox;
'OS/2';
hhea;
numGlyphs;
characterSet;
availableFeatures;
type;
constructor(src) {
this.name = src;
this.fullName = src;
this.familyName = src;
this.subfamilyName = src;
this.type = 'STANDARD';
this.postscriptName = src;
this.availableFeatures = [];
this.copyright = '';
this.version = 1;
this.underlinePosition = -100;
this.underlineThickness = 50;
this.italicAngle = 0;
this.bbox = {};
this['OS/2'] = {};
this.hhea = {};
this.numGlyphs = 0;
this.characterSet = [];
this.src = PDFFont.open(null, src);
}
encode(str) {
return this.src.encode(str);
}
layout(str) {
const [encoded, positions] = this.encode(str);
const glyphs = encoded.map((g, i) => {
const glyph = this.getGlyph(parseInt(g, 16));
glyph.advanceWidth = positions[i].advanceWidth;
return glyph;
});
const advanceWidth = positions.reduce((acc, p) => acc + p.advanceWidth, 0);
return {
positions,
stringIndices: positions.map((_, i) => i),
glyphs,
script: 'latin',
language: 'dflt',
direction: 'ltr',
features: {},
advanceWidth,
advanceHeight: 0,
bbox: undefined,
};
}
glyphForCodePoint(codePoint) {
const glyph = this.getGlyph(codePoint);
glyph.advanceWidth = 400;
return glyph;
}
getGlyph(id) {
return {
id,
codePoints: [id],
isLigature: false,
name: this.src.font.characterToGlyph(id),
_font: this.src,
// @ts-expect-error assign proper value
advanceWidth: undefined,
};
}
hasGlyphForCodePoint(codePoint) {
return this.src.font.characterToGlyph(codePoint) !== '.notdef';
}
// Based on empirical observation
get ascent() {
return 900;
}
// Based on empirical observation
get capHeight() {
switch (this.name) {
case 'Times-Roman':
case 'Times-Bold':
case 'Times-Italic':
case 'Times-BoldItalic':
return 650;
case 'Courier':
case 'Courier-Bold':
case 'Courier-Oblique':
case 'Courier-BoldOblique':
return 550;
default:
return 690;
}
}
// Based on empirical observation
get xHeight() {
switch (this.name) {
case 'Times-Roman':
case 'Times-Bold':
case 'Times-Italic':
case 'Times-BoldItalic':
return 440;
case 'Courier':
case 'Courier-Bold':
case 'Courier-Oblique':
case 'Courier-BoldOblique':
return 390;
default:
return 490;
}
}
// Based on empirical observation
get descent() {
switch (this.name) {
case 'Times-Roman':
case 'Times-Bold':
case 'Times-Italic':
case 'Times-BoldItalic':
return -220;
case 'Courier':
case 'Courier-Bold':
case 'Courier-Oblique':
case 'Courier-BoldOblique':
return -230;
default:
return -200;
}
}
get lineGap() {
return 0;
}
get unitsPerEm() {
return 1000;
}
stringsForGlyph() {
throw new Error('Method not implemented.');
}
glyphsForString() {
throw new Error('Method not implemented.');
}
widthOfGlyph() {
throw new Error('Method not implemented.');
}
getAvailableFeatures() {
throw new Error('Method not implemented.');
}
createSubset() {
throw new Error('Method not implemented.');
}
getVariation() {
throw new Error('Method not implemented.');
}
getFont() {
throw new Error('Method not implemented.');
}
getName() {
throw new Error('Method not implemented.');
}
setDefaultLanguage() {
throw new Error('Method not implemented.');
}
}
const fetchFont = async (src, options) => {
const response = await fetch(src, options);
const data = await response.arrayBuffer();
return new Uint8Array(data);
};
const isDataUrl = (dataUrl) => {
const header = dataUrl.split(',')[0];
const hasDataPrefix = header.substring(0, 5) === 'data:';
const hasBase64Prefix = header.split(';')[1] === 'base64';
return hasDataPrefix && hasBase64Prefix;
};
class FontSource {
src;
fontFamily;
fontStyle;
fontWeight;
data;
options;
loadResultPromise;
constructor(src, fontFamily, fontStyle, fontWeight, options) {
this.src = src;
this.fontFamily = fontFamily;
this.fontStyle = fontStyle || 'normal';
this.fontWeight = fontWeight || 400;
this.data = null;
this.options = options || {};
this.loadResultPromise = null;
}
async _load() {
const { postscriptName } = this.options;
let data = null;
if (STANDARD_FONTS.includes(this.src)) {
data = new StandardFont(this.src);
}
else if (isDataUrl(this.src)) {
const raw = this.src.split(',')[1];
const uint8Array = new Uint8Array(atob(raw)
.split('')
.map((c) => c.charCodeAt(0)));
data = fontkit.create(uint8Array, postscriptName);
}
else if (isUrl(this.src)) {
const { headers, body, method = 'GET' } = this.options;
const buffer = await fetchFont(this.src, { method, body, headers });
data = fontkit.create(buffer, postscriptName);
}
else {
data = await fontkit.open(this.src, postscriptName);
}
if (data && 'fonts' in data) {
throw new Error('Font collection is not supported');
}
this.data = data;
}
async load() {
if (this.loadResultPromise === null) {
this.loadResultPromise = this._load();
}
return this.loadResultPromise;
}
}
const FONT_WEIGHTS = {
thin: 100,
hairline: 100,
ultralight: 200,
extralight: 200,
light: 300,
normal: 400,
medium: 500,
semibold: 600,
demibold: 600,
bold: 700,
ultrabold: 800,
extrabold: 800,
heavy: 900,
black: 900,
};
const resolveFontWeight = (value) => {
return typeof value === 'string' ? FONT_WEIGHTS[value] : value;
};
const sortByFontWeight = (a, b) => a.fontWeight - b.fontWeight;
class FontFamily {
family;
sources;
static create(family) {
return new FontFamily(family);
}
constructor(family) {
this.family = family;
this.sources = [];
}
register({ src, fontWeight, fontStyle, ...options }) {
const numericFontWeight = fontWeight
? resolveFontWeight(fontWeight)
: undefined;
this.sources.push(new FontSource(src, this.family, fontStyle, numericFontWeight, options));
}
resolve(descriptor) {
const { fontWeight = 400, fontStyle = 'normal' } = descriptor;
const styleSources = this.sources.filter((s) => s.fontStyle === fontStyle);
const exactFit = styleSources.find((s) => s.fontWeight === fontWeight);
if (exactFit)
return exactFit;
// Weight resolution. https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight#Fallback_weights
let font = null;
const numericFontWeight = resolveFontWeight(fontWeight);
if (numericFontWeight >= 400 && numericFontWeight <= 500) {
const leftOffset = styleSources.filter((s) => s.fontWeight <= numericFontWeight);
const rightOffset = styleSources.filter((s) => s.fontWeight > 500);
const fit = styleSources.filter((s) => s.fontWeight >= numericFontWeight && s.fontWeight < 500);
font = fit[0] || leftOffset[leftOffset.length - 1] || rightOffset[0];
}
const lt = styleSources
.filter((s) => s.fontWeight < numericFontWeight)
.sort(sortByFontWeight);
const gt = styleSources
.filter((s) => s.fontWeight > numericFontWeight)
.sort(sortByFontWeight);
if (numericFontWeight < 400) {
font = lt[lt.length - 1] || gt[0];
}
if (numericFontWeight > 500) {
font = gt[0] || lt[lt.length - 1];
}
if (!font) {
throw new Error(`Could not resolve font for ${this.family}, fontWeight ${fontWeight}, fontStyle ${fontStyle}`);
}
return font;
}
}
class FontStore {
fontFamilies = {};
emojiSource = null;
constructor() {
this.register({
family: 'Helvetica',
fonts: [
{ src: 'Helvetica', fontStyle: 'normal', fontWeight: 400 },
{ src: 'Helvetica-Bold', fontStyle: 'normal', fontWeight: 700 },
{ src: 'Helvetica-Oblique', fontStyle: 'italic', fontWeight: 400 },
{ src: 'Helvetica-BoldOblique', fontStyle: 'italic', fontWeight: 700 },
],
});
this.register({
family: 'Courier',
fonts: [
{ src: 'Courier', fontStyle: 'normal', fontWeight: 400 },
{ src: 'Courier-Bold', fontStyle: 'normal', fontWeight: 700 },
{ src: 'Courier-Oblique', fontStyle: 'italic', fontWeight: 400 },
{ src: 'Courier-BoldOblique', fontStyle: 'italic', fontWeight: 700 },
],
});
this.register({
family: 'Times-Roman',
fonts: [
{ src: 'Times-Roman', fontStyle: 'normal', fontWeight: 400 },
{ src: 'Times-Bold', fontStyle: 'normal', fontWeight: 700 },
{ src: 'Times-Italic', fontStyle: 'italic', fontWeight: 400 },
{ src: 'Times-BoldItalic', fontStyle: 'italic', fontWeight: 700 },
],
});
// For backwards compatibility
this.register({
family: 'Helvetica-Bold',
src: 'Helvetica-Bold',
});
this.register({
family: 'Helvetica-Oblique',
src: 'Helvetica-Oblique',
});
this.register({
family: 'Helvetica-BoldOblique',
src: 'Helvetica-BoldOblique',
});
this.register({
family: 'Courier-Bold',
src: 'Courier-Bold',
});
this.register({
family: 'Courier-Oblique',
src: 'Courier-Oblique',
});
this.register({
family: 'Courier-BoldOblique',
src: 'Courier-BoldOblique',
});
this.register({
family: 'Times-Bold',
src: 'Times-Bold',
});
this.register({
family: 'Times-Italic',
src: 'Times-Italic',
});
this.register({
family: 'Times-BoldItalic',
src: 'Times-BoldItalic',
});
// Load default fonts
this.load({
fontFamily: 'Helvetica',
fontStyle: 'normal',
fontWeight: 400,
});
this.load({
fontFamily: 'Helvetica',
fontStyle: 'normal',
fontWeight: 700,
});
this.load({
fontFamily: 'Helvetica',
fontStyle: 'italic',
fontWeight: 400,
});
this.load({
fontFamily: 'Helvetica',
fontStyle: 'italic',
fontWeight: 700,
});
}
hyphenationCallback = null;
register = (data) => {
const { family } = data;
if (!this.fontFamilies[family]) {
this.fontFamilies[family] = FontFamily.create(family);
}
// Bulk loading
if ('fonts' in data) {
for (let i = 0; i < data.fonts.length; i += 1) {
const { src, fontStyle, fontWeight, ...options } = data.fonts[i];
this.fontFamilies[family].register({
src,
fontStyle,
fontWeight,
...options,
});
}
}
else {
const { src, fontStyle, fontWeight, ...options } = data;
this.fontFamilies[family].register({
src,
fontStyle,
fontWeight,
...options,
});
}
};
registerEmojiSource = (emojiSource) => {
this.emojiSource = emojiSource;
};
registerHyphenationCallback = (callback) => {
this.hyphenationCallback = callback;
};
getFont = (descriptor) => {
const { fontFamily } = descriptor;
if (!this.fontFamilies[fontFamily]) {
throw new Error(`Font family not registered: ${fontFamily}. Please register it calling Font.register() method.`);
}
return this.fontFamilies[fontFamily].resolve(descriptor);
};
load = async (descriptor) => {
const font = this.getFont(descriptor);
if (font)
await font.load();
};
reset = () => {
const keys = Object.keys(this.fontFamilies);
for (let i = 0; i < keys.length; i += 1) {
const key = keys[i];
for (let j = 0; j < this.fontFamilies[key].sources.length; j++) {
const fontSource = this.fontFamilies[key].sources[j];
fontSource.data = null;
}
}
};
clear = () => {
this.fontFamilies = {};
};
getRegisteredFonts = () => this.fontFamilies;
getEmojiSource = () => this.emojiSource;
getHyphenationCallback = () => this.hyphenationCallback;
getRegisteredFontFamilies = () => Object.keys(this.fontFamilies);
}
export { FontStore as default };
+38
View File
@@ -0,0 +1,38 @@
{
"name": "@react-pdf/font",
"version": "4.0.2",
"license": "MIT",
"description": "Register font and emoji source for react-pdf document",
"author": "Diego Muracciole <diegomuracciole@gmail.com>",
"homepage": "https://github.com/diegomura/react-pdf#readme",
"repository": {
"type": "git",
"url": "https://github.com/diegomura/react-pdf.git",
"directory": "packages/font"
},
"type": "module",
"main": "./lib/index.js",
"types": "./lib/index.d.ts",
"browser": {
"./lib/index.js": "./lib/index.browser.js"
},
"scripts": {
"test": "vitest",
"build": "rimraf ./lib && rollup -c",
"watch": "rimraf ./lib && rollup -c -w",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@react-pdf/pdfkit": "^4.0.3",
"@react-pdf/types": "^2.9.0",
"fontkit": "^2.0.2",
"is-url": "^1.2.4"
},
"files": [
"lib"
],
"devDependencies": {
"@types/fontkit": "^2.0.7",
"@types/is-url": "^1.2.32"
}
}
+5
View File
@@ -0,0 +1,5 @@
<p align="center">
<img src="https://user-images.githubusercontent.com/5600341/27505816-c8bc37aa-587f-11e7-9a86-08a2d081a8b9.png" height="280px">
</p>
# @react-pdf/image
File diff suppressed because it is too large Load Diff
+35
View File
@@ -0,0 +1,35 @@
/// <reference types="node" />
interface Image {
width: number;
height: number;
data: Buffer;
format: 'jpeg' | 'png';
key?: string;
}
type ImageFormat = 'jpg' | 'jpeg' | 'png';
type DataImageSrc = {
data: Buffer;
format: ImageFormat;
};
type LocalImageSrc = {
uri: string;
format?: ImageFormat;
};
type RemoteImageSrc = {
uri: string;
method?: 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
headers?: Record<string, string>;
format?: ImageFormat;
body?: any;
credentials?: 'omit' | 'same-origin' | 'include';
};
type Base64ImageSrc = {
uri: `data:image${string}`;
};
type ImageSrc = Blob | Buffer | DataImageSrc | LocalImageSrc | RemoteImageSrc | Base64ImageSrc;
declare const resolveImage: (src: ImageSrc, { cache }?: {
cache?: boolean | undefined;
}) => Promise<Image | null> | null;
export { type Image, type ImageSrc, resolveImage as default };
+257
View File
@@ -0,0 +1,257 @@
import fs from 'fs';
import url from 'url';
import path from 'path';
import _PNG from '@react-pdf/png-js';
import _JPEG from 'jay-peg';
class PNG {
data;
width;
height;
format;
constructor(data) {
const png = new _PNG(data);
this.data = data;
this.width = png.width;
this.height = png.height;
this.format = 'png';
}
static isValid(data) {
try {
return !!new PNG(data);
}
catch {
return false;
}
}
}
class JPEG {
data;
width;
height;
format;
constructor(data) {
this.data = data;
this.format = 'jpeg';
this.width = 0;
this.height = 0;
if (data.readUInt16BE(0) !== 0xffd8) {
throw new Error('SOI not found in JPEG');
}
const markers = _JPEG.decode(this.data);
let orientation;
for (let i = 0; i < markers.length; i += 1) {
const marker = markers[i];
if (marker.name === 'EXIF' && marker.entries.orientation) {
orientation = marker.entries.orientation;
}
if (marker.name === 'SOF') {
this.width ||= marker.width;
this.height ||= marker.height;
}
}
if (orientation > 4) {
[this.width, this.height] = [this.height, this.width];
}
}
static isValid(data) {
return data && Buffer.isBuffer(data) && data.readUInt16BE(0) === 0xffd8;
}
}
const createCache = ({ limit = 100 } = {}) => {
let cache = {};
let keys = [];
return {
get: (key) => (key ? cache[key] : null),
set: (key, value) => {
keys.push(key);
if (keys.length > limit) {
delete cache[keys.shift()];
}
cache[key] = value;
},
reset: () => {
cache = {};
keys = [];
},
length: () => keys.length,
};
};
const IMAGE_CACHE = createCache({ limit: 30 });
const isBuffer = Buffer.isBuffer;
const isBlob = (src) => {
return typeof Blob !== 'undefined' && src instanceof Blob;
};
const isDataImageSrc = (src) => {
return 'data' in src;
};
const isBase64Src = (imageSrc) => 'uri' in imageSrc &&
/^data:image\/[a-zA-Z]*;base64,[^"]*/g.test(imageSrc.uri);
const getAbsoluteLocalPath = (src) => {
const { protocol, auth, host, port, hostname, path: pathname, } = url.parse(src);
const absolutePath = pathname ? path.resolve(pathname) : undefined;
if ((protocol && protocol !== 'file:') || auth || host || port || hostname) {
return undefined;
}
return absolutePath;
};
const fetchLocalFile = (src) => new Promise((resolve, reject) => {
try {
if (false) ;
const absolutePath = getAbsoluteLocalPath(src.uri);
if (!absolutePath) {
reject(new Error(`Cannot fetch non-local path: ${src}`));
return;
}
fs.readFile(absolutePath, (err, data) => err ? reject(err) : resolve(data));
}
catch (err) {
reject(err);
}
});
const fetchRemoteFile = async (src) => {
const { method = 'GET', headers, body, credentials } = src;
const response = await fetch(src.uri, {
method,
headers,
body,
credentials,
});
const buffer = await response.arrayBuffer();
return Buffer.from(buffer);
};
const isValidFormat = (format) => {
const lower = format.toLowerCase();
return lower === 'jpg' || lower === 'jpeg' || lower === 'png';
};
const guessFormat = (buffer) => {
let format;
if (JPEG.isValid(buffer)) {
format = 'jpg';
}
else if (PNG.isValid(buffer)) {
format = 'png';
}
return format;
};
function getImage(body, format) {
switch (format.toLowerCase()) {
case 'jpg':
case 'jpeg':
return new JPEG(body);
case 'png':
return new PNG(body);
default:
return null;
}
}
const resolveBase64Image = async ({ uri }) => {
const match = /^data:image\/([a-zA-Z]*);base64,([^"]*)/g.exec(uri);
if (!match)
throw new Error(`Invalid base64 image: ${uri}`);
const format = match[1];
const data = match[2];
if (!isValidFormat(format))
throw new Error(`Base64 image invalid format: ${format}`);
return getImage(Buffer.from(data, 'base64'), format);
};
const resolveImageFromData = async (src) => {
if (src.data && src.format) {
return getImage(src.data, src.format);
}
throw new Error(`Invalid data given for local file: ${JSON.stringify(src)}`);
};
const resolveBufferImage = async (buffer) => {
const format = guessFormat(buffer);
if (format) {
return getImage(buffer, format);
}
return null;
};
const resolveBlobImage = async (blob) => {
const { type } = blob;
if (!type || type === 'application/octet-stream') {
const arrayBuffer = await blob.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
return resolveBufferImage(buffer);
}
if (!type.startsWith('image/')) {
throw new Error(`Invalid blob type: ${type}`);
}
const format = type.replace('image/', '');
if (!isValidFormat(format)) {
throw new Error(`Invalid blob type: ${type}`);
}
const buffer = await blob.arrayBuffer();
return getImage(Buffer.from(buffer), format);
};
const getImageFormat = (body) => {
const isPng = body[0] === 137 &&
body[1] === 80 &&
body[2] === 78 &&
body[3] === 71 &&
body[4] === 13 &&
body[5] === 10 &&
body[6] === 26 &&
body[7] === 10;
const isJpg = body[0] === 255 && body[1] === 216 && body[2] === 255;
let extension = '';
if (isPng) {
extension = 'png';
}
else if (isJpg) {
extension = 'jpg';
}
else {
throw new Error('Not valid image extension');
}
return extension;
};
const resolveImageFromUrl = async (src) => {
const data = getAbsoluteLocalPath(src.uri)
? await fetchLocalFile(src)
: await fetchRemoteFile(src);
const format = getImageFormat(data);
return getImage(data, format);
};
const getCacheKey = (src) => {
if (isBlob(src) || isBuffer(src))
return null;
if (isDataImageSrc(src))
return src.data.toString();
return src.uri;
};
const resolveImage = (src, { cache = true } = {}) => {
let image;
const cacheKey = getCacheKey(src);
if (isBlob(src)) {
image = resolveBlobImage(src);
}
else if (isBuffer(src)) {
image = resolveBufferImage(src);
}
else if (cache && IMAGE_CACHE.get(cacheKey)) {
return IMAGE_CACHE.get(cacheKey);
}
else if (isBase64Src(src)) {
image = resolveBase64Image(src);
}
else if (isDataImageSrc(src)) {
image = resolveImageFromData(src);
}
else {
image = resolveImageFromUrl(src);
}
if (!image) {
throw new Error('Cannot resolve image');
}
if (cache && cacheKey) {
IMAGE_CACHE.set(cacheKey, image);
}
return image;
};
export { resolveImage as default };
+32
View File
@@ -0,0 +1,32 @@
{
"name": "@react-pdf/image",
"version": "3.0.3",
"license": "MIT",
"description": "Parses the images in png or jpeg format for react-pdf document",
"author": "Diego Muracciole <diegomuracciole@gmail.com>",
"homepage": "https://github.com/diegomura/react-pdf#readme",
"type": "module",
"main": "./lib/index.js",
"types": "./lib/index.d.ts",
"browser": {
"./lib/index.js": "./lib/index.browser.js"
},
"repository": {
"type": "git",
"url": "https://github.com/diegomura/react-pdf.git",
"directory": "packages/image"
},
"scripts": {
"test": "vitest",
"build": "rimraf ./lib && rollup -c",
"watch": "rimraf ./lib && rollup -c -w",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@react-pdf/png-js": "^3.0.0",
"jay-peg": "^1.1.1"
},
"files": [
"lib"
]
}
+5
View File
@@ -0,0 +1,5 @@
<p align="center">
<img src="https://user-images.githubusercontent.com/5600341/27505816-c8bc37aa-587f-11e7-9a86-08a2d081a8b9.png" height="280px">
</p>
# @react-pdf/layout
+885
View File
@@ -0,0 +1,885 @@
/// <reference path="../globals.d.ts" />
/// <reference types="node" />
import { Style, SafeStyle, Transform } from '@react-pdf/stylesheet';
import { YogaNode } from 'yoga-layout/load';
import * as React from 'react';
import * as P from '@react-pdf/primitives';
import { Image } from '@react-pdf/image';
import { HyphenationCallback } from '@react-pdf/font';
import { Paragraph } from '@react-pdf/textkit';
interface LineProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x1: string | number;
x2: string | number;
y1: string | number;
y2: string | number;
}
interface SafeLineProps extends SafeSVGPresentationAttributes {
style?: SafeSVGPresentationAttributes;
x1: number;
x2: number;
y1: number;
y2: number;
}
type LineNode = {
type: typeof P.Line;
props: LineProps;
style?: Style | Style[];
box?: never;
origin?: never;
yogaNode?: never;
children?: never[];
};
type SafeLineNode = Omit<LineNode, 'style' | 'props'> & {
style: SafeStyle;
props: SafeLineProps;
};
interface PolylineProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
points: string;
}
interface SafePolylineProps extends SafeSVGPresentationAttributes {
style?: SafeSVGPresentationAttributes;
points: string;
}
type PolylineNode = {
type: typeof P.Polyline;
props: PolylineProps;
style?: Style | Style[];
box?: never;
origin?: never;
yogaNode?: never;
children?: never[];
};
type SafePolylineNode = Omit<PolylineNode, 'style' | 'props'> & {
style: SafeStyle;
props: SafePolylineProps;
};
interface PolygonProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
points: string;
}
interface SafePolygonProps extends SafeSVGPresentationAttributes {
style?: SafeSVGPresentationAttributes;
points: string;
}
type PolygonNode = {
type: typeof P.Polygon;
props: PolygonProps;
style?: Style | Style[];
box?: never;
origin?: never;
yogaNode?: never;
children?: never[];
};
type SafePolygonNode = Omit<PolygonNode, 'style' | 'props'> & {
style: SafeStyle;
props: SafePolygonProps;
};
interface PathProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
d: string;
}
interface SafePathProps extends SafeSVGPresentationAttributes {
style?: SafeSVGPresentationAttributes;
d: string;
}
type PathNode = {
type: typeof P.Path;
props: PathProps;
style?: Style | Style[];
box?: never;
origin?: never;
yogaNode?: never;
children?: never[];
};
type SafePathNode = Omit<PathNode, 'style' | 'props'> & {
style: SafeStyle;
props: SafePathProps;
};
interface RectProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x?: string | number;
y?: string | number;
width: string | number;
height: string | number;
rx?: string | number;
ry?: string | number;
}
interface SafeRectProps extends SafeSVGPresentationAttributes {
style?: SafeSVGPresentationAttributes;
x?: number;
y?: number;
width: number;
height: number;
rx?: number;
ry?: number;
}
type RectNode = {
type: typeof P.Rect;
props: RectProps;
style?: Style | Style[];
box?: never;
origin?: never;
yogaNode?: never;
children?: never[];
};
type SafeRectNode = Omit<RectNode, 'style' | 'props'> & {
style: SafeStyle;
props: SafeRectProps;
};
interface CircleProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
cx?: string | number;
cy?: string | number;
r: string | number;
}
interface SafeCircleProps extends SafeSVGPresentationAttributes {
style?: SafeSVGPresentationAttributes;
cx?: number;
cy?: number;
r: number;
}
type CircleNode = {
type: typeof P.Circle;
props: CircleProps;
style?: Style | Style[];
box?: never;
origin?: Origin;
yogaNode?: never;
children?: never[];
};
type SafeCircleNode = Omit<CircleNode, 'style' | 'props'> & {
style: SafeStyle;
props: SafeCircleProps;
};
interface EllipseProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
cx?: string | number;
cy?: string | number;
rx: string | number;
ry: string | number;
}
interface SafeEllipseProps extends SafeSVGPresentationAttributes {
style?: SafeSVGPresentationAttributes;
cx?: number;
cy?: number;
rx: number;
ry: number;
}
type EllipseNode = {
type: typeof P.Ellipse;
props: EllipseProps;
style?: Style | Style[];
box?: never;
origin?: never;
yogaNode?: never;
children?: never[];
};
type SafeEllipseNode = Omit<EllipseNode, 'style' | 'props'> & {
style: SafeStyle;
props: SafeEllipseProps;
};
interface ClipPathProps {
id?: string;
}
type ClipPathNode = {
type: typeof P.ClipPath;
props: ClipPathProps;
style: never;
box?: never;
origin?: never;
yogaNode?: never;
children?: (LineNode | PolylineNode | PolygonNode | PathNode | RectNode | CircleNode | EllipseNode)[];
};
type SafeClipPathNode = Omit<ClipPathNode, 'children'> & {
children?: (SafeLineNode | SafePolylineNode | SafePolygonNode | SafePathNode | SafeRectNode | SafeCircleNode | SafeEllipseNode)[];
};
interface StopProps {
offset: string | number;
stopColor: string;
stopOpacity?: string | number;
}
interface StopSafeProps {
offset: number;
stopColor: string;
stopOpacity?: number;
}
type StopNode = {
type: typeof P.Stop;
props: StopProps;
style?: never;
box?: never;
origin?: never;
yogaNode?: never;
children?: never[];
};
type SafeStopNode = Omit<StopNode, 'props'> & {
props: StopSafeProps;
};
interface LinearGradientProps {
id: string;
x1?: string | number;
x2?: string | number;
y1?: string | number;
y2?: string | number;
xlinkHref?: string;
gradientTransform?: string;
gradientUnits?: 'userSpaceOnUse' | 'objectBoundingBox';
}
interface SafeLinearGradientProps {
id: string;
x1?: number;
x2?: number;
y1?: number;
y2?: number;
xlinkHref?: string;
gradientTransform?: Transform[];
gradientUnits?: 'userSpaceOnUse' | 'objectBoundingBox';
}
type LinearGradientNode = {
type: typeof P.LinearGradient;
props: LinearGradientProps;
style?: never;
box?: never;
origin?: never;
yogaNode?: never;
children?: StopNode[];
};
type SafeLinearGradientNode = Omit<LinearGradientNode, 'props' | 'children'> & {
props: SafeLinearGradientProps;
children?: SafeStopNode[];
};
interface RadialGradientProps {
id: string;
cx?: string | number;
cy?: string | number;
fr?: string | number;
fx?: string | number;
fy?: string | number;
r?: string | number;
xlinkHref?: string;
gradientTransform?: string;
gradientUnits?: 'userSpaceOnUse' | 'objectBoundingBox';
}
interface SafeRadialGradientProps {
id: string;
cx?: number;
cy?: number;
fr?: number;
fx?: number;
fy?: number;
r?: number;
xlinkHref?: string;
gradientTransform?: Transform[];
gradientUnits?: 'userSpaceOnUse' | 'objectBoundingBox';
}
type RadialGradientNode = {
type: typeof P.RadialGradient;
props: RadialGradientProps;
style?: never;
box?: never;
origin?: never;
yogaNode?: never;
children?: StopNode[];
};
type SafeRadialGradientNode = Omit<RadialGradientNode, 'props' | 'children'> & {
props: SafeRadialGradientProps;
children?: SafeStopNode[];
};
type YogaInstance = {
node: {
create: () => YogaNode;
};
};
type Box = {
width: number;
height: number;
top: number;
left: number;
right: number;
bottom: number;
marginTop?: number;
marginRight?: number;
marginBottom?: number;
marginLeft?: number;
paddingTop?: number;
paddingRight?: number;
paddingBottom?: number;
paddingLeft?: number;
borderTopWidth?: number;
borderRightWidth?: number;
borderBottomWidth?: number;
borderLeftWidth?: number;
};
type Origin = {
left: number;
top: number;
};
interface Bookmark {
title: string;
top?: number;
left?: number;
zoom?: number;
fit?: true | false;
expanded?: true | false;
parent?: number;
ref?: number;
}
type DynamicPageProps = {
pageNumber: number;
totalPages?: number;
subPageNumber?: number;
subPageTotalPages?: number;
};
type RenderProp = (props: DynamicPageProps) => React.ReactNode | null | undefined;
type NodeProps = {
id?: string;
/**
* Render component in all wrapped pages.
* @see https://react-pdf.org/advanced#fixed-components
*/
fixed?: boolean;
/**
* Force the wrapping algorithm to start a new page when rendering the
* element.
* @see https://react-pdf.org/advanced#page-breaks
*/
break?: boolean;
/**
* Hint that no page wrapping should occur between all sibling elements following the element within n points
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
minPresenceAhead?: number;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
bookmark?: Bookmark;
};
type FillRule = 'nonzero' | 'evenodd';
type TextAnchor = 'start' | 'middle' | 'end';
type StrokeLinecap = 'butt' | 'round' | 'square';
type StrokeLinejoin = 'butt' | 'round' | 'square' | 'miter' | 'bevel';
type Visibility = 'visible' | 'hidden' | 'collapse';
type DominantBaseline = 'auto' | 'middle' | 'central' | 'hanging' | 'mathematical' | 'text-after-edge' | 'text-before-edge';
type SVGPresentationAttributes = {
fill?: string;
color?: string;
stroke?: string;
transform?: string;
strokeDasharray?: string;
opacity?: string | number;
strokeWidth?: string | number;
fillOpacity?: string | number;
fillRule?: FillRule;
strokeOpacity?: string | number;
textAnchor?: TextAnchor;
strokeLinecap?: StrokeLinecap;
strokeLinejoin?: StrokeLinejoin;
visibility?: Visibility;
clipPath?: string;
dominantBaseline?: DominantBaseline;
};
type SafeSVGPresentationAttributes = {
fill?: string | SafeLinearGradientNode | SafeRadialGradientNode;
color?: string;
stroke?: string;
transform?: Transform[];
strokeDasharray?: string;
opacity?: number;
strokeWidth?: number;
fillOpacity?: number;
fillRule?: FillRule;
strokeOpacity?: number;
textAnchor?: TextAnchor;
strokeLinecap?: StrokeLinecap;
strokeLinejoin?: StrokeLinejoin;
visibility?: Visibility;
clipPath?: SafeClipPathNode;
dominantBaseline?: DominantBaseline;
};
interface FormCommonProps extends NodeProps {
name?: string;
required?: boolean;
noExport?: boolean;
readOnly?: boolean;
value?: number | string;
defaultValue?: number | string;
}
interface CanvasProps extends NodeProps {
paint: (painter: any, availableWidth?: number, availableHeight?: number) => null;
}
type CanvasNode = {
type: typeof P.Canvas;
props: CanvasProps;
style?: Style | Style[];
box?: Box;
origin?: Origin;
yogaNode?: YogaNode;
children?: never[];
};
type SafeCanvasNode = Omit<CanvasNode, 'style'> & {
style: SafeStyle;
};
interface CheckboxProps extends FormCommonProps {
backgroundColor?: string;
borderColor?: string;
checked?: boolean;
onState?: string;
offState?: string;
xMark?: boolean;
}
type CheckboxNode = {
type: typeof P.Checkbox;
props: CheckboxProps;
style?: Style | Style[];
box?: Box;
origin?: Origin;
yogaNode?: YogaNode;
children?: never[];
};
type SafeCheckboxNode = Omit<CheckboxNode, 'style'> & {
style: SafeStyle;
};
type DefsNode = {
type: typeof P.Defs;
props?: never;
style?: never;
box?: never;
origin?: never;
yogaNode?: never;
children?: (ClipPathNode | LinearGradientNode | RadialGradientNode)[];
};
type Defs = Record<string, DefsNode['children'][number]>;
type SafeDefsNode = Omit<DefsNode, 'children'> & {
children?: (SafeClipPathNode | SafeLinearGradientNode | SafeRadialGradientNode)[];
};
type SafeDefs = Record<string, SafeDefsNode['children'][number]>;
type HTTPMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
type SourceURL = string;
type SourceBuffer = Buffer;
type SourceBlob = Blob;
type SourceDataBuffer = {
data: Buffer;
format: 'png' | 'jpg';
};
type SourceURLObject = {
uri: string;
method?: HTTPMethod;
body?: any;
headers?: any;
credentials?: 'omit' | 'same-origin' | 'include';
};
type Source = SourceURL | SourceBuffer | SourceBlob | SourceDataBuffer | SourceURLObject | undefined;
type SourceFactory = () => Source;
type SourceAsync = Promise<Source>;
type SourceAsyncFactory = () => Promise<Source>;
type SourceObject = Source | SourceFactory | SourceAsync | SourceAsyncFactory;
interface BaseImageProps extends NodeProps {
cache?: boolean;
x?: number;
y?: number;
}
interface ImageWithSrcProp extends BaseImageProps {
src: SourceObject;
source?: never;
}
interface ImageWithSourceProp extends BaseImageProps {
source: SourceObject;
src?: never;
}
type ImageProps = ImageWithSrcProp | ImageWithSourceProp;
type ImageNode = {
type: typeof P.Image;
props: ImageProps;
image?: Image;
style?: Style | Style[];
box?: Box;
origin?: Origin;
yogaNode?: YogaNode;
children?: never[];
};
type SafeImageNode = Omit<ImageNode, 'style'> & {
style: SafeStyle;
};
type TextInstanceNode = {
type: typeof P.TextInstance;
props?: never;
style?: never;
box?: never;
origin?: never;
children?: never[];
yogaNode?: never;
value: string;
};
type SafeTextInstanceNode = TextInstanceNode;
interface TspanProps extends SVGPresentationAttributes {
x?: string | number;
y?: string | number;
}
interface SafeTspanProps extends SafeSVGPresentationAttributes {
x?: number;
y?: number;
}
type TspanNode = {
type: typeof P.Tspan;
props: TspanProps;
style?: Style | Style[];
box?: never;
origin?: never;
yogaNode?: never;
lines?: Paragraph;
children?: TextInstanceNode[];
};
type SafeTspanNode = Omit<TspanNode, 'style' | 'props' | 'children'> & {
style: SafeStyle;
props: SafeTspanProps;
children?: SafeTextInstanceNode[];
};
interface TextProps extends NodeProps {
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
render?: RenderProp;
/**
* Override the default hyphenation-callback
* @see https://react-pdf.org/fonts#registerhyphenationcallback
*/
hyphenationCallback?: HyphenationCallback;
/**
* Specifies the minimum number of lines in a text element that must be shown at the bottom of a page or its container.
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
orphans?: number;
/**
* Specifies the minimum number of lines in a text element that must be shown at the top of a page or its container..
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
widows?: number;
x?: number;
y?: number;
}
type TextNode = {
type: typeof P.Text;
props: TextProps;
style?: Style | Style[];
box?: Box;
origin?: Origin;
yogaNode?: YogaNode;
lines?: Paragraph;
alignOffset?: number;
children?: (TextNode | TextInstanceNode | ImageNode | TspanNode)[];
};
type SafeTextNode = Omit<TextNode, 'style' | 'children'> & {
style: SafeStyle;
children?: (SafeTextNode | SafeTextInstanceNode | SafeImageNode | SafeTspanNode)[];
};
interface LinkProps extends NodeProps {
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
href?: string;
src?: string;
render?: RenderProp;
}
type LinkNode = {
type: typeof P.Link;
props: LinkProps;
style?: Style | Style[];
box?: Box;
origin?: Origin;
yogaNode?: YogaNode;
children?: (ViewNode | ImageNode | TextNode | TextInstanceNode)[];
};
type SafeLinkNode = Omit<LinkNode, 'style' | 'children'> & {
style: SafeStyle;
children?: (SafeViewNode | SafeImageNode | SafeTextNode | SafeTextInstanceNode)[];
};
interface TextInputFormatting {
type: 'date' | 'time' | 'percent' | 'number' | 'zip' | 'zipPlus4' | 'phone' | 'ssn';
param?: string;
nDec?: number;
sepComma?: boolean;
negStyle?: 'MinusBlack' | 'Red' | 'ParensBlack' | 'ParensRed';
currency?: string;
currencyPrepend?: boolean;
}
interface TextInputProps extends FormCommonProps {
align?: 'left' | 'center' | 'right';
multiline?: boolean;
/**
* The text will be masked (e.g. with asterisks).
*/
password?: boolean;
/**
* If set, text entered in the field is not spell-checked
*/
noSpell?: boolean;
format?: TextInputFormatting;
/**
* Sets the fontSize (default or 0 means auto sizing)
*/
fontSize?: number;
/**
* Sets the maximum length (characters) of the text in the field
*/
maxLength?: number;
}
type TextInputNode = {
type: typeof P.TextInput;
props: TextInputProps;
style?: Style | Style[];
box?: Box;
origin?: Origin;
yogaNode?: YogaNode;
children?: never[];
};
type SafeTextInputNode = Omit<TextInputNode, 'style'> & {
style: SafeStyle;
};
interface FieldSetProps extends NodeProps {
name: string;
}
type FieldSetNode = {
type: typeof P.FieldSet;
props: FieldSetProps;
style?: Style | Style[];
box?: Box;
origin?: Origin;
yogaNode?: YogaNode;
children?: (TextNode | ViewNode | TextInputNode)[];
};
type SafeFieldSetNode = Omit<FieldSetNode, 'style' | 'children'> & {
style: SafeStyle;
children?: (SafeTextNode | SafeViewNode | SafeTextInputNode)[];
};
interface SelectAndListProps extends FormCommonProps {
sort?: boolean;
edit?: boolean;
multiSelect?: boolean;
noSpell?: boolean;
select?: string[];
}
type SelectNode = {
type: typeof P.Select;
props: SelectAndListProps;
style?: Style | Style[];
box?: Box;
origin?: Origin;
yogaNode?: never;
children?: never[];
};
type SafeSelectNode = Omit<SelectNode, 'style'> & {
style: SafeStyle;
};
type ListNode = {
type: typeof P.List;
props: SelectAndListProps;
style?: Style | Style[];
box?: Box;
origin?: Origin;
yogaNode?: YogaNode;
children?: never[];
};
type SafeListNode = Omit<ListNode, 'style'> & {
style: SafeStyle;
};
type NoteNode = {
type: typeof P.Note;
props: NodeProps;
style?: Style | Style[];
box?: never;
origin?: never;
yogaNode?: never;
children?: TextInstanceNode[];
};
type SafeNoteNode = Omit<NoteNode, 'style' | 'children'> & {
style: SafeStyle;
children?: SafeTextInstanceNode[];
};
interface ViewProps extends NodeProps {
id?: string;
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
render?: RenderProp;
}
type ViewNode = {
type: typeof P.View;
props: ViewProps;
style?: Style | Style[];
box?: Box;
origin?: Origin;
yogaNode?: YogaNode;
children?: (ViewNode | ImageNode | TextNode | LinkNode | CanvasNode | FieldSetNode | TextInputNode | SelectNode | ListNode | CheckboxNode | NoteNode)[];
};
type SafeViewNode = Omit<ViewNode, 'style' | 'children'> & {
style: SafeStyle;
children?: (SafeViewNode | SafeImageNode | SafeTextNode | SafeLinkNode | SafeCanvasNode | SafeFieldSetNode | SafeTextInputNode | SafeSelectNode | SafeListNode | SafeCanvasNode | SafeNoteNode)[];
};
type Orientation = 'portrait' | 'landscape';
type StandardPageSize = '4A0' | '2A0' | 'A0' | 'A1' | 'A2' | 'A3' | 'A4' | 'A5' | 'A6' | 'A7' | 'A8' | 'A9' | 'A10' | 'B0' | 'B1' | 'B2' | 'B3' | 'B4' | 'B5' | 'B6' | 'B7' | 'B8' | 'B9' | 'B10' | 'C0' | 'C1' | 'C2' | 'C3' | 'C4' | 'C5' | 'C6' | 'C7' | 'C8' | 'C9' | 'C10' | 'RA0' | 'RA1' | 'RA2' | 'RA3' | 'RA4' | 'SRA0' | 'SRA1' | 'SRA2' | 'SRA3' | 'SRA4' | 'EXECUTIVE' | 'FOLIO' | 'LEGAL' | 'LETTER' | 'TABLOID' | 'ID1';
type StaticSize = number | string;
type PageSize = number | StandardPageSize | [StaticSize] | [StaticSize, StaticSize] | {
width: StaticSize;
height?: StaticSize;
};
interface PageProps extends NodeProps {
/**
* Enable page wrapping for this page.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
size?: PageSize;
orientation?: Orientation;
dpi?: number;
}
type PageNode = {
type: typeof P.Page;
props: PageProps;
style?: Style | Style[];
box?: Box;
origin?: Origin;
yogaNode?: YogaNode;
children?: (ViewNode | ImageNode | TextNode | LinkNode | CanvasNode | FieldSetNode | TextInputNode | SelectNode | ListNode | CheckboxNode | NoteNode)[];
};
type SafePageNode = Omit<PageNode, 'style' | 'children'> & {
style: SafeStyle;
children?: (SafeViewNode | SafeImageNode | SafeTextNode | SafeLinkNode | SafeCanvasNode | SafeFieldSetNode | SafeTextInputNode | SafeSelectNode | SafeListNode | SafeCheckboxNode | SafeNoteNode)[];
};
type PDFVersion = '1.3' | '1.4' | '1.5' | '1.6' | '1.7' | '1.7ext3';
type PageLayout = 'singlePage' | 'oneColumn' | 'twoColumnLeft' | 'twoColumnRight' | 'twoPageLeft' | 'twoPageRight';
type PageMode = 'useNone' | 'useOutlines' | 'useThumbs' | 'fullScreen' | 'useOC' | 'useAttachments';
interface OnRenderProps {
blob?: Blob;
}
type DocumentProps = {
bookmark?: never;
title?: string;
author?: string;
subject?: string;
creator?: string;
keywords?: string;
producer?: string;
language?: string;
creationDate?: Date;
modificationDate?: Date;
pdfVersion?: PDFVersion;
pageMode?: PageMode;
pageLayout?: PageLayout;
onRender?: (props: OnRenderProps) => any;
};
type DocumentNode = {
type: typeof P.Document;
props: DocumentProps;
box?: never;
origin?: never;
style?: Style | Style[];
yoga?: YogaInstance;
yogaNode?: never;
children: PageNode[];
};
type SafeDocumentNode = Omit<DocumentNode, 'style' | 'children'> & {
style: SafeStyle;
children: SafePageNode[];
};
interface GProps extends SVGPresentationAttributes {
style?: Style | Style[];
}
interface SafeGProps extends SafeSVGPresentationAttributes {
style?: Style;
}
type GNode = {
type: typeof P.G;
props: GProps;
style?: Style | Style[];
box?: never;
origin?: never;
yogaNode?: never;
children?: (LineNode | PolylineNode | PolygonNode | PathNode | RectNode | CircleNode | EllipseNode | ImageNode | TextNode | TspanNode | GNode)[];
};
type SafeGNode = Omit<GNode, 'style' | 'props' | 'children'> & {
style: SafeStyle;
props: SafeGProps;
children?: (SafeLineNode | SafePolylineNode | SafePolygonNode | SafePathNode | SafeRectNode | SafeCircleNode | SafeEllipseNode | SafeImageNode | SafeTextNode | SafeTspanNode | SafeGNode)[];
};
type Viewbox = {
minX: number;
minY: number;
maxX: number;
maxY: number;
};
type PreserveAspectRatio = {
align: 'none' | 'xMinYMin' | 'xMidYMin' | 'xMaxYMin' | 'xMinYMid' | 'xMidYMid' | 'xMaxYMid' | 'xMinYMax' | 'xMidYMax' | 'xMaxYMax';
meetOrSlice: 'meet' | 'slice';
};
interface SvgProps extends NodeProps, SVGPresentationAttributes {
width?: string | number;
height?: string | number;
viewBox?: string | Viewbox;
preserveAspectRatio?: string;
}
interface SvgSafeProps extends NodeProps, SafeSVGPresentationAttributes {
width?: string | number;
height?: string | number;
viewBox?: Viewbox;
preserveAspectRatio?: PreserveAspectRatio;
}
type SvgNode = {
type: typeof P.Svg;
props: SvgProps;
style?: Style | Style[];
box?: Box;
origin?: Origin;
yogaNode?: YogaNode;
children?: (LineNode | PolylineNode | PolygonNode | PathNode | RectNode | CircleNode | EllipseNode | ImageNode | TextNode | TspanNode | GNode | DefsNode)[];
};
type SafeSvgNode = Omit<SvgNode, 'style' | 'props' | 'children'> & {
style: SafeStyle;
props: SvgSafeProps;
children?: (SafeLineNode | SafePolylineNode | SafePolygonNode | SafePathNode | SafeRectNode | SafeCircleNode | SafeEllipseNode | SafeImageNode | SafeTextNode | SafeTspanNode | SafeGNode | SafeDefsNode)[];
};
type Node = DocumentNode | PageNode | ImageNode | SvgNode | CircleNode | ClipPathNode | DefsNode | EllipseNode | GNode | LineNode | LinearGradientNode | PathNode | PolygonNode | PolylineNode | RadialGradientNode | RectNode | StopNode | TspanNode | ViewNode | LinkNode | TextNode | TextInstanceNode | NoteNode | CanvasNode | FieldSetNode | TextInputNode | SelectNode | ListNode | CheckboxNode;
type SafeNode = SafeDocumentNode | SafePageNode | SafeImageNode | SafeSvgNode | SafeCircleNode | SafeClipPathNode | SafeDefsNode | SafeEllipseNode | SafeGNode | SafeLineNode | SafeLinearGradientNode | SafePathNode | SafePolygonNode | SafePolylineNode | SafeRadialGradientNode | SafeRectNode | SafeStopNode | SafeTspanNode | SafeViewNode | SafeLinkNode | SafeTextNode | SafeTextInstanceNode | SafeNoteNode | SafeCanvasNode | SafeFieldSetNode | SafeTextInputNode | SafeSelectNode | SafeListNode | SafeCheckboxNode;
declare const layout: (value: DocumentNode) => Promise<SafeDocumentNode>;
export { type Bookmark, type Box, type CanvasNode, type CheckboxNode, type CircleNode, type ClipPathNode, type Defs, type DefsNode, type DocumentNode, type DocumentProps, type DominantBaseline, type DynamicPageProps, type EllipseNode, type FieldSetNode, type FillRule, type FormCommonProps, type GNode, type ImageNode, type ImageProps, type LineNode, type LinearGradientNode, type LinkNode, type ListNode, type Node, type NodeProps, type NoteNode, type OnRenderProps, type Orientation, type Origin, type PDFVersion, type PageLayout, type PageMode, type PageNode, type PageSize, type PathNode, type PolygonNode, type PolylineNode, type PreserveAspectRatio, type RadialGradientNode, type RectNode, type RenderProp, type SVGPresentationAttributes, type SafeCanvasNode, type SafeCheckboxNode, type SafeCircleNode, type SafeClipPathNode, type SafeDefs, type SafeDefsNode, type SafeDocumentNode, type SafeEllipseNode, type SafeFieldSetNode, type SafeGNode, type SafeImageNode, type SafeLineNode, type SafeLinearGradientNode, type SafeLinkNode, type SafeListNode, type SafeNode, type SafeNoteNode, type SafePageNode, type SafePathNode, type SafePolygonNode, type SafePolylineNode, type SafeRadialGradientNode, type SafeRectNode, type SafeSVGPresentationAttributes, type SafeSelectNode, type SafeStopNode, type SafeSvgNode, type SafeTextInputNode, type SafeTextInstanceNode, type SafeTextNode, type SafeTspanNode, type SafeViewNode, type SelectNode, type SourceObject, type StandardPageSize, type StopNode, type StrokeLinecap, type StrokeLinejoin, type SvgNode, type TextAnchor, type TextInputNode, type TextInstanceNode, type TextNode, type TspanNode, type ViewNode, type Viewbox, type Visibility, type YogaInstance, layout as default };
+2976
View File
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,20 @@
Copyright Mathias Bynens <https://mathiasbynens.be/>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
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.
+107
View File
@@ -0,0 +1,107 @@
# emoji-regex [![Build status](https://github.com/mathiasbynens/emoji-regex/actions/workflows/main.yml/badge.svg)](https://github.com/mathiasbynens/emoji-regex/actions/workflows/main.yml) [![emoji-regex on npm](https://img.shields.io/npm/v/emoji-regex)](https://www.npmjs.com/package/emoji-regex)
_emoji-regex_ offers a regular expression to match all emoji symbols and sequences (including textual representations of emoji) as per the Unicode Standard. Its based on [_emoji-test-regex-pattern_](https://github.com/mathiasbynens/emoji-test-regex-pattern), which generates (at build time) the regular expression pattern based on the Unicode Standard. As a result, _emoji-regex_ can easily be updated whenever new emoji are added to Unicode.
Since each version of _emoji-regex_ is tied to the latest Unicode version at the time of release, results are deterministic. This is important for use cases like image replacement, where you want to guarantee that an image asset is available for every possibly matched emoji. If you dont need a deterministic regex, a lighter-weight, general emoji pattern is available via the [_emoji-regex-xs_](https://github.com/slevithan/emoji-regex-xs) package that follows the same API.
## Installation
Via [npm](https://www.npmjs.com/):
```bash
npm install emoji-regex
```
In [Node.js](https://nodejs.org/):
```js
const emojiRegex = require('emoji-regex');
// Note: because the regular expression has the global flag set, this module
// exports a function that returns the regex rather than exporting the regular
// expression itself, to make it impossible to (accidentally) mutate the
// original regular expression.
const text = `
\u{231A}: ⌚ default emoji presentation character (Emoji_Presentation)
\u{2194}\u{FE0F}: ↔️ default text presentation character rendered as emoji
\u{1F469}: 👩 emoji modifier base (Emoji_Modifier_Base)
\u{1F469}\u{1F3FF}: 👩🏿 emoji modifier base followed by a modifier
`;
const regex = emojiRegex();
for (const match of text.matchAll(regex)) {
const emoji = match[0];
console.log(`Matched sequence ${ emoji } — code points: ${ [...emoji].length }`);
}
```
Console output:
```
Matched sequence ⌚ — code points: 1
Matched sequence ⌚ — code points: 1
Matched sequence ↔️ — code points: 2
Matched sequence ↔️ — code points: 2
Matched sequence 👩 — code points: 1
Matched sequence 👩 — code points: 1
Matched sequence 👩🏿 — code points: 2
Matched sequence 👩🏿 — code points: 2
```
## For maintainers
### How to update emoji-regex after new Unicode Standard releases
1. [Update _emoji-test-regex-pattern_ as described in its repository](https://github.com/mathiasbynens/emoji-test-regex-pattern#how-to-update-emoji-test-regex-pattern-after-new-uts51-releases).
1. Bump the _emoji-test-regex-pattern_ dependency to the latest version.
1. Update the Unicode data dependency in `package.json` by running the following commands:
```sh
# Example: updating from Unicode v13 to Unicode v14.
npm uninstall @unicode/unicode-13.0.0
npm install @unicode/unicode-14.0.0 --save-dev
````
1. Generate the new output:
```sh
npm run build
```
1. Verify that tests still pass:
```sh
npm test
```
### How to publish a new release
1. On the `main` branch, bump the emoji-regex version number in `package.json`:
```sh
npm version patch -m 'Release v%s'
```
Instead of `patch`, use `minor` or `major` [as needed](https://semver.org/).
Note that this produces a Git commit + tag.
1. Push the release commit and tag:
```sh
git push && git push --tags
```
Our CI then automatically publishes the new release to npm.
## Author
| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") |
|---|
| [Mathias Bynens](https://mathiasbynens.be/) |
## License
_emoji-regex_ is available under the [MIT](https://mths.be/mit) license.
+3
View File
@@ -0,0 +1,3 @@
declare module 'emoji-regex' {
export default function emojiRegex(): RegExp;
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+45
View File
@@ -0,0 +1,45 @@
{
"name": "emoji-regex",
"version": "10.4.0",
"description": "A regular expression to match all Emoji-only symbols as per the Unicode Standard.",
"homepage": "https://mths.be/emoji-regex",
"main": "index.js",
"module": "index.mjs",
"types": "index.d.ts",
"keywords": [
"unicode",
"regex",
"regexp",
"regular expressions",
"code points",
"symbols",
"characters",
"emoji"
],
"license": "MIT",
"author": {
"name": "Mathias Bynens",
"url": "https://mathiasbynens.be/"
},
"repository": {
"type": "git",
"url": "https://github.com/mathiasbynens/emoji-regex.git"
},
"bugs": "https://github.com/mathiasbynens/emoji-regex/issues",
"files": [
"LICENSE-MIT.txt",
"index.js",
"index.d.ts",
"index.mjs"
],
"scripts": {
"build": "node script/build.js",
"test": "mocha",
"test:watch": "npm run test -- --watch"
},
"devDependencies": {
"@unicode/unicode-16.0.0": "^1.0.0",
"emoji-test-regex-pattern": "^2.2.0",
"mocha": "^10.7.3"
}
}
+36
View File
@@ -0,0 +1,36 @@
{
"name": "@react-pdf/layout",
"version": "4.4.0",
"license": "MIT",
"description": "Resolve document component's layout",
"author": "Diego Muracciole <diegomuracciole@gmail.com>",
"homepage": "https://github.com/diegomura/react-pdf#readme",
"type": "module",
"main": "./lib/index.js",
"types": "./lib/index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/diegomura/react-pdf.git",
"directory": "packages/layout"
},
"scripts": {
"test": "vitest",
"build": "rimraf ./lib && rollup -c",
"watch": "rimraf ./lib && rollup -c -w",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@react-pdf/fns": "3.1.2",
"@react-pdf/image": "^3.0.3",
"@react-pdf/primitives": "^4.1.1",
"@react-pdf/stylesheet": "^6.1.0",
"@react-pdf/textkit": "^6.0.0",
"@react-pdf/types": "^2.9.0",
"emoji-regex": "^10.3.0",
"queue": "^6.0.1",
"yoga-layout": "^3.2.1"
},
"files": [
"lib"
]
}
+8
View File
@@ -0,0 +1,8 @@
MIT LICENSE
Copyright (c) 2014 Devon Govett
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
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.
+73
View File
@@ -0,0 +1,73 @@
<p align="center">
<img src="https://user-images.githubusercontent.com/5600341/27505816-c8bc37aa-587f-11e7-9a86-08a2d081a8b9.png" height="280px">
</p>
# @react-pdf/pdfkit
A JavaScript PDF generation library for Node and the browser.
## Acknowledges
This project is a fork of [pdfkit](https://github.com/foliojs/pdfkit) by @devongovett and continued under the scope of this project since it has react-pdf specific features. Any recongnition should go to him and the original project mantainers.
## Description
PDFKit is a PDF document generation library for Node and the browser that makes creating complex, multi-page, printable documents easy.
It's written in CoffeeScript, but you can choose to use the API in plain 'ol JavaScript if you like. The API embraces
chainability, and includes both low level functions as well as abstractions for higher level functionality. The PDFKit API
is designed to be simple, so generating complex documents is often as simple as a few function calls.
Check out some of the [documentation and examples](http://pdfkit.org/docs/getting_started.html) to see for yourself!
You can also read the guide as a [self-generated PDF](http://pdfkit.org/docs/guide.pdf) with example output displayed inline.
If you'd like to see how it was generated, check out the README in the [docs](https://github.com/devongovett/pdfkit/tree/master/docs)
folder.
You can also try out an interactive in-browser demo of PDFKit [here](http://pdfkit.org/demo/browser.html).
## Installation
Installation uses the [npm](http://npmjs.org/) package manager. Just type the following command after installing npm.
npm install @react-pdf/pdfkit
## Features
- Vector graphics
- HTML5 canvas-like API
- Path operations
- SVG path parser for easy path creation
- Transformations
- Linear and radial gradients
- Text
- Line wrapping
- Text alignments
- Bulleted lists
- Font embedding
- Supports TrueType (.ttf), OpenType (.otf), WOFF, WOFF2, TrueType Collections (.ttc), and Datafork TrueType (.dfont) fonts
- Font subsetting
- See [fontkit](http://github.com/devongovett/fontkit) for more details on advanced glyph layout support.
- Image embedding
- Supports JPEG and PNG files (including indexed PNGs, and PNGs with transparency)
- Annotations
- Links
- Notes
- Highlights
- Underlines
- etc.
## Coming soon!
- Patterns fills
- Outlines
- PDF Security
- Higher level APIs for creating tables and laying out content
- More performance optimizations
- Even more awesomeness, perhaps written by you! Please fork this repository and send me pull requests.
## Documentation
For complete API documentation and more examples, see the [PDFKit website](http://pdfkit.org/).
## License
PDFKit is available under the MIT license.
File diff suppressed because it is too large Load Diff
+39709
View File
File diff suppressed because it is too large Load Diff
+43
View File
@@ -0,0 +1,43 @@
{
"name": "@react-pdf/pdfkit",
"version": "4.0.3",
"license": "MIT",
"description": "A PDF generation library for Node.js",
"type": "module",
"main": "./lib/pdfkit.js",
"browser": {
"./lib/pdfkit.js": "./lib/pdfkit.browser.js"
},
"repository": {
"type": "git",
"url": "https://github.com/diegomura/react-pdf.git",
"directory": "packages/pdfkit"
},
"author": {
"name": "Devon Govett",
"email": "devongovett@gmail.com",
"url": "http://badassjs.com/"
},
"scripts": {
"clear": "rimraf ./lib ./src/font/data/*.json",
"parse:afm": "node ./src/font/data/compressData.js",
"build": "npm run clear && npm run parse:afm && rollup -c ",
"watch": "npm run clear && npm run parse:afm && rollup -c -w"
},
"files": [
"lib"
],
"dependencies": {
"@babel/runtime": "^7.20.13",
"@react-pdf/png-js": "^3.0.0",
"browserify-zlib": "^0.2.0",
"crypto-js": "^4.2.0",
"fontkit": "^2.0.2",
"jay-peg": "^1.1.1",
"linebreak": "^1.1.0",
"vite-compatible-readable-stream": "^3.6.1"
},
"devDependencies": {
"iconv-lite": "^0.4.13"
}
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017 Devon Govett
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
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.
+50
View File
@@ -0,0 +1,50 @@
<p align="center">
<img src="https://user-images.githubusercontent.com/5600341/27505816-c8bc37aa-587f-11e7-9a86-08a2d081a8b9.png" height="280px">
</p>
# @react-pdf/png-js
A PNG decoder in JS for the canvas element or Node.js.
## Acknowledges
This project is a fork of [png.js](https://github.com/foliojs/png.js) by @devongovett and continued under the scope of this project since it has react-pdf specific features. Any recongnition should go to him and the original project mantainers.
## About this fork
> Updated to 977b857a11676c1e720e79ed8d9178a005a9abd6
- Build node and browser specific bundles
- Uses rollup for build
## Browser Usage
Simply include png.js and zlib.js on your HTML page, create a canvas element, and call PNG.load to load an image.
<canvas></canvas>
<script src="zlib.js"></script>
<script src="png.js"></script>
<script>
var canvas = document.getElementsByTagName('canvas')[0];
PNG.load('some.png', canvas);
</script>
The source code for the browser version resides in `png.js` and also supports loading and displaying animated PNGs.
## Node.js Usage
Install the module using npm
sudo npm install png-js
Require the module and decode a PNG
var PNG = require('png-js');
PNG.decode('some.png', function(pixels) {
// pixels is a 1d array (in rgba order) of decoded pixel data
});
You can also call `PNG.load` if you want to load the PNG (but not decode the pixels) synchronously. If you already
have the PNG data in a buffer, simply use `new PNG(buffer)`. In both of these cases, you need to call `png.decode`
yourself which passes your callback the decoded pixels as a buffer. If you already have a buffer you want the pixels
copied to, call `copyToImageData` with your buffer and the decoded pixels as returned from `decodePixels`.
File diff suppressed because it is too large Load Diff
+339
View File
@@ -0,0 +1,339 @@
import fs from 'fs';
import zlib from 'zlib';
class PNG {
static decode(path, fn) {
{
return fs.readFile(path, (err, file) => {
const png = new PNG(file);
return png.decode(pixels => fn(pixels));
});
}
}
static load(path) {
{
const file = fs.readFileSync(path);
return new PNG(file);
}
}
constructor(data) {
let i;
this.data = data;
this.pos = 8; // Skip the default header
this.palette = [];
this.imgData = [];
this.transparency = {};
this.text = {};
while (true) {
const chunkSize = this.readUInt32();
let section = '';
for (i = 0; i < 4; i++) {
section += String.fromCharCode(this.data[this.pos++]);
}
switch (section) {
case 'IHDR':
// we can grab interesting values from here (like width, height, etc)
this.width = this.readUInt32();
this.height = this.readUInt32();
this.bits = this.data[this.pos++];
this.colorType = this.data[this.pos++];
this.compressionMethod = this.data[this.pos++];
this.filterMethod = this.data[this.pos++];
this.interlaceMethod = this.data[this.pos++];
break;
case 'PLTE':
this.palette = this.read(chunkSize);
break;
case 'IDAT':
for (i = 0; i < chunkSize; i++) {
this.imgData.push(this.data[this.pos++]);
}
break;
case 'tRNS':
// This chunk can only occur once and it must occur after the
// PLTE chunk and before the IDAT chunk.
this.transparency = {};
switch (this.colorType) {
case 3:
// Indexed color, RGB. Each byte in this chunk is an alpha for
// the palette index in the PLTE ("palette") chunk up until the
// last non-opaque entry. Set up an array, stretching over all
// palette entries which will be 0 (opaque) or 1 (transparent).
this.transparency.indexed = this.read(chunkSize);
var short = 255 - this.transparency.indexed.length;
if (short > 0) {
for (i = 0; i < short; i++) {
this.transparency.indexed.push(255);
}
}
break;
case 0:
// Greyscale. Corresponding to entries in the PLTE chunk.
// Grey is two bytes, range 0 .. (2 ^ bit-depth) - 1
this.transparency.grayscale = this.read(chunkSize)[0];
break;
case 2:
// True color with proper alpha channel.
this.transparency.rgb = this.read(chunkSize);
break;
}
break;
case 'tEXt':
var text = this.read(chunkSize);
var index = text.indexOf(0);
var key = String.fromCharCode.apply(String, text.slice(0, index));
this.text[key] = String.fromCharCode.apply(String, text.slice(index + 1));
break;
case 'IEND':
// we've got everything we need!
switch (this.colorType) {
case 0:
case 3:
case 4:
this.colors = 1;
break;
case 2:
case 6:
this.colors = 3;
break;
}
this.hasAlphaChannel = [4, 6].includes(this.colorType);
var colors = this.colors + (this.hasAlphaChannel ? 1 : 0);
this.pixelBitlength = this.bits * colors;
switch (this.colors) {
case 1:
this.colorSpace = 'DeviceGray';
break;
case 3:
this.colorSpace = 'DeviceRGB';
break;
}
this.imgData = Buffer.from(this.imgData);
return;
default:
// unknown (or unimportant) section, skip it
this.pos += chunkSize;
}
this.pos += 4; // Skip the CRC
if (this.pos > this.data.length) {
throw new Error('Incomplete or corrupt PNG file');
}
}
}
read(bytes) {
const result = new Array(bytes);
for (let i = 0; i < bytes; i++) {
result[i] = this.data[this.pos++];
}
return result;
}
readUInt32() {
const b1 = this.data[this.pos++] << 24;
const b2 = this.data[this.pos++] << 16;
const b3 = this.data[this.pos++] << 8;
const b4 = this.data[this.pos++];
return b1 | b2 | b3 | b4;
}
readUInt16() {
const b1 = this.data[this.pos++] << 8;
const b2 = this.data[this.pos++];
return b1 | b2;
}
decodePixels(fn) {
return zlib.inflate(this.imgData, (err, data) => {
if (err) throw err;
var pos = 0;
const {
width,
height
} = this;
var pixelBytes = this.pixelBitlength / 8;
const pixels = Buffer.alloc(width * height * pixelBytes);
function pass(x0, y0, dx, dy, singlePass) {
if (singlePass === void 0) {
singlePass = false;
}
const w = Math.ceil((width - x0) / dx);
const h = Math.ceil((height - y0) / dy);
const scanlineLength = pixelBytes * w;
const buffer = singlePass ? pixels : Buffer.alloc(scanlineLength * h);
let row = 0;
let c = 0;
while (row < h && pos < data.length) {
var byte;
var col;
var i;
var left;
var upper;
switch (data[pos++]) {
case 0:
// None
for (i = 0; i < scanlineLength; i++) {
buffer[c++] = data[pos++];
}
break;
case 1:
// Sub
for (i = 0; i < scanlineLength; i++) {
byte = data[pos++];
left = i < pixelBytes ? 0 : buffer[c - pixelBytes];
buffer[c++] = (byte + left) % 256;
}
break;
case 2:
// Up
for (i = 0; i < scanlineLength; i++) {
byte = data[pos++];
col = (i - i % pixelBytes) / pixelBytes;
upper = row && buffer[(row - 1) * scanlineLength + col * pixelBytes + i % pixelBytes];
buffer[c++] = (upper + byte) % 256;
}
break;
case 3:
// Average
for (i = 0; i < scanlineLength; i++) {
byte = data[pos++];
col = (i - i % pixelBytes) / pixelBytes;
left = i < pixelBytes ? 0 : buffer[c - pixelBytes];
upper = row && buffer[(row - 1) * scanlineLength + col * pixelBytes + i % pixelBytes];
buffer[c++] = (byte + Math.floor((left + upper) / 2)) % 256;
}
break;
case 4:
// Paeth
for (i = 0; i < scanlineLength; i++) {
var paeth;
var upperLeft;
byte = data[pos++];
col = (i - i % pixelBytes) / pixelBytes;
left = i < pixelBytes ? 0 : buffer[c - pixelBytes];
if (row === 0) {
upper = upperLeft = 0;
} else {
upper = buffer[(row - 1) * scanlineLength + col * pixelBytes + i % pixelBytes];
upperLeft = col && buffer[(row - 1) * scanlineLength + (col - 1) * pixelBytes + i % pixelBytes];
}
const p = left + upper - upperLeft;
const pa = Math.abs(p - left);
const pb = Math.abs(p - upper);
const pc = Math.abs(p - upperLeft);
if (pa <= pb && pa <= pc) {
paeth = left;
} else if (pb <= pc) {
paeth = upper;
} else {
paeth = upperLeft;
}
buffer[c++] = (byte + paeth) % 256;
}
break;
default:
throw new Error(`Invalid filter algorithm: ${data[pos - 1]}`);
}
if (!singlePass) {
let pixelsPos = ((y0 + row * dy) * width + x0) * pixelBytes;
let bufferPos = row * scanlineLength;
for (i = 0; i < w; i++) {
for (let j = 0; j < pixelBytes; j++) pixels[pixelsPos++] = buffer[bufferPos++];
pixelsPos += (dx - 1) * pixelBytes;
}
}
row++;
}
}
if (this.interlaceMethod === 1) {
/*
1 6 4 6 2 6 4 6
7 7 7 7 7 7 7 7
5 6 5 6 5 6 5 6
7 7 7 7 7 7 7 7
3 6 4 6 3 6 4 6
7 7 7 7 7 7 7 7
5 6 5 6 5 6 5 6
7 7 7 7 7 7 7 7
*/
pass(0, 0, 8, 8); // 1
pass(4, 0, 8, 8); // 2
pass(0, 4, 4, 8); // 3
pass(2, 0, 4, 4); // 4
pass(0, 2, 2, 4); // 5
pass(1, 0, 2, 2); // 6
pass(0, 1, 1, 2); // 7
} else {
pass(0, 0, 1, 1, true);
}
return fn(pixels);
});
}
decodePalette() {
const {
palette
} = this;
const {
length
} = palette;
const transparency = this.transparency.indexed || [];
const ret = Buffer.alloc(transparency.length + length);
let pos = 0;
let c = 0;
for (let i = 0; i < length; i += 3) {
var left;
ret[pos++] = palette[i];
ret[pos++] = palette[i + 1];
ret[pos++] = palette[i + 2];
ret[pos++] = (left = transparency[c++]) != null ? left : 255;
}
return ret;
}
copyToImageData(imageData, pixels) {
let j;
var k;
let {
colors
} = this;
let palette = null;
let alpha = this.hasAlphaChannel;
if (this.palette.length) {
palette = this._decodedPalette || (this._decodedPalette = this.decodePalette());
colors = 4;
alpha = true;
}
const data = imageData.data || imageData;
const {
length
} = data;
const input = palette || pixels;
let i = j = 0;
if (colors === 1) {
while (i < length) {
k = palette ? pixels[i / 4] * 4 : j;
const v = input[k++];
data[i++] = v;
data[i++] = v;
data[i++] = v;
data[i++] = alpha ? input[k++] : 255;
j = k;
}
} else {
while (i < length) {
k = palette ? pixels[i / 4] * 4 : j;
data[i++] = input[k++];
data[i++] = input[k++];
data[i++] = input[k++];
data[i++] = alpha ? input[k++] : 255;
j = k;
}
}
}
decode(fn) {
const ret = Buffer.alloc(this.width * this.height * 4);
return this.decodePixels(pixels => {
this.copyToImageData(ret, pixels);
return fn(ret);
});
}
}
export { PNG as default };
+31
View File
@@ -0,0 +1,31 @@
{
"name": "@react-pdf/png-js",
"description": "A PNG decoder in JS",
"version": "3.0.0",
"license": "MIT",
"type": "module",
"main": "./lib/png-js.js",
"browser": {
"./lib/png-js.js": "./lib/png-js.browser.js"
},
"repository": {
"type": "git",
"url": "https://github.com/diegomura/react-pdf.git",
"directory": "packages/png-js"
},
"author": {
"name": "Devon Govett",
"email": "devongovett@gmail.com",
"url": "http://badassjs.com/"
},
"scripts": {
"build": "rimraf ./lib && rollup -c",
"watch": "rimraf ./lib && rollup -c -w"
},
"files": [
"lib"
],
"dependencies": {
"browserify-zlib": "^0.2.0"
}
}
+5
View File
@@ -0,0 +1,5 @@
<p align="center">
<img src="https://user-images.githubusercontent.com/5600341/27505816-c8bc37aa-587f-11e7-9a86-08a2d081a8b9.png" height="280px">
</p>
# @react-pdf/primitives
+29
View File
@@ -0,0 +1,29 @@
export declare const G = "G";
export declare const Svg = "SVG";
export declare const View = "VIEW";
export declare const Text = "TEXT";
export declare const Link = "LINK";
export declare const Page = "PAGE";
export declare const Note = "NOTE";
export declare const Path = "PATH";
export declare const Rect = "RECT";
export declare const Line = "LINE";
export declare const FieldSet = "FIELD_SET";
export declare const TextInput = "TEXT_INPUT";
export declare const Select = "SELECT";
export declare const Checkbox = "CHECKBOX";
export declare const List = "LIST";
export declare const Stop = "STOP";
export declare const Defs = "DEFS";
export declare const Image = "IMAGE";
export declare const Tspan = "TSPAN";
export declare const Canvas = "CANVAS";
export declare const Circle = "CIRCLE";
export declare const Ellipse = "ELLIPSE";
export declare const Polygon = "POLYGON";
export declare const Document = "DOCUMENT";
export declare const Polyline = "POLYLINE";
export declare const ClipPath = "CLIP_PATH";
export declare const TextInstance = "TEXT_INSTANCE";
export declare const LinearGradient = "LINEAR_GRADIENT";
export declare const RadialGradient = "RADIAL_GRADIENT";
+31
View File
@@ -0,0 +1,31 @@
const G = 'G';
const Svg = 'SVG';
const View = 'VIEW';
const Text = 'TEXT';
const Link = 'LINK';
const Page = 'PAGE';
const Note = 'NOTE';
const Path = 'PATH';
const Rect = 'RECT';
const Line = 'LINE';
const FieldSet = 'FIELD_SET';
const TextInput = 'TEXT_INPUT';
const Select = 'SELECT';
const Checkbox = 'CHECKBOX';
const List = 'LIST';
const Stop = 'STOP';
const Defs = 'DEFS';
const Image = 'IMAGE';
const Tspan = 'TSPAN';
const Canvas = 'CANVAS';
const Circle = 'CIRCLE';
const Ellipse = 'ELLIPSE';
const Polygon = 'POLYGON';
const Document = 'DOCUMENT';
const Polyline = 'POLYLINE';
const ClipPath = 'CLIP_PATH';
const TextInstance = 'TEXT_INSTANCE';
const LinearGradient = 'LINEAR_GRADIENT';
const RadialGradient = 'RADIAL_GRADIENT';
export { Canvas, Checkbox, Circle, ClipPath, Defs, Document, Ellipse, FieldSet, G, Image, Line, LinearGradient, Link, List, Note, Page, Path, Polygon, Polyline, RadialGradient, Rect, Select, Stop, Svg, Text, TextInput, TextInstance, Tspan, View };
+24
View File
@@ -0,0 +1,24 @@
{
"name": "@react-pdf/primitives",
"version": "4.1.1",
"license": "MIT",
"description": "Define uninitialized elements",
"author": "Diego Muracciole <diegomuracciole@gmail.com>",
"homepage": "https://github.com/diegomura/react-pdf#readme",
"type": "module",
"main": "./lib/index.js",
"types": "./lib/index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/diegomura/react-pdf.git",
"directory": "packages/primitives"
},
"scripts": {
"build": "rimraf ./lib && rollup -c",
"watch": "rimraf ./lib && rollup -c -w",
"test": "vitest"
},
"files": [
"lib"
]
}
+5
View File
@@ -0,0 +1,5 @@
<p align="center">
<img src="https://user-images.githubusercontent.com/5600341/27505816-c8bc37aa-587f-11e7-9a86-08a2d081a8b9.png" height="280px">
</p>
# @react-pdf/reconciler
+20
View File
@@ -0,0 +1,20 @@
interface Reconciler<T> {
createContainer: (container: any) => T;
updateContainer: (element: T, container: T, parentComponent: T, callback?: () => void) => void;
}
type ReconcilerFactory = <I, T>(config: {
appendChild: (parent: I, child: I | T) => void;
appendChildToContainer: (parent: I, child: I | T) => void;
commitTextUpdate: (textInstance: T, oldText: string, newText: string) => void;
commitUpdate: (instance: I, updatePayload: any, type: string, oldProps: any, newProps: any) => void;
createInstance: (type: string, props: any) => I;
createTextInstance: (text: string) => T;
insertBefore: (parent: I, child: I | T, beforeChild: I | T) => void;
removeChild: (parent: I, child: I | T) => void;
removeChildFromContainer: (parent: I, child: I | T) => void;
resetAfterCommit: () => void;
}) => Reconciler<I>;
declare const _default: ReconcilerFactory;
export { _default as default };
+10
View File
@@ -0,0 +1,10 @@
import React from 'react';
import createRendererForReact19 from './reconciler-31.js';
import createRendererForReact18AndLess from './reconciler-23.js';
const isReact19 = React.version.startsWith('19');
var index = isReact19
? createRendererForReact19
: createRendererForReact18AndLess;
export { index as default };
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
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.
+9
View File
@@ -0,0 +1,9 @@
# `scheduler`
This is a package for cooperative scheduling in a browser environment. It is currently used internally by React, but we plan to make it more generic.
The public API for this package is not yet finalized.
### Thanks
The React team thanks [Anton Podviaznikov](https://podviaznikov.com/) for donating the `scheduler` package name.
@@ -0,0 +1,423 @@
/**
* @license React
* scheduler-unstable_mock.development.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
"use strict";
"production" !== process.env.NODE_ENV &&
(function () {
function push(heap, node) {
var index = heap.length;
heap.push(node);
a: for (; 0 < index; ) {
var parentIndex = (index - 1) >>> 1,
parent = heap[parentIndex];
if (0 < compare(parent, node))
(heap[parentIndex] = node),
(heap[index] = parent),
(index = parentIndex);
else break a;
}
}
function peek(heap) {
return 0 === heap.length ? null : heap[0];
}
function pop(heap) {
if (0 === heap.length) return null;
var first = heap[0],
last = heap.pop();
if (last !== first) {
heap[0] = last;
a: for (
var index = 0, length = heap.length, halfLength = length >>> 1;
index < halfLength;
) {
var leftIndex = 2 * (index + 1) - 1,
left = heap[leftIndex],
rightIndex = leftIndex + 1,
right = heap[rightIndex];
if (0 > compare(left, last))
rightIndex < length && 0 > compare(right, left)
? ((heap[index] = right),
(heap[rightIndex] = last),
(index = rightIndex))
: ((heap[index] = left),
(heap[leftIndex] = last),
(index = leftIndex));
else if (rightIndex < length && 0 > compare(right, last))
(heap[index] = right),
(heap[rightIndex] = last),
(index = rightIndex);
else break a;
}
}
return first;
}
function compare(a, b) {
var diff = a.sortIndex - b.sortIndex;
return 0 !== diff ? diff : a.id - b.id;
}
function advanceTimers(currentTime) {
for (var timer = peek(timerQueue); null !== timer; ) {
if (null === timer.callback) pop(timerQueue);
else if (timer.startTime <= currentTime)
pop(timerQueue),
(timer.sortIndex = timer.expirationTime),
push(taskQueue, timer);
else break;
timer = peek(timerQueue);
}
}
function handleTimeout(currentTime) {
isHostTimeoutScheduled = !1;
advanceTimers(currentTime);
if (!isHostCallbackScheduled)
if (null !== peek(taskQueue))
(isHostCallbackScheduled = !0), (scheduledCallback = flushWork);
else {
var firstTimer = peek(timerQueue);
null !== firstTimer &&
((currentTime = firstTimer.startTime - currentTime),
(scheduledTimeout = handleTimeout),
(timeoutTime = currentMockTime + currentTime));
}
}
function flushWork(hasTimeRemaining, initialTime) {
isHostCallbackScheduled = !1;
isHostTimeoutScheduled &&
((isHostTimeoutScheduled = !1),
(scheduledTimeout = null),
(timeoutTime = -1));
isPerformingWork = !0;
var previousPriorityLevel = currentPriorityLevel;
try {
a: {
advanceTimers(initialTime);
for (
currentTask = peek(taskQueue);
null !== currentTask &&
(!(currentTask.expirationTime > initialTime) ||
(hasTimeRemaining && !shouldYieldToHost()));
) {
var callback = currentTask.callback;
if ("function" === typeof callback) {
currentTask.callback = null;
currentPriorityLevel = currentTask.priorityLevel;
var continuationCallback = callback(
currentTask.expirationTime <= initialTime
);
initialTime = currentMockTime;
if ("function" === typeof continuationCallback) {
if (
((currentTask.callback = continuationCallback),
advanceTimers(initialTime),
shouldYieldForPaint)
) {
var JSCompiler_inline_result = (needsPaint = !0);
break a;
}
} else
currentTask === peek(taskQueue) && pop(taskQueue),
advanceTimers(initialTime);
} else pop(taskQueue);
currentTask = peek(taskQueue);
}
if (null !== currentTask) JSCompiler_inline_result = !0;
else {
var firstTimer = peek(timerQueue);
if (null !== firstTimer) {
var ms = firstTimer.startTime - initialTime;
scheduledTimeout = handleTimeout;
timeoutTime = currentMockTime + ms;
}
JSCompiler_inline_result = !1;
}
}
return JSCompiler_inline_result;
} finally {
(currentTask = null),
(currentPriorityLevel = previousPriorityLevel),
(isPerformingWork = !1);
}
}
function shouldYieldToHost() {
return (0 === expectedNumberOfYields && null === yieldedValues) ||
(-1 !== expectedNumberOfYields &&
null !== yieldedValues &&
yieldedValues.length >= expectedNumberOfYields) ||
(shouldYieldForPaint && needsPaint)
? (didStop = !0)
: !1;
}
function unstable_flushAllWithoutAsserting() {
if (isFlushing) throw Error("Already flushing work.");
if (null !== scheduledCallback) {
var cb = scheduledCallback;
isFlushing = !0;
try {
var hasMoreWork = !0;
do hasMoreWork = cb(!0, currentMockTime);
while (hasMoreWork);
hasMoreWork || (scheduledCallback = null);
return !0;
} finally {
isFlushing = !1;
}
} else return !1;
}
var taskQueue = [],
timerQueue = [],
taskIdCounter = 1,
currentTask = null,
currentPriorityLevel = 3,
isPerformingWork = !1,
isHostCallbackScheduled = !1,
isHostTimeoutScheduled = !1,
currentMockTime = 0,
scheduledCallback = null,
scheduledTimeout = null,
timeoutTime = -1,
yieldedValues = null,
expectedNumberOfYields = -1,
didStop = !1,
isFlushing = !1,
needsPaint = !1,
shouldYieldForPaint = !1,
disableYieldValue = !1;
exports.log = function (value) {
"disabledLog" === console.log.name ||
disableYieldValue ||
(null === yieldedValues
? (yieldedValues = [value])
: yieldedValues.push(value));
};
exports.reset = function () {
if (isFlushing) throw Error("Cannot reset while already flushing work.");
currentMockTime = 0;
scheduledTimeout = scheduledCallback = null;
timeoutTime = -1;
yieldedValues = null;
expectedNumberOfYields = -1;
needsPaint = isFlushing = didStop = !1;
};
exports.unstable_IdlePriority = 5;
exports.unstable_ImmediatePriority = 1;
exports.unstable_LowPriority = 4;
exports.unstable_NormalPriority = 3;
exports.unstable_Profiling = null;
exports.unstable_UserBlockingPriority = 2;
exports.unstable_advanceTime = function (ms) {
"disabledLog" === console.log.name ||
disableYieldValue ||
((currentMockTime += ms),
null !== scheduledTimeout &&
timeoutTime <= currentMockTime &&
(scheduledTimeout(currentMockTime),
(timeoutTime = -1),
(scheduledTimeout = null)));
};
exports.unstable_cancelCallback = function (task) {
task.callback = null;
};
exports.unstable_clearLog = function () {
if (null === yieldedValues) return [];
var values = yieldedValues;
yieldedValues = null;
return values;
};
exports.unstable_continueExecution = function () {
isHostCallbackScheduled ||
isPerformingWork ||
((isHostCallbackScheduled = !0), (scheduledCallback = flushWork));
};
exports.unstable_flushAll = function () {
if (null !== yieldedValues)
throw Error(
"Log is not empty. Assert on the log of yielded values before flushing additional work."
);
unstable_flushAllWithoutAsserting();
if (null !== yieldedValues)
throw Error(
"While flushing work, something yielded a value. Use an assertion helper to assert on the log of yielded values, e.g. expect(Scheduler).toFlushAndYield([...])"
);
};
exports.unstable_flushAllWithoutAsserting =
unstable_flushAllWithoutAsserting;
exports.unstable_flushExpired = function () {
if (isFlushing) throw Error("Already flushing work.");
if (null !== scheduledCallback) {
isFlushing = !0;
try {
scheduledCallback(!1, currentMockTime) || (scheduledCallback = null);
} finally {
isFlushing = !1;
}
}
};
exports.unstable_flushNumberOfYields = function (count) {
if (isFlushing) throw Error("Already flushing work.");
if (null !== scheduledCallback) {
var cb = scheduledCallback;
expectedNumberOfYields = count;
isFlushing = !0;
try {
count = !0;
do count = cb(!0, currentMockTime);
while (count && !didStop);
count || (scheduledCallback = null);
} finally {
(expectedNumberOfYields = -1), (isFlushing = didStop = !1);
}
}
};
exports.unstable_flushUntilNextPaint = function () {
if (isFlushing) throw Error("Already flushing work.");
if (null !== scheduledCallback) {
var cb = scheduledCallback;
shouldYieldForPaint = !0;
needsPaint = !1;
isFlushing = !0;
try {
var hasMoreWork = !0;
do hasMoreWork = cb(!0, currentMockTime);
while (hasMoreWork && !didStop);
hasMoreWork || (scheduledCallback = null);
} finally {
isFlushing = didStop = shouldYieldForPaint = !1;
}
}
return !1;
};
exports.unstable_forceFrameRate = function () {};
exports.unstable_getCurrentPriorityLevel = function () {
return currentPriorityLevel;
};
exports.unstable_getFirstCallbackNode = function () {
return peek(taskQueue);
};
exports.unstable_hasPendingWork = function () {
return null !== scheduledCallback;
};
exports.unstable_next = function (eventHandler) {
switch (currentPriorityLevel) {
case 1:
case 2:
case 3:
var priorityLevel = 3;
break;
default:
priorityLevel = currentPriorityLevel;
}
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = priorityLevel;
try {
return eventHandler();
} finally {
currentPriorityLevel = previousPriorityLevel;
}
};
exports.unstable_now = function () {
return currentMockTime;
};
exports.unstable_pauseExecution = function () {};
exports.unstable_requestPaint = function () {
needsPaint = !0;
};
exports.unstable_runWithPriority = function (priorityLevel, eventHandler) {
switch (priorityLevel) {
case 1:
case 2:
case 3:
case 4:
case 5:
break;
default:
priorityLevel = 3;
}
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = priorityLevel;
try {
return eventHandler();
} finally {
currentPriorityLevel = previousPriorityLevel;
}
};
exports.unstable_scheduleCallback = function (
priorityLevel,
callback,
options
) {
var currentTime = currentMockTime;
"object" === typeof options && null !== options
? ((options = options.delay),
(options =
"number" === typeof options && 0 < options
? currentTime + options
: currentTime))
: (options = currentTime);
switch (priorityLevel) {
case 1:
var timeout = -1;
break;
case 2:
timeout = 250;
break;
case 5:
timeout = 1073741823;
break;
case 4:
timeout = 1e4;
break;
default:
timeout = 5e3;
}
timeout = options + timeout;
priorityLevel = {
id: taskIdCounter++,
callback: callback,
priorityLevel: priorityLevel,
startTime: options,
expirationTime: timeout,
sortIndex: -1
};
options > currentTime
? ((priorityLevel.sortIndex = options),
push(timerQueue, priorityLevel),
null === peek(taskQueue) &&
priorityLevel === peek(timerQueue) &&
(isHostTimeoutScheduled
? ((scheduledTimeout = null), (timeoutTime = -1))
: (isHostTimeoutScheduled = !0),
(scheduledTimeout = handleTimeout),
(timeoutTime = currentMockTime + (options - currentTime))))
: ((priorityLevel.sortIndex = timeout),
push(taskQueue, priorityLevel),
isHostCallbackScheduled ||
isPerformingWork ||
((isHostCallbackScheduled = !0), (scheduledCallback = flushWork)));
return priorityLevel;
};
exports.unstable_setDisableYieldValue = function (newValue) {
disableYieldValue = newValue;
};
exports.unstable_shouldYield = shouldYieldToHost;
exports.unstable_wrapCallback = function (callback) {
var parentPriorityLevel = currentPriorityLevel;
return function () {
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = parentPriorityLevel;
try {
return callback.apply(this, arguments);
} finally {
currentPriorityLevel = previousPriorityLevel;
}
};
};
})();
@@ -0,0 +1,415 @@
/**
* @license React
* scheduler-unstable_mock.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
"use strict";
function push(heap, node) {
var index = heap.length;
heap.push(node);
a: for (; 0 < index; ) {
var parentIndex = (index - 1) >>> 1,
parent = heap[parentIndex];
if (0 < compare(parent, node))
(heap[parentIndex] = node), (heap[index] = parent), (index = parentIndex);
else break a;
}
}
function peek(heap) {
return 0 === heap.length ? null : heap[0];
}
function pop(heap) {
if (0 === heap.length) return null;
var first = heap[0],
last = heap.pop();
if (last !== first) {
heap[0] = last;
a: for (
var index = 0, length = heap.length, halfLength = length >>> 1;
index < halfLength;
) {
var leftIndex = 2 * (index + 1) - 1,
left = heap[leftIndex],
rightIndex = leftIndex + 1,
right = heap[rightIndex];
if (0 > compare(left, last))
rightIndex < length && 0 > compare(right, left)
? ((heap[index] = right),
(heap[rightIndex] = last),
(index = rightIndex))
: ((heap[index] = left),
(heap[leftIndex] = last),
(index = leftIndex));
else if (rightIndex < length && 0 > compare(right, last))
(heap[index] = right), (heap[rightIndex] = last), (index = rightIndex);
else break a;
}
}
return first;
}
function compare(a, b) {
var diff = a.sortIndex - b.sortIndex;
return 0 !== diff ? diff : a.id - b.id;
}
var taskQueue = [],
timerQueue = [],
taskIdCounter = 1,
currentTask = null,
currentPriorityLevel = 3,
isPerformingWork = !1,
isHostCallbackScheduled = !1,
isHostTimeoutScheduled = !1,
currentMockTime = 0,
scheduledCallback = null,
scheduledTimeout = null,
timeoutTime = -1,
yieldedValues = null,
expectedNumberOfYields = -1,
didStop = !1,
isFlushing = !1,
needsPaint = !1,
shouldYieldForPaint = !1,
disableYieldValue = !1;
function advanceTimers(currentTime) {
for (var timer = peek(timerQueue); null !== timer; ) {
if (null === timer.callback) pop(timerQueue);
else if (timer.startTime <= currentTime)
pop(timerQueue),
(timer.sortIndex = timer.expirationTime),
push(taskQueue, timer);
else break;
timer = peek(timerQueue);
}
}
function handleTimeout(currentTime) {
isHostTimeoutScheduled = !1;
advanceTimers(currentTime);
if (!isHostCallbackScheduled)
if (null !== peek(taskQueue))
(isHostCallbackScheduled = !0), (scheduledCallback = flushWork);
else {
var firstTimer = peek(timerQueue);
null !== firstTimer &&
((currentTime = firstTimer.startTime - currentTime),
(scheduledTimeout = handleTimeout),
(timeoutTime = currentMockTime + currentTime));
}
}
function flushWork(hasTimeRemaining, initialTime) {
isHostCallbackScheduled = !1;
isHostTimeoutScheduled &&
((isHostTimeoutScheduled = !1),
(scheduledTimeout = null),
(timeoutTime = -1));
isPerformingWork = !0;
var previousPriorityLevel = currentPriorityLevel;
try {
a: {
advanceTimers(initialTime);
for (
currentTask = peek(taskQueue);
null !== currentTask &&
(!(currentTask.expirationTime > initialTime) ||
(hasTimeRemaining && !shouldYieldToHost()));
) {
var callback = currentTask.callback;
if ("function" === typeof callback) {
currentTask.callback = null;
currentPriorityLevel = currentTask.priorityLevel;
var continuationCallback = callback(
currentTask.expirationTime <= initialTime
);
initialTime = currentMockTime;
if ("function" === typeof continuationCallback) {
if (
((currentTask.callback = continuationCallback),
advanceTimers(initialTime),
shouldYieldForPaint)
) {
var JSCompiler_inline_result = (needsPaint = !0);
break a;
}
} else
currentTask === peek(taskQueue) && pop(taskQueue),
advanceTimers(initialTime);
} else pop(taskQueue);
currentTask = peek(taskQueue);
}
if (null !== currentTask) JSCompiler_inline_result = !0;
else {
var firstTimer = peek(timerQueue);
if (null !== firstTimer) {
var ms = firstTimer.startTime - initialTime;
scheduledTimeout = handleTimeout;
timeoutTime = currentMockTime + ms;
}
JSCompiler_inline_result = !1;
}
}
return JSCompiler_inline_result;
} finally {
(currentTask = null),
(currentPriorityLevel = previousPriorityLevel),
(isPerformingWork = !1);
}
}
function shouldYieldToHost() {
return (0 === expectedNumberOfYields && null === yieldedValues) ||
(-1 !== expectedNumberOfYields &&
null !== yieldedValues &&
yieldedValues.length >= expectedNumberOfYields) ||
(shouldYieldForPaint && needsPaint)
? (didStop = !0)
: !1;
}
function unstable_flushAllWithoutAsserting() {
if (isFlushing) throw Error("Already flushing work.");
if (null !== scheduledCallback) {
var cb = scheduledCallback;
isFlushing = !0;
try {
var hasMoreWork = !0;
do hasMoreWork = cb(!0, currentMockTime);
while (hasMoreWork);
hasMoreWork || (scheduledCallback = null);
return !0;
} finally {
isFlushing = !1;
}
} else return !1;
}
exports.log = function (value) {
"disabledLog" === console.log.name ||
disableYieldValue ||
(null === yieldedValues
? (yieldedValues = [value])
: yieldedValues.push(value));
};
exports.reset = function () {
if (isFlushing) throw Error("Cannot reset while already flushing work.");
currentMockTime = 0;
scheduledTimeout = scheduledCallback = null;
timeoutTime = -1;
yieldedValues = null;
expectedNumberOfYields = -1;
needsPaint = isFlushing = didStop = !1;
};
exports.unstable_IdlePriority = 5;
exports.unstable_ImmediatePriority = 1;
exports.unstable_LowPriority = 4;
exports.unstable_NormalPriority = 3;
exports.unstable_Profiling = null;
exports.unstable_UserBlockingPriority = 2;
exports.unstable_advanceTime = function (ms) {
"disabledLog" === console.log.name ||
disableYieldValue ||
((currentMockTime += ms),
null !== scheduledTimeout &&
timeoutTime <= currentMockTime &&
(scheduledTimeout(currentMockTime),
(timeoutTime = -1),
(scheduledTimeout = null)));
};
exports.unstable_cancelCallback = function (task) {
task.callback = null;
};
exports.unstable_clearLog = function () {
if (null === yieldedValues) return [];
var values = yieldedValues;
yieldedValues = null;
return values;
};
exports.unstable_continueExecution = function () {
isHostCallbackScheduled ||
isPerformingWork ||
((isHostCallbackScheduled = !0), (scheduledCallback = flushWork));
};
exports.unstable_flushAll = function () {
if (null !== yieldedValues)
throw Error(
"Log is not empty. Assert on the log of yielded values before flushing additional work."
);
unstable_flushAllWithoutAsserting();
if (null !== yieldedValues)
throw Error(
"While flushing work, something yielded a value. Use an assertion helper to assert on the log of yielded values, e.g. expect(Scheduler).toFlushAndYield([...])"
);
};
exports.unstable_flushAllWithoutAsserting = unstable_flushAllWithoutAsserting;
exports.unstable_flushExpired = function () {
if (isFlushing) throw Error("Already flushing work.");
if (null !== scheduledCallback) {
isFlushing = !0;
try {
scheduledCallback(!1, currentMockTime) || (scheduledCallback = null);
} finally {
isFlushing = !1;
}
}
};
exports.unstable_flushNumberOfYields = function (count) {
if (isFlushing) throw Error("Already flushing work.");
if (null !== scheduledCallback) {
var cb = scheduledCallback;
expectedNumberOfYields = count;
isFlushing = !0;
try {
count = !0;
do count = cb(!0, currentMockTime);
while (count && !didStop);
count || (scheduledCallback = null);
} finally {
(expectedNumberOfYields = -1), (isFlushing = didStop = !1);
}
}
};
exports.unstable_flushUntilNextPaint = function () {
if (isFlushing) throw Error("Already flushing work.");
if (null !== scheduledCallback) {
var cb = scheduledCallback;
shouldYieldForPaint = !0;
needsPaint = !1;
isFlushing = !0;
try {
var hasMoreWork = !0;
do hasMoreWork = cb(!0, currentMockTime);
while (hasMoreWork && !didStop);
hasMoreWork || (scheduledCallback = null);
} finally {
isFlushing = didStop = shouldYieldForPaint = !1;
}
}
return !1;
};
exports.unstable_forceFrameRate = function () {};
exports.unstable_getCurrentPriorityLevel = function () {
return currentPriorityLevel;
};
exports.unstable_getFirstCallbackNode = function () {
return peek(taskQueue);
};
exports.unstable_hasPendingWork = function () {
return null !== scheduledCallback;
};
exports.unstable_next = function (eventHandler) {
switch (currentPriorityLevel) {
case 1:
case 2:
case 3:
var priorityLevel = 3;
break;
default:
priorityLevel = currentPriorityLevel;
}
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = priorityLevel;
try {
return eventHandler();
} finally {
currentPriorityLevel = previousPriorityLevel;
}
};
exports.unstable_now = function () {
return currentMockTime;
};
exports.unstable_pauseExecution = function () {};
exports.unstable_requestPaint = function () {
needsPaint = !0;
};
exports.unstable_runWithPriority = function (priorityLevel, eventHandler) {
switch (priorityLevel) {
case 1:
case 2:
case 3:
case 4:
case 5:
break;
default:
priorityLevel = 3;
}
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = priorityLevel;
try {
return eventHandler();
} finally {
currentPriorityLevel = previousPriorityLevel;
}
};
exports.unstable_scheduleCallback = function (
priorityLevel,
callback,
options
) {
var currentTime = currentMockTime;
"object" === typeof options && null !== options
? ((options = options.delay),
(options =
"number" === typeof options && 0 < options
? currentTime + options
: currentTime))
: (options = currentTime);
switch (priorityLevel) {
case 1:
var timeout = -1;
break;
case 2:
timeout = 250;
break;
case 5:
timeout = 1073741823;
break;
case 4:
timeout = 1e4;
break;
default:
timeout = 5e3;
}
timeout = options + timeout;
priorityLevel = {
id: taskIdCounter++,
callback: callback,
priorityLevel: priorityLevel,
startTime: options,
expirationTime: timeout,
sortIndex: -1
};
options > currentTime
? ((priorityLevel.sortIndex = options),
push(timerQueue, priorityLevel),
null === peek(taskQueue) &&
priorityLevel === peek(timerQueue) &&
(isHostTimeoutScheduled
? ((scheduledTimeout = null), (timeoutTime = -1))
: (isHostTimeoutScheduled = !0),
(scheduledTimeout = handleTimeout),
(timeoutTime = currentMockTime + (options - currentTime))))
: ((priorityLevel.sortIndex = timeout),
push(taskQueue, priorityLevel),
isHostCallbackScheduled ||
isPerformingWork ||
((isHostCallbackScheduled = !0), (scheduledCallback = flushWork)));
return priorityLevel;
};
exports.unstable_setDisableYieldValue = function (newValue) {
disableYieldValue = newValue;
};
exports.unstable_shouldYield = shouldYieldToHost;
exports.unstable_wrapCallback = function (callback) {
var parentPriorityLevel = currentPriorityLevel;
return function () {
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = parentPriorityLevel;
try {
return callback.apply(this, arguments);
} finally {
currentPriorityLevel = previousPriorityLevel;
}
};
};
@@ -0,0 +1,155 @@
/**
* @license React
* scheduler-unstable_post_task.development.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
"use strict";
"production" !== process.env.NODE_ENV &&
(function () {
function runTask(priorityLevel, postTaskPriority, node, callback) {
deadline = getCurrentTime() + 5;
try {
currentPriorityLevel_DEPRECATED = priorityLevel;
var result = callback(!1);
if ("function" === typeof result) {
var continuationOptions = { signal: node._controller.signal },
nextTask = runTask.bind(
null,
priorityLevel,
postTaskPriority,
node,
result
);
void 0 !== scheduler.yield
? scheduler
.yield(continuationOptions)
.then(nextTask)
.catch(handleAbortError)
: scheduler
.postTask(nextTask, continuationOptions)
.catch(handleAbortError);
}
} catch (error) {
setTimeout(function () {
throw error;
});
} finally {
currentPriorityLevel_DEPRECATED = 3;
}
}
function handleAbortError() {}
var perf = window.performance,
setTimeout = window.setTimeout,
scheduler = global.scheduler,
getCurrentTime = perf.now.bind(perf),
deadline = 0,
currentPriorityLevel_DEPRECATED = 3;
exports.unstable_IdlePriority = 5;
exports.unstable_ImmediatePriority = 1;
exports.unstable_LowPriority = 4;
exports.unstable_NormalPriority = 3;
exports.unstable_Profiling = null;
exports.unstable_UserBlockingPriority = 2;
exports.unstable_cancelCallback = function (node) {
node._controller.abort();
};
exports.unstable_continueExecution = function () {};
exports.unstable_forceFrameRate = function () {};
exports.unstable_getCurrentPriorityLevel = function () {
return currentPriorityLevel_DEPRECATED;
};
exports.unstable_getFirstCallbackNode = function () {
return null;
};
exports.unstable_next = function (callback) {
switch (currentPriorityLevel_DEPRECATED) {
case 1:
case 2:
case 3:
var priorityLevel = 3;
break;
default:
priorityLevel = currentPriorityLevel_DEPRECATED;
}
var previousPriorityLevel = currentPriorityLevel_DEPRECATED;
currentPriorityLevel_DEPRECATED = priorityLevel;
try {
return callback();
} finally {
currentPriorityLevel_DEPRECATED = previousPriorityLevel;
}
};
exports.unstable_now = getCurrentTime;
exports.unstable_pauseExecution = function () {};
exports.unstable_requestPaint = function () {};
exports.unstable_runWithPriority = function (priorityLevel, callback) {
var previousPriorityLevel = currentPriorityLevel_DEPRECATED;
currentPriorityLevel_DEPRECATED = priorityLevel;
try {
return callback();
} finally {
currentPriorityLevel_DEPRECATED = previousPriorityLevel;
}
};
exports.unstable_scheduleCallback = function (
priorityLevel,
callback,
options
) {
switch (priorityLevel) {
case 1:
case 2:
var postTaskPriority = "user-blocking";
break;
case 4:
case 3:
postTaskPriority = "user-visible";
break;
case 5:
postTaskPriority = "background";
break;
default:
postTaskPriority = "user-visible";
}
var controller = new TaskController({ priority: postTaskPriority });
options = {
delay:
"object" === typeof options && null !== options ? options.delay : 0,
signal: controller.signal
};
controller = { _controller: controller };
scheduler
.postTask(
runTask.bind(
null,
priorityLevel,
postTaskPriority,
controller,
callback
),
options
)
.catch(handleAbortError);
return controller;
};
exports.unstable_shouldYield = function () {
return getCurrentTime() >= deadline;
};
exports.unstable_wrapCallback = function (callback) {
var parentPriorityLevel = currentPriorityLevel_DEPRECATED;
return function () {
var previousPriorityLevel = currentPriorityLevel_DEPRECATED;
currentPriorityLevel_DEPRECATED = parentPriorityLevel;
try {
return callback();
} finally {
currentPriorityLevel_DEPRECATED = previousPriorityLevel;
}
};
};
})();
@@ -0,0 +1,145 @@
/**
* @license React
* scheduler-unstable_post_task.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
"use strict";
var perf = window.performance,
setTimeout = window.setTimeout,
scheduler = global.scheduler,
getCurrentTime = perf.now.bind(perf),
deadline = 0,
currentPriorityLevel_DEPRECATED = 3;
function runTask(priorityLevel, postTaskPriority, node, callback) {
deadline = getCurrentTime() + 5;
try {
currentPriorityLevel_DEPRECATED = priorityLevel;
var result = callback(!1);
if ("function" === typeof result) {
var continuationOptions = { signal: node._controller.signal },
nextTask = runTask.bind(
null,
priorityLevel,
postTaskPriority,
node,
result
);
void 0 !== scheduler.yield
? scheduler
.yield(continuationOptions)
.then(nextTask)
.catch(handleAbortError)
: scheduler
.postTask(nextTask, continuationOptions)
.catch(handleAbortError);
}
} catch (error) {
setTimeout(function () {
throw error;
});
} finally {
currentPriorityLevel_DEPRECATED = 3;
}
}
function handleAbortError() {}
exports.unstable_IdlePriority = 5;
exports.unstable_ImmediatePriority = 1;
exports.unstable_LowPriority = 4;
exports.unstable_NormalPriority = 3;
exports.unstable_Profiling = null;
exports.unstable_UserBlockingPriority = 2;
exports.unstable_cancelCallback = function (node) {
node._controller.abort();
};
exports.unstable_continueExecution = function () {};
exports.unstable_forceFrameRate = function () {};
exports.unstable_getCurrentPriorityLevel = function () {
return currentPriorityLevel_DEPRECATED;
};
exports.unstable_getFirstCallbackNode = function () {
return null;
};
exports.unstable_next = function (callback) {
switch (currentPriorityLevel_DEPRECATED) {
case 1:
case 2:
case 3:
var priorityLevel = 3;
break;
default:
priorityLevel = currentPriorityLevel_DEPRECATED;
}
var previousPriorityLevel = currentPriorityLevel_DEPRECATED;
currentPriorityLevel_DEPRECATED = priorityLevel;
try {
return callback();
} finally {
currentPriorityLevel_DEPRECATED = previousPriorityLevel;
}
};
exports.unstable_now = getCurrentTime;
exports.unstable_pauseExecution = function () {};
exports.unstable_requestPaint = function () {};
exports.unstable_runWithPriority = function (priorityLevel, callback) {
var previousPriorityLevel = currentPriorityLevel_DEPRECATED;
currentPriorityLevel_DEPRECATED = priorityLevel;
try {
return callback();
} finally {
currentPriorityLevel_DEPRECATED = previousPriorityLevel;
}
};
exports.unstable_scheduleCallback = function (
priorityLevel,
callback,
options
) {
switch (priorityLevel) {
case 1:
case 2:
var postTaskPriority = "user-blocking";
break;
case 4:
case 3:
postTaskPriority = "user-visible";
break;
case 5:
postTaskPriority = "background";
break;
default:
postTaskPriority = "user-visible";
}
var controller = new TaskController({ priority: postTaskPriority });
options = {
delay: "object" === typeof options && null !== options ? options.delay : 0,
signal: controller.signal
};
controller = { _controller: controller };
scheduler
.postTask(
runTask.bind(null, priorityLevel, postTaskPriority, controller, callback),
options
)
.catch(handleAbortError);
return controller;
};
exports.unstable_shouldYield = function () {
return getCurrentTime() >= deadline;
};
exports.unstable_wrapCallback = function (callback) {
var parentPriorityLevel = currentPriorityLevel_DEPRECATED;
return function () {
var previousPriorityLevel = currentPriorityLevel_DEPRECATED;
currentPriorityLevel_DEPRECATED = parentPriorityLevel;
try {
return callback();
} finally {
currentPriorityLevel_DEPRECATED = previousPriorityLevel;
}
};
};
@@ -0,0 +1,364 @@
/**
* @license React
* scheduler.development.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
"use strict";
"production" !== process.env.NODE_ENV &&
(function () {
function performWorkUntilDeadline() {
if (isMessageLoopRunning) {
var currentTime = exports.unstable_now();
startTime = currentTime;
var hasMoreWork = !0;
try {
a: {
isHostCallbackScheduled = !1;
isHostTimeoutScheduled &&
((isHostTimeoutScheduled = !1),
localClearTimeout(taskTimeoutID),
(taskTimeoutID = -1));
isPerformingWork = !0;
var previousPriorityLevel = currentPriorityLevel;
try {
b: {
advanceTimers(currentTime);
for (
currentTask = peek(taskQueue);
null !== currentTask &&
!(
currentTask.expirationTime > currentTime &&
shouldYieldToHost()
);
) {
var callback = currentTask.callback;
if ("function" === typeof callback) {
currentTask.callback = null;
currentPriorityLevel = currentTask.priorityLevel;
var continuationCallback = callback(
currentTask.expirationTime <= currentTime
);
currentTime = exports.unstable_now();
if ("function" === typeof continuationCallback) {
currentTask.callback = continuationCallback;
advanceTimers(currentTime);
hasMoreWork = !0;
break b;
}
currentTask === peek(taskQueue) && pop(taskQueue);
advanceTimers(currentTime);
} else pop(taskQueue);
currentTask = peek(taskQueue);
}
if (null !== currentTask) hasMoreWork = !0;
else {
var firstTimer = peek(timerQueue);
null !== firstTimer &&
requestHostTimeout(
handleTimeout,
firstTimer.startTime - currentTime
);
hasMoreWork = !1;
}
}
break a;
} finally {
(currentTask = null),
(currentPriorityLevel = previousPriorityLevel),
(isPerformingWork = !1);
}
hasMoreWork = void 0;
}
} finally {
hasMoreWork
? schedulePerformWorkUntilDeadline()
: (isMessageLoopRunning = !1);
}
}
}
function push(heap, node) {
var index = heap.length;
heap.push(node);
a: for (; 0 < index; ) {
var parentIndex = (index - 1) >>> 1,
parent = heap[parentIndex];
if (0 < compare(parent, node))
(heap[parentIndex] = node),
(heap[index] = parent),
(index = parentIndex);
else break a;
}
}
function peek(heap) {
return 0 === heap.length ? null : heap[0];
}
function pop(heap) {
if (0 === heap.length) return null;
var first = heap[0],
last = heap.pop();
if (last !== first) {
heap[0] = last;
a: for (
var index = 0, length = heap.length, halfLength = length >>> 1;
index < halfLength;
) {
var leftIndex = 2 * (index + 1) - 1,
left = heap[leftIndex],
rightIndex = leftIndex + 1,
right = heap[rightIndex];
if (0 > compare(left, last))
rightIndex < length && 0 > compare(right, left)
? ((heap[index] = right),
(heap[rightIndex] = last),
(index = rightIndex))
: ((heap[index] = left),
(heap[leftIndex] = last),
(index = leftIndex));
else if (rightIndex < length && 0 > compare(right, last))
(heap[index] = right),
(heap[rightIndex] = last),
(index = rightIndex);
else break a;
}
}
return first;
}
function compare(a, b) {
var diff = a.sortIndex - b.sortIndex;
return 0 !== diff ? diff : a.id - b.id;
}
function advanceTimers(currentTime) {
for (var timer = peek(timerQueue); null !== timer; ) {
if (null === timer.callback) pop(timerQueue);
else if (timer.startTime <= currentTime)
pop(timerQueue),
(timer.sortIndex = timer.expirationTime),
push(taskQueue, timer);
else break;
timer = peek(timerQueue);
}
}
function handleTimeout(currentTime) {
isHostTimeoutScheduled = !1;
advanceTimers(currentTime);
if (!isHostCallbackScheduled)
if (null !== peek(taskQueue))
(isHostCallbackScheduled = !0), requestHostCallback();
else {
var firstTimer = peek(timerQueue);
null !== firstTimer &&
requestHostTimeout(
handleTimeout,
firstTimer.startTime - currentTime
);
}
}
function shouldYieldToHost() {
return exports.unstable_now() - startTime < frameInterval ? !1 : !0;
}
function requestHostCallback() {
isMessageLoopRunning ||
((isMessageLoopRunning = !0), schedulePerformWorkUntilDeadline());
}
function requestHostTimeout(callback, ms) {
taskTimeoutID = localSetTimeout(function () {
callback(exports.unstable_now());
}, ms);
}
"undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&
"function" ===
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart &&
__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
exports.unstable_now = void 0;
if (
"object" === typeof performance &&
"function" === typeof performance.now
) {
var localPerformance = performance;
exports.unstable_now = function () {
return localPerformance.now();
};
} else {
var localDate = Date,
initialTime = localDate.now();
exports.unstable_now = function () {
return localDate.now() - initialTime;
};
}
var taskQueue = [],
timerQueue = [],
taskIdCounter = 1,
currentTask = null,
currentPriorityLevel = 3,
isPerformingWork = !1,
isHostCallbackScheduled = !1,
isHostTimeoutScheduled = !1,
localSetTimeout = "function" === typeof setTimeout ? setTimeout : null,
localClearTimeout =
"function" === typeof clearTimeout ? clearTimeout : null,
localSetImmediate =
"undefined" !== typeof setImmediate ? setImmediate : null,
isMessageLoopRunning = !1,
taskTimeoutID = -1,
frameInterval = 5,
startTime = -1;
if ("function" === typeof localSetImmediate)
var schedulePerformWorkUntilDeadline = function () {
localSetImmediate(performWorkUntilDeadline);
};
else if ("undefined" !== typeof MessageChannel) {
var channel = new MessageChannel(),
port = channel.port2;
channel.port1.onmessage = performWorkUntilDeadline;
schedulePerformWorkUntilDeadline = function () {
port.postMessage(null);
};
} else
schedulePerformWorkUntilDeadline = function () {
localSetTimeout(performWorkUntilDeadline, 0);
};
exports.unstable_IdlePriority = 5;
exports.unstable_ImmediatePriority = 1;
exports.unstable_LowPriority = 4;
exports.unstable_NormalPriority = 3;
exports.unstable_Profiling = null;
exports.unstable_UserBlockingPriority = 2;
exports.unstable_cancelCallback = function (task) {
task.callback = null;
};
exports.unstable_continueExecution = function () {
isHostCallbackScheduled ||
isPerformingWork ||
((isHostCallbackScheduled = !0), requestHostCallback());
};
exports.unstable_forceFrameRate = function (fps) {
0 > fps || 125 < fps
? console.error(
"forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"
)
: (frameInterval = 0 < fps ? Math.floor(1e3 / fps) : 5);
};
exports.unstable_getCurrentPriorityLevel = function () {
return currentPriorityLevel;
};
exports.unstable_getFirstCallbackNode = function () {
return peek(taskQueue);
};
exports.unstable_next = function (eventHandler) {
switch (currentPriorityLevel) {
case 1:
case 2:
case 3:
var priorityLevel = 3;
break;
default:
priorityLevel = currentPriorityLevel;
}
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = priorityLevel;
try {
return eventHandler();
} finally {
currentPriorityLevel = previousPriorityLevel;
}
};
exports.unstable_pauseExecution = function () {};
exports.unstable_requestPaint = function () {};
exports.unstable_runWithPriority = function (priorityLevel, eventHandler) {
switch (priorityLevel) {
case 1:
case 2:
case 3:
case 4:
case 5:
break;
default:
priorityLevel = 3;
}
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = priorityLevel;
try {
return eventHandler();
} finally {
currentPriorityLevel = previousPriorityLevel;
}
};
exports.unstable_scheduleCallback = function (
priorityLevel,
callback,
options
) {
var currentTime = exports.unstable_now();
"object" === typeof options && null !== options
? ((options = options.delay),
(options =
"number" === typeof options && 0 < options
? currentTime + options
: currentTime))
: (options = currentTime);
switch (priorityLevel) {
case 1:
var timeout = -1;
break;
case 2:
timeout = 250;
break;
case 5:
timeout = 1073741823;
break;
case 4:
timeout = 1e4;
break;
default:
timeout = 5e3;
}
timeout = options + timeout;
priorityLevel = {
id: taskIdCounter++,
callback: callback,
priorityLevel: priorityLevel,
startTime: options,
expirationTime: timeout,
sortIndex: -1
};
options > currentTime
? ((priorityLevel.sortIndex = options),
push(timerQueue, priorityLevel),
null === peek(taskQueue) &&
priorityLevel === peek(timerQueue) &&
(isHostTimeoutScheduled
? (localClearTimeout(taskTimeoutID), (taskTimeoutID = -1))
: (isHostTimeoutScheduled = !0),
requestHostTimeout(handleTimeout, options - currentTime)))
: ((priorityLevel.sortIndex = timeout),
push(taskQueue, priorityLevel),
isHostCallbackScheduled ||
isPerformingWork ||
((isHostCallbackScheduled = !0), requestHostCallback()));
return priorityLevel;
};
exports.unstable_shouldYield = shouldYieldToHost;
exports.unstable_wrapCallback = function (callback) {
var parentPriorityLevel = currentPriorityLevel;
return function () {
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = parentPriorityLevel;
try {
return callback.apply(this, arguments);
} finally {
currentPriorityLevel = previousPriorityLevel;
}
};
};
"undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&
"function" ===
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop &&
__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
})();
@@ -0,0 +1,345 @@
/**
* @license React
* scheduler.native.development.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
"use strict";
"production" !== process.env.NODE_ENV &&
(function () {
function performWorkUntilDeadline() {
if (isMessageLoopRunning) {
var currentTime = getCurrentTime();
startTime = currentTime;
var hasMoreWork = !0;
try {
a: {
isHostCallbackScheduled = !1;
isHostTimeoutScheduled &&
((isHostTimeoutScheduled = !1),
localClearTimeout(taskTimeoutID),
(taskTimeoutID = -1));
isPerformingWork = !0;
var previousPriorityLevel = currentPriorityLevel;
try {
b: {
advanceTimers(currentTime);
for (
currentTask = peek(taskQueue);
null !== currentTask &&
!(
currentTask.expirationTime > currentTime &&
shouldYieldToHost()
);
) {
var callback = currentTask.callback;
if ("function" === typeof callback) {
currentTask.callback = null;
currentPriorityLevel = currentTask.priorityLevel;
var continuationCallback = callback(
currentTask.expirationTime <= currentTime
);
currentTime = getCurrentTime();
if ("function" === typeof continuationCallback) {
currentTask.callback = continuationCallback;
advanceTimers(currentTime);
hasMoreWork = !0;
break b;
}
currentTask === peek(taskQueue) && pop(taskQueue);
advanceTimers(currentTime);
} else pop(taskQueue);
currentTask = peek(taskQueue);
}
if (null !== currentTask) hasMoreWork = !0;
else {
var firstTimer = peek(timerQueue);
null !== firstTimer &&
requestHostTimeout(
handleTimeout,
firstTimer.startTime - currentTime
);
hasMoreWork = !1;
}
}
break a;
} finally {
(currentTask = null),
(currentPriorityLevel = previousPriorityLevel),
(isPerformingWork = !1);
}
hasMoreWork = void 0;
}
} finally {
hasMoreWork
? schedulePerformWorkUntilDeadline()
: (isMessageLoopRunning = !1);
}
}
}
function push(heap, node) {
var index = heap.length;
heap.push(node);
a: for (; 0 < index; ) {
var parentIndex = (index - 1) >>> 1,
parent = heap[parentIndex];
if (0 < compare(parent, node))
(heap[parentIndex] = node),
(heap[index] = parent),
(index = parentIndex);
else break a;
}
}
function peek(heap) {
return 0 === heap.length ? null : heap[0];
}
function pop(heap) {
if (0 === heap.length) return null;
var first = heap[0],
last = heap.pop();
if (last !== first) {
heap[0] = last;
a: for (
var index = 0, length = heap.length, halfLength = length >>> 1;
index < halfLength;
) {
var leftIndex = 2 * (index + 1) - 1,
left = heap[leftIndex],
rightIndex = leftIndex + 1,
right = heap[rightIndex];
if (0 > compare(left, last))
rightIndex < length && 0 > compare(right, left)
? ((heap[index] = right),
(heap[rightIndex] = last),
(index = rightIndex))
: ((heap[index] = left),
(heap[leftIndex] = last),
(index = leftIndex));
else if (rightIndex < length && 0 > compare(right, last))
(heap[index] = right),
(heap[rightIndex] = last),
(index = rightIndex);
else break a;
}
}
return first;
}
function compare(a, b) {
var diff = a.sortIndex - b.sortIndex;
return 0 !== diff ? diff : a.id - b.id;
}
function advanceTimers(currentTime) {
for (var timer = peek(timerQueue); null !== timer; ) {
if (null === timer.callback) pop(timerQueue);
else if (timer.startTime <= currentTime)
pop(timerQueue),
(timer.sortIndex = timer.expirationTime),
push(taskQueue, timer);
else break;
timer = peek(timerQueue);
}
}
function handleTimeout(currentTime) {
isHostTimeoutScheduled = !1;
advanceTimers(currentTime);
if (!isHostCallbackScheduled)
if (null !== peek(taskQueue))
(isHostCallbackScheduled = !0),
isMessageLoopRunning ||
((isMessageLoopRunning = !0), schedulePerformWorkUntilDeadline());
else {
var firstTimer = peek(timerQueue);
null !== firstTimer &&
requestHostTimeout(
handleTimeout,
firstTimer.startTime - currentTime
);
}
}
function unstable_scheduleCallback$1(priorityLevel, callback, options) {
var currentTime = getCurrentTime();
"object" === typeof options && null !== options
? ((options = options.delay),
(options =
"number" === typeof options && 0 < options
? currentTime + options
: currentTime))
: (options = currentTime);
switch (priorityLevel) {
case 1:
var timeout = -1;
break;
case 2:
timeout = 250;
break;
case 5:
timeout = 1073741823;
break;
case 4:
timeout = 1e4;
break;
default:
timeout = 5e3;
}
timeout = options + timeout;
priorityLevel = {
id: taskIdCounter++,
callback: callback,
priorityLevel: priorityLevel,
startTime: options,
expirationTime: timeout,
sortIndex: -1
};
options > currentTime
? ((priorityLevel.sortIndex = options),
push(timerQueue, priorityLevel),
null === peek(taskQueue) &&
priorityLevel === peek(timerQueue) &&
(isHostTimeoutScheduled
? (localClearTimeout(taskTimeoutID), (taskTimeoutID = -1))
: (isHostTimeoutScheduled = !0),
requestHostTimeout(handleTimeout, options - currentTime)))
: ((priorityLevel.sortIndex = timeout),
push(taskQueue, priorityLevel),
isHostCallbackScheduled ||
isPerformingWork ||
((isHostCallbackScheduled = !0),
isMessageLoopRunning ||
((isMessageLoopRunning = !0),
schedulePerformWorkUntilDeadline())));
return priorityLevel;
}
function unstable_cancelCallback$1(task) {
task.callback = null;
}
function unstable_getCurrentPriorityLevel$1() {
return currentPriorityLevel;
}
function shouldYieldToHost() {
return getCurrentTime() - startTime < frameInterval ? !1 : !0;
}
function requestPaint() {}
function requestHostTimeout(callback, ms) {
taskTimeoutID = localSetTimeout(function () {
callback(getCurrentTime());
}, ms);
}
function throwNotImplemented() {
throw Error("Not implemented.");
}
if (
"object" === typeof performance &&
"function" === typeof performance.now
) {
var localPerformance = performance;
var getCurrentTime = function () {
return localPerformance.now();
};
} else {
var localDate = Date,
initialTime = localDate.now();
getCurrentTime = function () {
return localDate.now() - initialTime;
};
}
var taskQueue = [],
timerQueue = [],
taskIdCounter = 1,
currentTask = null,
currentPriorityLevel = 3,
isPerformingWork = !1,
isHostCallbackScheduled = !1,
isHostTimeoutScheduled = !1,
localSetTimeout = "function" === typeof setTimeout ? setTimeout : null,
localClearTimeout =
"function" === typeof clearTimeout ? clearTimeout : null,
localSetImmediate =
"undefined" !== typeof setImmediate ? setImmediate : null,
isMessageLoopRunning = !1,
taskTimeoutID = -1,
frameInterval = 5,
startTime = -1;
if ("function" === typeof localSetImmediate)
var schedulePerformWorkUntilDeadline = function () {
localSetImmediate(performWorkUntilDeadline);
};
else if ("undefined" !== typeof MessageChannel) {
var channel = new MessageChannel(),
port = channel.port2;
channel.port1.onmessage = performWorkUntilDeadline;
schedulePerformWorkUntilDeadline = function () {
port.postMessage(null);
};
} else
schedulePerformWorkUntilDeadline = function () {
localSetTimeout(performWorkUntilDeadline, 0);
};
channel =
"undefined" !== typeof nativeRuntimeScheduler
? nativeRuntimeScheduler.unstable_UserBlockingPriority
: 2;
var unstable_NormalPriority =
"undefined" !== typeof nativeRuntimeScheduler
? nativeRuntimeScheduler.unstable_NormalPriority
: 3,
unstable_LowPriority =
"undefined" !== typeof nativeRuntimeScheduler
? nativeRuntimeScheduler.unstable_LowPriority
: 4,
unstable_ImmediatePriority =
"undefined" !== typeof nativeRuntimeScheduler
? nativeRuntimeScheduler.unstable_ImmediatePriority
: 1,
unstable_scheduleCallback =
"undefined" !== typeof nativeRuntimeScheduler
? nativeRuntimeScheduler.unstable_scheduleCallback
: unstable_scheduleCallback$1,
unstable_cancelCallback =
"undefined" !== typeof nativeRuntimeScheduler
? nativeRuntimeScheduler.unstable_cancelCallback
: unstable_cancelCallback$1,
unstable_getCurrentPriorityLevel =
"undefined" !== typeof nativeRuntimeScheduler
? nativeRuntimeScheduler.unstable_getCurrentPriorityLevel
: unstable_getCurrentPriorityLevel$1,
unstable_shouldYield =
"undefined" !== typeof nativeRuntimeScheduler
? nativeRuntimeScheduler.unstable_shouldYield
: shouldYieldToHost,
unstable_requestPaint =
"undefined" !== typeof nativeRuntimeScheduler
? nativeRuntimeScheduler.unstable_requestPaint
: requestPaint,
unstable_now =
"undefined" !== typeof nativeRuntimeScheduler
? nativeRuntimeScheduler.unstable_now
: getCurrentTime;
exports.unstable_IdlePriority =
"undefined" !== typeof nativeRuntimeScheduler
? nativeRuntimeScheduler.unstable_IdlePriority
: 5;
exports.unstable_ImmediatePriority = unstable_ImmediatePriority;
exports.unstable_LowPriority = unstable_LowPriority;
exports.unstable_NormalPriority = unstable_NormalPriority;
exports.unstable_Profiling = null;
exports.unstable_UserBlockingPriority = channel;
exports.unstable_cancelCallback = unstable_cancelCallback;
exports.unstable_continueExecution = throwNotImplemented;
exports.unstable_forceFrameRate = throwNotImplemented;
exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel;
exports.unstable_getFirstCallbackNode = throwNotImplemented;
exports.unstable_next = throwNotImplemented;
exports.unstable_now = unstable_now;
exports.unstable_pauseExecution = throwNotImplemented;
exports.unstable_requestPaint = unstable_requestPaint;
exports.unstable_runWithPriority = throwNotImplemented;
exports.unstable_scheduleCallback = unstable_scheduleCallback;
exports.unstable_shouldYield = unstable_shouldYield;
exports.unstable_wrapCallback = throwNotImplemented;
})();
@@ -0,0 +1,329 @@
/**
* @license React
* scheduler.native.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
"use strict";
function push(heap, node) {
var index = heap.length;
heap.push(node);
a: for (; 0 < index; ) {
var parentIndex = (index - 1) >>> 1,
parent = heap[parentIndex];
if (0 < compare(parent, node))
(heap[parentIndex] = node), (heap[index] = parent), (index = parentIndex);
else break a;
}
}
function peek(heap) {
return 0 === heap.length ? null : heap[0];
}
function pop(heap) {
if (0 === heap.length) return null;
var first = heap[0],
last = heap.pop();
if (last !== first) {
heap[0] = last;
a: for (
var index = 0, length = heap.length, halfLength = length >>> 1;
index < halfLength;
) {
var leftIndex = 2 * (index + 1) - 1,
left = heap[leftIndex],
rightIndex = leftIndex + 1,
right = heap[rightIndex];
if (0 > compare(left, last))
rightIndex < length && 0 > compare(right, left)
? ((heap[index] = right),
(heap[rightIndex] = last),
(index = rightIndex))
: ((heap[index] = left),
(heap[leftIndex] = last),
(index = leftIndex));
else if (rightIndex < length && 0 > compare(right, last))
(heap[index] = right), (heap[rightIndex] = last), (index = rightIndex);
else break a;
}
}
return first;
}
function compare(a, b) {
var diff = a.sortIndex - b.sortIndex;
return 0 !== diff ? diff : a.id - b.id;
}
var getCurrentTime;
if ("object" === typeof performance && "function" === typeof performance.now) {
var localPerformance = performance;
getCurrentTime = function () {
return localPerformance.now();
};
} else {
var localDate = Date,
initialTime = localDate.now();
getCurrentTime = function () {
return localDate.now() - initialTime;
};
}
var taskQueue = [],
timerQueue = [],
taskIdCounter = 1,
currentTask = null,
currentPriorityLevel = 3,
isPerformingWork = !1,
isHostCallbackScheduled = !1,
isHostTimeoutScheduled = !1,
localSetTimeout = "function" === typeof setTimeout ? setTimeout : null,
localClearTimeout = "function" === typeof clearTimeout ? clearTimeout : null,
localSetImmediate = "undefined" !== typeof setImmediate ? setImmediate : null;
function advanceTimers(currentTime) {
for (var timer = peek(timerQueue); null !== timer; ) {
if (null === timer.callback) pop(timerQueue);
else if (timer.startTime <= currentTime)
pop(timerQueue),
(timer.sortIndex = timer.expirationTime),
push(taskQueue, timer);
else break;
timer = peek(timerQueue);
}
}
function handleTimeout(currentTime) {
isHostTimeoutScheduled = !1;
advanceTimers(currentTime);
if (!isHostCallbackScheduled)
if (null !== peek(taskQueue))
(isHostCallbackScheduled = !0),
isMessageLoopRunning ||
((isMessageLoopRunning = !0), schedulePerformWorkUntilDeadline());
else {
var firstTimer = peek(timerQueue);
null !== firstTimer &&
requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
}
}
function unstable_scheduleCallback$1(priorityLevel, callback, options) {
var currentTime = getCurrentTime();
"object" === typeof options && null !== options
? ((options = options.delay),
(options =
"number" === typeof options && 0 < options
? currentTime + options
: currentTime))
: (options = currentTime);
switch (priorityLevel) {
case 1:
var timeout = -1;
break;
case 2:
timeout = 250;
break;
case 5:
timeout = 1073741823;
break;
case 4:
timeout = 1e4;
break;
default:
timeout = 5e3;
}
timeout = options + timeout;
priorityLevel = {
id: taskIdCounter++,
callback: callback,
priorityLevel: priorityLevel,
startTime: options,
expirationTime: timeout,
sortIndex: -1
};
options > currentTime
? ((priorityLevel.sortIndex = options),
push(timerQueue, priorityLevel),
null === peek(taskQueue) &&
priorityLevel === peek(timerQueue) &&
(isHostTimeoutScheduled
? (localClearTimeout(taskTimeoutID), (taskTimeoutID = -1))
: (isHostTimeoutScheduled = !0),
requestHostTimeout(handleTimeout, options - currentTime)))
: ((priorityLevel.sortIndex = timeout),
push(taskQueue, priorityLevel),
isHostCallbackScheduled ||
isPerformingWork ||
((isHostCallbackScheduled = !0),
isMessageLoopRunning ||
((isMessageLoopRunning = !0), schedulePerformWorkUntilDeadline())));
return priorityLevel;
}
function unstable_cancelCallback$1(task) {
task.callback = null;
}
function unstable_getCurrentPriorityLevel$1() {
return currentPriorityLevel;
}
var isMessageLoopRunning = !1,
taskTimeoutID = -1,
startTime = -1;
function shouldYieldToHost() {
return 5 > getCurrentTime() - startTime ? !1 : !0;
}
function requestPaint() {}
function performWorkUntilDeadline() {
if (isMessageLoopRunning) {
var currentTime = getCurrentTime();
startTime = currentTime;
var hasMoreWork = !0;
try {
a: {
isHostCallbackScheduled = !1;
isHostTimeoutScheduled &&
((isHostTimeoutScheduled = !1),
localClearTimeout(taskTimeoutID),
(taskTimeoutID = -1));
isPerformingWork = !0;
var previousPriorityLevel = currentPriorityLevel;
try {
b: {
advanceTimers(currentTime);
for (
currentTask = peek(taskQueue);
null !== currentTask &&
!(
currentTask.expirationTime > currentTime && shouldYieldToHost()
);
) {
var callback = currentTask.callback;
if ("function" === typeof callback) {
currentTask.callback = null;
currentPriorityLevel = currentTask.priorityLevel;
var continuationCallback = callback(
currentTask.expirationTime <= currentTime
);
currentTime = getCurrentTime();
if ("function" === typeof continuationCallback) {
currentTask.callback = continuationCallback;
advanceTimers(currentTime);
hasMoreWork = !0;
break b;
}
currentTask === peek(taskQueue) && pop(taskQueue);
advanceTimers(currentTime);
} else pop(taskQueue);
currentTask = peek(taskQueue);
}
if (null !== currentTask) hasMoreWork = !0;
else {
var firstTimer = peek(timerQueue);
null !== firstTimer &&
requestHostTimeout(
handleTimeout,
firstTimer.startTime - currentTime
);
hasMoreWork = !1;
}
}
break a;
} finally {
(currentTask = null),
(currentPriorityLevel = previousPriorityLevel),
(isPerformingWork = !1);
}
hasMoreWork = void 0;
}
} finally {
hasMoreWork
? schedulePerformWorkUntilDeadline()
: (isMessageLoopRunning = !1);
}
}
}
var schedulePerformWorkUntilDeadline;
if ("function" === typeof localSetImmediate)
schedulePerformWorkUntilDeadline = function () {
localSetImmediate(performWorkUntilDeadline);
};
else if ("undefined" !== typeof MessageChannel) {
var channel = new MessageChannel(),
port = channel.port2;
channel.port1.onmessage = performWorkUntilDeadline;
schedulePerformWorkUntilDeadline = function () {
port.postMessage(null);
};
} else
schedulePerformWorkUntilDeadline = function () {
localSetTimeout(performWorkUntilDeadline, 0);
};
function requestHostTimeout(callback, ms) {
taskTimeoutID = localSetTimeout(function () {
callback(getCurrentTime());
}, ms);
}
var unstable_UserBlockingPriority =
"undefined" !== typeof nativeRuntimeScheduler
? nativeRuntimeScheduler.unstable_UserBlockingPriority
: 2,
unstable_NormalPriority =
"undefined" !== typeof nativeRuntimeScheduler
? nativeRuntimeScheduler.unstable_NormalPriority
: 3,
unstable_LowPriority =
"undefined" !== typeof nativeRuntimeScheduler
? nativeRuntimeScheduler.unstable_LowPriority
: 4,
unstable_ImmediatePriority =
"undefined" !== typeof nativeRuntimeScheduler
? nativeRuntimeScheduler.unstable_ImmediatePriority
: 1,
unstable_scheduleCallback =
"undefined" !== typeof nativeRuntimeScheduler
? nativeRuntimeScheduler.unstable_scheduleCallback
: unstable_scheduleCallback$1,
unstable_cancelCallback =
"undefined" !== typeof nativeRuntimeScheduler
? nativeRuntimeScheduler.unstable_cancelCallback
: unstable_cancelCallback$1,
unstable_getCurrentPriorityLevel =
"undefined" !== typeof nativeRuntimeScheduler
? nativeRuntimeScheduler.unstable_getCurrentPriorityLevel
: unstable_getCurrentPriorityLevel$1,
unstable_shouldYield =
"undefined" !== typeof nativeRuntimeScheduler
? nativeRuntimeScheduler.unstable_shouldYield
: shouldYieldToHost,
unstable_requestPaint =
"undefined" !== typeof nativeRuntimeScheduler
? nativeRuntimeScheduler.unstable_requestPaint
: requestPaint,
unstable_now =
"undefined" !== typeof nativeRuntimeScheduler
? nativeRuntimeScheduler.unstable_now
: getCurrentTime;
function throwNotImplemented() {
throw Error("Not implemented.");
}
exports.unstable_IdlePriority =
"undefined" !== typeof nativeRuntimeScheduler
? nativeRuntimeScheduler.unstable_IdlePriority
: 5;
exports.unstable_ImmediatePriority = unstable_ImmediatePriority;
exports.unstable_LowPriority = unstable_LowPriority;
exports.unstable_NormalPriority = unstable_NormalPriority;
exports.unstable_Profiling = null;
exports.unstable_UserBlockingPriority = unstable_UserBlockingPriority;
exports.unstable_cancelCallback = unstable_cancelCallback;
exports.unstable_continueExecution = throwNotImplemented;
exports.unstable_forceFrameRate = throwNotImplemented;
exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel;
exports.unstable_getFirstCallbackNode = throwNotImplemented;
exports.unstable_next = throwNotImplemented;
exports.unstable_now = unstable_now;
exports.unstable_pauseExecution = throwNotImplemented;
exports.unstable_requestPaint = unstable_requestPaint;
exports.unstable_runWithPriority = throwNotImplemented;
exports.unstable_scheduleCallback = unstable_scheduleCallback;
exports.unstable_shouldYield = unstable_shouldYield;
exports.unstable_wrapCallback = throwNotImplemented;
@@ -0,0 +1,341 @@
/**
* @license React
* scheduler.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
"use strict";
function push(heap, node) {
var index = heap.length;
heap.push(node);
a: for (; 0 < index; ) {
var parentIndex = (index - 1) >>> 1,
parent = heap[parentIndex];
if (0 < compare(parent, node))
(heap[parentIndex] = node), (heap[index] = parent), (index = parentIndex);
else break a;
}
}
function peek(heap) {
return 0 === heap.length ? null : heap[0];
}
function pop(heap) {
if (0 === heap.length) return null;
var first = heap[0],
last = heap.pop();
if (last !== first) {
heap[0] = last;
a: for (
var index = 0, length = heap.length, halfLength = length >>> 1;
index < halfLength;
) {
var leftIndex = 2 * (index + 1) - 1,
left = heap[leftIndex],
rightIndex = leftIndex + 1,
right = heap[rightIndex];
if (0 > compare(left, last))
rightIndex < length && 0 > compare(right, left)
? ((heap[index] = right),
(heap[rightIndex] = last),
(index = rightIndex))
: ((heap[index] = left),
(heap[leftIndex] = last),
(index = leftIndex));
else if (rightIndex < length && 0 > compare(right, last))
(heap[index] = right), (heap[rightIndex] = last), (index = rightIndex);
else break a;
}
}
return first;
}
function compare(a, b) {
var diff = a.sortIndex - b.sortIndex;
return 0 !== diff ? diff : a.id - b.id;
}
exports.unstable_now = void 0;
if ("object" === typeof performance && "function" === typeof performance.now) {
var localPerformance = performance;
exports.unstable_now = function () {
return localPerformance.now();
};
} else {
var localDate = Date,
initialTime = localDate.now();
exports.unstable_now = function () {
return localDate.now() - initialTime;
};
}
var taskQueue = [],
timerQueue = [],
taskIdCounter = 1,
currentTask = null,
currentPriorityLevel = 3,
isPerformingWork = !1,
isHostCallbackScheduled = !1,
isHostTimeoutScheduled = !1,
localSetTimeout = "function" === typeof setTimeout ? setTimeout : null,
localClearTimeout = "function" === typeof clearTimeout ? clearTimeout : null,
localSetImmediate = "undefined" !== typeof setImmediate ? setImmediate : null;
function advanceTimers(currentTime) {
for (var timer = peek(timerQueue); null !== timer; ) {
if (null === timer.callback) pop(timerQueue);
else if (timer.startTime <= currentTime)
pop(timerQueue),
(timer.sortIndex = timer.expirationTime),
push(taskQueue, timer);
else break;
timer = peek(timerQueue);
}
}
function handleTimeout(currentTime) {
isHostTimeoutScheduled = !1;
advanceTimers(currentTime);
if (!isHostCallbackScheduled)
if (null !== peek(taskQueue))
(isHostCallbackScheduled = !0), requestHostCallback();
else {
var firstTimer = peek(timerQueue);
null !== firstTimer &&
requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
}
}
var isMessageLoopRunning = !1,
taskTimeoutID = -1,
frameInterval = 5,
startTime = -1;
function shouldYieldToHost() {
return exports.unstable_now() - startTime < frameInterval ? !1 : !0;
}
function performWorkUntilDeadline() {
if (isMessageLoopRunning) {
var currentTime = exports.unstable_now();
startTime = currentTime;
var hasMoreWork = !0;
try {
a: {
isHostCallbackScheduled = !1;
isHostTimeoutScheduled &&
((isHostTimeoutScheduled = !1),
localClearTimeout(taskTimeoutID),
(taskTimeoutID = -1));
isPerformingWork = !0;
var previousPriorityLevel = currentPriorityLevel;
try {
b: {
advanceTimers(currentTime);
for (
currentTask = peek(taskQueue);
null !== currentTask &&
!(
currentTask.expirationTime > currentTime && shouldYieldToHost()
);
) {
var callback = currentTask.callback;
if ("function" === typeof callback) {
currentTask.callback = null;
currentPriorityLevel = currentTask.priorityLevel;
var continuationCallback = callback(
currentTask.expirationTime <= currentTime
);
currentTime = exports.unstable_now();
if ("function" === typeof continuationCallback) {
currentTask.callback = continuationCallback;
advanceTimers(currentTime);
hasMoreWork = !0;
break b;
}
currentTask === peek(taskQueue) && pop(taskQueue);
advanceTimers(currentTime);
} else pop(taskQueue);
currentTask = peek(taskQueue);
}
if (null !== currentTask) hasMoreWork = !0;
else {
var firstTimer = peek(timerQueue);
null !== firstTimer &&
requestHostTimeout(
handleTimeout,
firstTimer.startTime - currentTime
);
hasMoreWork = !1;
}
}
break a;
} finally {
(currentTask = null),
(currentPriorityLevel = previousPriorityLevel),
(isPerformingWork = !1);
}
hasMoreWork = void 0;
}
} finally {
hasMoreWork
? schedulePerformWorkUntilDeadline()
: (isMessageLoopRunning = !1);
}
}
}
var schedulePerformWorkUntilDeadline;
if ("function" === typeof localSetImmediate)
schedulePerformWorkUntilDeadline = function () {
localSetImmediate(performWorkUntilDeadline);
};
else if ("undefined" !== typeof MessageChannel) {
var channel = new MessageChannel(),
port = channel.port2;
channel.port1.onmessage = performWorkUntilDeadline;
schedulePerformWorkUntilDeadline = function () {
port.postMessage(null);
};
} else
schedulePerformWorkUntilDeadline = function () {
localSetTimeout(performWorkUntilDeadline, 0);
};
function requestHostCallback() {
isMessageLoopRunning ||
((isMessageLoopRunning = !0), schedulePerformWorkUntilDeadline());
}
function requestHostTimeout(callback, ms) {
taskTimeoutID = localSetTimeout(function () {
callback(exports.unstable_now());
}, ms);
}
exports.unstable_IdlePriority = 5;
exports.unstable_ImmediatePriority = 1;
exports.unstable_LowPriority = 4;
exports.unstable_NormalPriority = 3;
exports.unstable_Profiling = null;
exports.unstable_UserBlockingPriority = 2;
exports.unstable_cancelCallback = function (task) {
task.callback = null;
};
exports.unstable_continueExecution = function () {
isHostCallbackScheduled ||
isPerformingWork ||
((isHostCallbackScheduled = !0), requestHostCallback());
};
exports.unstable_forceFrameRate = function (fps) {
0 > fps || 125 < fps
? console.error(
"forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"
)
: (frameInterval = 0 < fps ? Math.floor(1e3 / fps) : 5);
};
exports.unstable_getCurrentPriorityLevel = function () {
return currentPriorityLevel;
};
exports.unstable_getFirstCallbackNode = function () {
return peek(taskQueue);
};
exports.unstable_next = function (eventHandler) {
switch (currentPriorityLevel) {
case 1:
case 2:
case 3:
var priorityLevel = 3;
break;
default:
priorityLevel = currentPriorityLevel;
}
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = priorityLevel;
try {
return eventHandler();
} finally {
currentPriorityLevel = previousPriorityLevel;
}
};
exports.unstable_pauseExecution = function () {};
exports.unstable_requestPaint = function () {};
exports.unstable_runWithPriority = function (priorityLevel, eventHandler) {
switch (priorityLevel) {
case 1:
case 2:
case 3:
case 4:
case 5:
break;
default:
priorityLevel = 3;
}
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = priorityLevel;
try {
return eventHandler();
} finally {
currentPriorityLevel = previousPriorityLevel;
}
};
exports.unstable_scheduleCallback = function (
priorityLevel,
callback,
options
) {
var currentTime = exports.unstable_now();
"object" === typeof options && null !== options
? ((options = options.delay),
(options =
"number" === typeof options && 0 < options
? currentTime + options
: currentTime))
: (options = currentTime);
switch (priorityLevel) {
case 1:
var timeout = -1;
break;
case 2:
timeout = 250;
break;
case 5:
timeout = 1073741823;
break;
case 4:
timeout = 1e4;
break;
default:
timeout = 5e3;
}
timeout = options + timeout;
priorityLevel = {
id: taskIdCounter++,
callback: callback,
priorityLevel: priorityLevel,
startTime: options,
expirationTime: timeout,
sortIndex: -1
};
options > currentTime
? ((priorityLevel.sortIndex = options),
push(timerQueue, priorityLevel),
null === peek(taskQueue) &&
priorityLevel === peek(timerQueue) &&
(isHostTimeoutScheduled
? (localClearTimeout(taskTimeoutID), (taskTimeoutID = -1))
: (isHostTimeoutScheduled = !0),
requestHostTimeout(handleTimeout, options - currentTime)))
: ((priorityLevel.sortIndex = timeout),
push(taskQueue, priorityLevel),
isHostCallbackScheduled ||
isPerformingWork ||
((isHostCallbackScheduled = !0), requestHostCallback()));
return priorityLevel;
};
exports.unstable_shouldYield = shouldYieldToHost;
exports.unstable_wrapCallback = function (callback) {
var parentPriorityLevel = currentPriorityLevel;
return function () {
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = parentPriorityLevel;
try {
return callback.apply(this, arguments);
} finally {
currentPriorityLevel = previousPriorityLevel;
}
};
};
+7
View File
@@ -0,0 +1,7 @@
'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/scheduler.production.js');
} else {
module.exports = require('./cjs/scheduler.development.js');
}
@@ -0,0 +1,7 @@
'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/scheduler.native.production.js');
} else {
module.exports = require('./cjs/scheduler.native.development.js');
}
+27
View File
@@ -0,0 +1,27 @@
{
"name": "scheduler",
"version": "0.25.0-rc-603e6108-20241029",
"description": "Cooperative scheduler for the browser environment.",
"repository": {
"type": "git",
"url": "https://github.com/facebook/react.git",
"directory": "packages/scheduler"
},
"license": "MIT",
"keywords": [
"react"
],
"bugs": {
"url": "https://github.com/facebook/react/issues"
},
"homepage": "https://react.dev/",
"files": [
"LICENSE",
"README.md",
"index.js",
"index.native.js",
"unstable_mock.js",
"unstable_post_task.js",
"cjs/"
]
}
@@ -0,0 +1,7 @@
'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/scheduler-unstable_mock.production.js');
} else {
module.exports = require('./cjs/scheduler-unstable_mock.development.js');
}
@@ -0,0 +1,7 @@
'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/scheduler-unstable_post_task.production.js');
} else {
module.exports = require('./cjs/scheduler-unstable_post_task.development.js');
}
+39
View File
@@ -0,0 +1,39 @@
{
"name": "@react-pdf/reconciler",
"version": "1.1.4",
"license": "MIT",
"description": "Define uninitialized elements",
"author": "Diego Muracciole <diegomuracciole@gmail.com>",
"homepage": "https://github.com/diegomura/react-pdf#readme",
"type": "module",
"main": "./lib/index.js",
"types": "./lib/index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/diegomura/react-pdf.git",
"directory": "packages/reconciler"
},
"scripts": {
"build": "rimraf ./lib && rollup -c",
"watch": "rimraf ./lib && rollup -c -w",
"size": "size-limit",
"lint": "eslint src",
"test": "vitest"
},
"files": [
"lib"
],
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
},
"dependencies": {
"object-assign": "^4.1.1",
"scheduler": "0.25.0-rc-603e6108-20241029"
},
"devDependencies": {
"ast-types": "^0.14.2",
"react-reconciler-23": "npm:react-reconciler@0.23.0",
"react-reconciler-31": "npm:react-reconciler@0.31.0-rc-603e6108-20241029",
"recast": "^0.23.9"
}
}
+145
View File
@@ -0,0 +1,145 @@
<p align="center">
<img src="https://user-images.githubusercontent.com/5600341/27505816-c8bc37aa-587f-11e7-9a86-08a2d081a8b9.png" height="280px">
</p>
# @react-pdf/render
> React-pdf render engine
## How to install
```sh
yarn add @react-pdf/render
```
## How it works
```js
import render from '@react-pdf/render';
import primitives from '@react-pdf/primitives';
const view = {
type: primitives.View,
style: {
backgroundColor: 'red',
borderTopLeftRadius: 5,
borderTopRightRadius: 10,
borderBottomLeftRadius: 0,
borderBottomRightRadius: 15,
borderTopColor: 'yellow',
borderLeftColor: 'green',
borderBottomColor: 'black',
borderRightColor: 'purple',
},
box: {
left: 20,
top: 20,
width: 100,
height: 80,
borderTopWidth: 3,
borderLeftWidth: 2,
borderBottomWidth: 1,
borderRightWidth: 4,
},
};
const doc = {
type: primitives.Document,
children: [
{
type: primitives.Page,
box: { width: 400, height: 600 },
children: [view],
},
],
};
// Provide your own context
const ctx = createContext();
render.default(ctx, doc);
```
This library exports a `render` function that takes two arguments:
- _ctx_: This is the target context where the document is going to be rendered. React-pdf currently uses a [pdfkit](https://github.com/react-pdf/pdfkit) document as context, but it can target any other type of structure as long as it signature matches pdfkit API. In the future this will enable rendering documents into muliple formats in addition to PDF.
- _node_: Document root node. A node is a nested structure that defines a single element in a document. They are defined by it's `type` and arguments.
## Node structure
A node represents a single element inside a document. It's mainly defined by it's `type` (mandatory) field in addition to other values to define where that element is positioned inside the document (`box`), how it looks (`style`), how it should behave (`params`) and what sub-nodes it contains (`children`).
The root node must always be of type `DOCUMENT`, containing as many `PAGE` nodes as desired inside it's children field.
Bare in mind this package does not handle any type of node positioning, inheritance, style transformations or any other layout related logic. It's role is limited to render exactly the node it get's into the provided context. Take this into account when definig styles as `paddingTop`, `paddingLeft` and so on instead of the shortcut `padding`. For layout or styles transformation this project provides separate packages.
### node.type
Mandatory field specifiying the type of the particular node. The full list of types can be found and imported from `@react-pdf/primitives`
### node.box
Defines bounding box where a particular node is located inside a document
- left
- top
- width
- height
- paddingTop
- paddingLeft
- paddingBottom
- paddingRight
- marginTop
- marginLeft
- marginBottom
- marginRight
- borderTopWidth
- borderLeftWidth
- borderBottomWidth
- borderRightWidth
### node.style
Defines how the node looks like. There are some types of nodes that expect special style values, but generally all support:
- color
- opacity
- overflow
- backgroundColor
- borderTopLeftRadius
- borderTopRightRadius
- borderBottomLeftRadius
- borderBottomRightRadius
- borderTopColor
- borderLeftColor
- borderBottomColor
- borderRightColor
- _others..._
### node.props
Specific node params needed to render correctly ot behave like certain way. Specially needed for SVG nodes
## PDF example
```js
import fs from 'fs';
import render from '@react-pdf/render';
import pdfkit from '@react-pdf/pdfkit';
const PDFDocument = pdfkit.default;
const ctx = new PDFDocument({ autoFirstPage: false });
const doc = {}; // See above
render.default(ctx, doc);
const stream = fs.createWriteStream('./test.pdf');
ctx.pipe(stream);
```
## License
MIT © [Diego Muracciole](http://github.com/diegomura)
+23
View File
@@ -0,0 +1,23 @@
/// <reference types="node" />
import { SafeDocumentNode } from '@react-pdf/layout';
import { Font } from '@react-pdf/textkit';
import PDFKitDocument from 'pdfkit';
type PDFFontSource = string | Buffer | Uint8Array | ArrayBuffer | Font;
type Context = typeof PDFKitDocument & {
_root: any;
_font: any;
_imageRegistry: any;
_acroform: any;
_fontSize: number;
openImage: any;
addNamedDestination: any;
addPage(options?: any): Context;
translate(x: number, y: number, options: any): Context;
font(src: PDFFontSource, size?: number): Context;
font(src: PDFFontSource, family: string, size?: number): Context;
};
declare const render: (ctx: Context, doc: SafeDocumentNode) => Context;
export { render as default };
+2075
View File
File diff suppressed because it is too large Load Diff
+42
View File
@@ -0,0 +1,42 @@
{
"name": "@react-pdf/render",
"version": "4.3.0",
"license": "MIT",
"description": "A render engine for Node and the browser",
"author": "Diego Muracciole <diegomuracciole@gmail.com>",
"homepage": "https://github.com/diegomura/react-pdf#readme",
"type": "module",
"main": "./lib/index.js",
"repository": {
"type": "git",
"url": "https://github.com/diegomura/react-pdf.git",
"directory": "packages/render"
},
"scripts": {
"test": "vitest",
"build": "rimraf ./lib && rollup -c",
"watch": "rimraf ./lib && rollup -c -w",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@babel/runtime": "^7.20.13",
"@react-pdf/fns": "3.1.2",
"@react-pdf/primitives": "^4.1.1",
"@react-pdf/textkit": "^6.0.0",
"@react-pdf/types": "^2.9.0",
"abs-svg-path": "^0.1.1",
"color-string": "^1.9.1",
"normalize-svg-path": "^1.1.0",
"parse-svg-path": "^0.1.2",
"svg-arc-to-cubic-bezier": "^3.2.0"
},
"devDependencies": {
"@react-pdf/layout": "^4.4.0",
"@types/abs-svg-path": "^0.1.3",
"@types/color-string": "^1.5.5",
"@types/pdfkit": "^0.13.9"
},
"files": [
"lib"
]
}
+162
View File
@@ -0,0 +1,162 @@
<p align="center">
<img src="https://user-images.githubusercontent.com/5600341/27505816-c8bc37aa-587f-11e7-9a86-08a2d081a8b9.png" height="280px">
<p align="center">React renderer for creating PDF files on the browser and server<p>
<p align="center">
<a href="https://www.npmjs.com/package/@react-pdf/renderer">
<img src="https://img.shields.io/npm/v/@react-pdf/renderer.svg" />
</a>
<a href="https://travis-ci.org/diegomura/react-pdf">
<img src="https://img.shields.io/travis/diegomura/react-pdf.svg" />
</a>
<a href="https://github.com/diegomura/react-pdf/blob/master/LICENSE">
<img src="https://img.shields.io/github/license/diegomura/react-pdf.svg" />
</a>
<a href="https://spectrum.chat/react-pdf">
<img src="https://withspectrum.github.io/badge/badge.svg" />
</a>
<a href="https://github.com/prettier/prettier">
<img src="https://img.shields.io/badge/styled_with-prettier-ff69b4.svg" />
</a>
</p>
</p>
## How to install
```sh
yarn add @react-pdf/renderer
```
## How it works
```jsx
import { Document, Page, Text, View, StyleSheet } from '@react-pdf/renderer';
// Create styles
const styles = StyleSheet.create({
page: {
flexDirection: 'row',
backgroundColor: '#E4E4E4',
},
section: {
margin: 10,
padding: 10,
flexGrow: 1,
},
});
// Create Document Component
const MyDocument = () => (
<Document>
<Page size="A4" style={styles.page}>
<View style={styles.section}>
<Text>Section #1</Text>
</View>
<View style={styles.section}>
<Text>Section #2</Text>
</View>
</Page>
</Document>
);
```
### `Web.` Render in DOM
```jsx
import ReactDOM from 'react-dom';
import { PDFViewer } from '@react-pdf/renderer';
const App = () => (
<PDFViewer>
<MyDocument />
</PDFViewer>
);
ReactDOM.render(<App />, document.getElementById('root'));
```
### `Node.` Save in a file
```jsx
import ReactPDF from '@react-pdf/renderer';
ReactPDF.render(<MyDocument />, `${__dirname}/example.pdf`);
```
## Examples
For each example, try opening `output.pdf` to see the result.
<table>
<tbody>
<tr>
<td align="center" valign="top">
<a href="https://github.com/diegomura/react-pdf/tree/master/packages/examples/src/text/">
<img width="150" height="150" src="https://github.com/diegomura/react-pdf/blob/master/packages/examples/src/text/thumb.png?raw=true">
</a>
<br>
<a href="https://github.com/diegomura/react-pdf/tree/master/packages/examples/src/text/">Text</a>
</td>
<td align="center" valign="top">
<a href="https://github.com/diegomura/react-pdf/tree/master/packages/examples/src/resume/">
<img width="150" height="150" src="https://github.com/diegomura/react-pdf/blob/master/packages/examples/src/resume/thumb.png?raw=true">
</a>
<br>
<a href="https://github.com/diegomura/react-pdf/tree/master/packages/examples/src/resume/">Resume</a>
</td>
<td align="center" valign="top">
<a href="https://github.com/diegomura/react-pdf/tree/master/packages/examples/src/fractals/">
<img width="150" height="150" src="https://github.com/diegomura/react-pdf/blob/master/packages/examples/src/fractals/thumb.png?raw=true">
</a>
<br>
<a href="https://github.com/diegomura/react-pdf/tree/master/packages/examples/src/fractals/">Fractals</a>
</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td align="center" valign="top">
<a href="https://github.com/diegomura/react-pdf/tree/master/packages/examples/src/knobs/">
<img width="150" height="150" src="https://github.com/diegomura/react-pdf/blob/master/packages/examples/src/knobs/thumb.png?raw=true">
</a>
<br>
<a href="https://github.com/diegomura/react-pdf/tree/master/packages/examples/src/knobs/">Knobs</a>
</td>
<td align="center" valign="top">
<a href="https://github.com/diegomura/react-pdf/tree/master/packages/examples/src/pageWrap/">
<img width="150" height="150" src="https://github.com/diegomura/react-pdf/blob/master/packages/examples/src/pageWrap/thumb.png?raw=true">
</a>
<br>
<a href="https://github.com/diegomura/react-pdf/tree/master/packages/examples/src/pageWrap/">Page wrap</a>
</td>
</tr>
</tbody>
</table>
## Contributors
This project exists thanks to all the people who contribute. [[Contribute]](CONTRIBUTING.md).
<a href="https://github.com/diegomura/react-pdf/graphs/contributors"><img src="https://opencollective.com/react-pdf/contributors.svg?width=890" /></a>
## Sponsors
Thank you to all our sponsors! [[Become a sponsors](https://opencollective.com/react-pdf#sponsors)]
<a href="https://opencollective.com/react-pdf#sponsors" target="_blank"><img src="https://opencollective.com/react-pdf/sponsors.svg?width=890"></a>
## Backers
Thank you to all our backers! [[Become a backer](https://opencollective.com/react-pdf#backer)]
<a href="https://opencollective.com/react-pdf#backers" target="_blank"><img src="https://opencollective.com/react-pdf/backers.svg?width=890"></a>
## License
MIT © [Diego Muracciole](http://github.com/diegomura)
[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Ftaylorudell%2Freact-pdf.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2Ftaylorudell%2Freact-pdf?ref=badge_large)
---
![](https://img.shields.io/npm/dt/@react-pdf/renderer.svg?style=flat)
+691
View File
@@ -0,0 +1,691 @@
/* eslint-disable max-classes-per-file */
import * as React from 'react';
import {
Style,
PageSize,
FontStore,
PDFVersion,
Orientation,
SourceObject,
HyphenationCallback,
SVGPresentationAttributes,
Bookmark,
PageLayout,
PageMode,
} from '@react-pdf/types';
declare class ReactPDF {
static default: typeof ReactPDF;
}
export = ReactPDF;
declare namespace ReactPDF {
interface Styles {
[key: string]: Style;
}
interface OnRenderProps {
blob?: Blob;
}
interface DocumentProps {
style?: Style | Style[];
title?: string;
author?: string;
subject?: string;
creator?: string;
keywords?: string;
producer?: string;
language?: string;
creationDate?: Date;
modificationDate?: Date;
pdfVersion?: PDFVersion;
pageMode?: PageMode;
pageLayout?: PageLayout;
onRender?: (props: OnRenderProps) => any;
}
/**
* This component represent the PDF document itself. It must be the root
* of your tree element structure, and under no circumstances should it be
* used as children of another react-pdf component. In addition, it should
* only have childs of type <Page />.
*/
export class Document extends React.Component<
React.PropsWithChildren<DocumentProps>
> {}
interface NodeProps {
id?: string;
style?: Style | Style[];
/**
* Render component in all wrapped pages.
* @see https://react-pdf.org/advanced#fixed-components
*/
fixed?: boolean;
/**
* Force the wrapping algorithm to start a new page when rendering the
* element.
* @see https://react-pdf.org/advanced#page-breaks
*/
break?: boolean;
/**
* Hint that no page wrapping should occur between all sibling elements following the element within n points
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
minPresenceAhead?: number;
}
interface PageProps extends NodeProps {
/**
* Enable page wrapping for this page.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
size?: PageSize;
orientation?: Orientation;
dpi?: number;
bookmark?: Bookmark;
}
/**
* Represents single page inside the PDF document, or a subset of them if
* using the wrapping feature. A <Document /> can contain as many pages as
* you want, but ensure not rendering a page inside any component besides
* Document.
*/
export class Page extends React.Component<
React.PropsWithChildren<PageProps>
> {}
interface ViewProps extends NodeProps {
id?: string;
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
render?: (props: {
pageNumber: number;
subPageNumber: number;
}) => React.ReactNode;
}
/**
* The most fundamental component for building a UI and is designed to be
* nested inside other views and can have 0 to many children.
*/
export class View extends React.Component<
React.PropsWithChildren<ViewProps>
> {}
interface BaseImageProps extends NodeProps {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
cache?: boolean;
}
interface ImageWithSrcProp extends BaseImageProps {
src: SourceObject;
}
interface ImageWithSourceProp extends BaseImageProps {
source: SourceObject;
}
type ImageProps = ImageWithSrcProp | ImageWithSourceProp;
/**
* A React component for displaying network or local (Node only) JPG or
* PNG images, as well as base64 encoded image strings.
*/
export class Image extends React.Component<ImageProps> {}
interface TextProps extends NodeProps {
id?: string;
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
render?: (props: {
pageNumber: number;
totalPages: number;
subPageNumber: number;
subPageTotalPages: number;
}) => React.ReactNode;
/**
* Override the default hyphenation-callback
* @see https://react-pdf.org/fonts#registerhyphenationcallback
*/
hyphenationCallback?: HyphenationCallback;
/**
* Specifies the minimum number of lines in a text element that must be shown at the bottom of a page or its container.
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
orphans?: number;
/**
* Specifies the minimum number of lines in a text element that must be shown at the top of a page or its container..
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
widows?: number;
}
interface SVGTextProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x: string | number;
y: string | number;
/**
* Override the default hyphenation-callback
* @see https://react-pdf.org/fonts#registerhyphenationcallback
*/
hyphenationCallback?: HyphenationCallback;
}
/**
* A React component for displaying text. Text supports nesting of other
* Text or Link components to create inline styling.
*/
export class Text extends React.Component<
React.PropsWithChildren<TextProps> | SVGTextProps
> {}
interface LinkProps extends NodeProps {
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
href?: string;
src?: string;
}
/**
* A React component for displaying a hyperlink. Links can be nested
* inside a Text component, or being inside any other valid primitive.
*/
export class Link extends React.Component<
React.PropsWithChildren<LinkProps>
> {}
interface FormCommonProps extends NodeProps {
name?: string;
required?: boolean;
noExport?: boolean;
readOnly?: boolean;
value?: number | string;
defaultValue?: number | string;
}
interface FieldSetProps extends NodeProps {
name: string;
}
export class FieldSet extends React.Component<
React.PropsWithChildren<FieldSetProps>
> {}
// see http://pdfkit.org/docs/forms.html#text_field_formatting
interface TextInputFormatting {
type:
| 'date'
| 'time'
| 'percent'
| 'number'
| 'zip'
| 'zipPlus4'
| 'phone'
| 'ssn';
param?: string;
nDec?: number;
sepComma?: boolean;
negStyle?: 'MinusBlack' | 'Red' | 'ParensBlack' | 'ParensRed';
currency?: string;
currencyPrepend?: boolean;
}
// see http://pdfkit.org/docs/forms.html#text_field_formatting
interface TextInputProps extends FormCommonProps {
align?: 'left' | 'center' | 'right';
multiline?: boolean;
/**
* The text will be masked (e.g. with asterisks).
*/
password?: boolean;
/**
* If set, text entered in the field is not spell-checked
*/
noSpell?: boolean;
format?: TextInputFormatting;
/**
* Sets the fontSize (default or 0 means auto sizing)
*/
fontSize?: number;
/**
* Sets the maximum length (characters) of the text in the field
*/
maxLength?: number;
}
export class TextInput extends React.Component<TextInputProps> {}
interface CheckboxProps extends FormCommonProps {
backgroundColor?: string;
borderColor?: string;
checked?: boolean;
onState?: string;
offState?: string;
xMark?: boolean;
}
export class Checkbox extends React.Component<CheckboxProps> {}
interface SelectAndListPropsBase extends FormCommonProps {
sort?: boolean;
edit?: boolean;
multiSelect?: boolean;
noSpell?: boolean;
select?: string[];
}
type SelectAndListPropsWithEdit = SelectAndListPropsBase & {
edit: true | false;
noSpell: boolean;
};
type SelectAndListPropsWithNoSpell = SelectAndListPropsBase & {
edit: boolean;
noSpell: true | false;
};
type SelectAndListProps =
| SelectAndListPropsWithEdit
| SelectAndListPropsWithNoSpell;
export class Select extends React.Component<SelectAndListProps> {}
export class List extends React.Component<SelectAndListProps> {}
interface NoteProps extends NodeProps {
children: string;
}
export class Note extends React.Component<NoteProps> {}
interface CanvasProps extends NodeProps {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
paint: (
painter: any,
availableWidth: number,
availableHeight: number,
) => null;
}
export class Canvas extends React.Component<CanvasProps> {}
interface SVGProps extends NodeProps, SVGPresentationAttributes {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
width?: string | number;
height?: string | number;
viewBox?: string;
preserveAspectRatio?: string;
}
/**
* The <SVG /> element is a container that defines a new coordinate system and viewport. It is used as the outermost element of SVG documents.
*/
export class Svg extends React.Component<React.PropsWithChildren<SVGProps>> {}
interface LineProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x1: string | number;
x2: string | number;
y1: string | number;
y2: string | number;
}
/**
* The <Line /> element is used to create a line.
*/
export class Line extends React.Component<
React.PropsWithChildren<LineProps>
> {}
interface PolylineProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
points: string;
}
/**
* The <Polyline /> element is used to create any shape that consists of only straight lines (that is connected at several points).
*/
export class Polyline extends React.Component<
React.PropsWithChildren<PolylineProps>
> {}
interface PolygonProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
points: string;
}
/**
* The <Polygon /> element is used to create a graphic that contains at least three sides.
* Polygons are made of straight lines, and the shape is "closed" (all the lines connect up).
*/
export class Polygon extends React.Component<
React.PropsWithChildren<PolygonProps>
> {}
interface PathProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
d: string;
}
/**
* The <Path /> element is the most powerful element in the SVG library of basic shapes. It can be used to create lines, curves, arcs, and more.
*/
export class Path extends React.Component<
React.PropsWithChildren<PathProps>
> {}
interface RectProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x?: string | number;
y?: string | number;
width: string | number;
height: string | number;
rx?: string | number;
ry?: string | number;
}
/**
* The <Rect /> element is used to create a rectangle and variations of a rectangle shape.
*/
export class Rect extends React.Component<
React.PropsWithChildren<RectProps>
> {}
interface CircleProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
cx?: string | number;
cy?: string | number;
r: string | number;
}
/**
* The <Circle /> element is used to create a circle.
*/
export class Circle extends React.Component<
React.PropsWithChildren<CircleProps>
> {}
interface EllipseProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
cx?: string | number;
cy?: string | number;
rx: string | number;
ry: string | number;
}
/**
* The <Ellipse /> element is used to create an ellipse.
* An ellipse is closely related to a circle. The difference is that an ellipse has an x and a y radius that differs from each other, while a circle has equal x and y radius.
*/
export class Ellipse extends React.Component<
React.PropsWithChildren<EllipseProps>
> {}
interface TspanProps extends SVGPresentationAttributes {
x?: string | number;
y?: string | number;
}
/**
* The <Tspan /> element defines a subtext within a <Text /> element or another <Tspan /> element.
* It allows for adjustment of the style and/or position of that subtext as needed.
*/
export class Tspan extends React.Component<
React.PropsWithChildren<TspanProps>
> {}
interface GProps extends SVGPresentationAttributes {
style?: Style;
}
/**
* The <G /> SVG element is a container used to group other SVG elements.
* Transformations applied to the <G /> element are performed on its child elements, and its attributes are inherited by its children.
*/
export class G extends React.Component<React.PropsWithChildren<GProps>> {}
interface StopProps {
offset: string | number;
stopColor: string;
stopOpacity?: string | number;
}
/**
* The SVG <Stop /> element defines a color and its position to use on a gradient. This element is always a child of a <LinearGradient /> or <RadialGradient /> element
*/
export class Stop extends React.Component<
React.PropsWithChildren<StopProps>
> {}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface DefsProps {}
/**
* The <Defs /> element is used to store graphical objects that will be used at a later time. Objects created inside a <Defs /> element are not rendered directly. To display them you have to reference them
*/
export class Defs extends React.Component<
React.PropsWithChildren<DefsProps>
> {}
interface ClipPathProps {
id?: string;
}
/**
* The <ClipPath /> SVG element defines a clipping path, to be used by the clipPath property.
* A clipping path restricts the region to which paint can be applied. Conceptually, parts of the drawing that lie outside of the region bounded by the clipping path are not drawn.
*/
export class ClipPath extends React.Component<
React.PropsWithChildren<ClipPathProps>
> {}
interface LinearGradientProps {
id: string;
x1?: string | number;
x2?: string | number;
y1?: string | number;
y2?: string | number;
xlinkHref?: string;
gradientTransform?: string;
gradientUnits?: 'userSpaceOnUse' | 'objectBoundingBox';
}
/**
* The <LinearGradient /> element lets authors define linear gradients that can be applied to fill or stroke of graphical elements.
*/
export class LinearGradient extends React.Component<
React.PropsWithChildren<LinearGradientProps>
> {}
interface RadialGradientProps {
id: string;
cx?: string | number;
cy?: string | number;
r?: string | number;
fx?: string | number;
fy?: string | number;
xlinkHref?: string;
gradientTransform?: string;
gradientUnits?: 'userSpaceOnUse' | 'objectBoundingBox';
}
/**
* The <RadialGradient /> element lets authors define radial gradients that can be applied to fill or stroke of graphical elements.
*/
export class RadialGradient extends React.Component<
React.PropsWithChildren<RadialGradientProps>
> {}
interface BlobProviderParams {
blob: Blob | null;
url: string | null;
loading: boolean;
error: Error | null;
}
interface BlobProviderProps {
document: React.ReactElement<DocumentProps>;
children: (params: BlobProviderParams) => React.ReactNode;
}
/**
* Easy and declarative way of getting document's blob data without
* showing it on screen.
* @see https://react-pdf.org/advanced#on-the-fly-rendering
* @platform web
*/
export class BlobProvider extends React.Component<BlobProviderProps> {}
interface PDFViewerProps {
width?: number | string;
height?: number | string;
style?: Style | Style[];
className?: string;
children?: React.ReactElement<DocumentProps>;
innerRef?: React.Ref<HTMLIFrameElement>;
showToolbar?: boolean;
}
/**
* Iframe PDF viewer for client-side generated documents.
* @platform web
*/
export class PDFViewer extends React.Component<PDFViewerProps> {}
interface PDFDownloadLinkProps
extends Omit<
React.AnchorHTMLAttributes<HTMLAnchorElement>,
'href' | 'children'
> {
/** PDF filename. Alias for anchor tag `download` attribute. */
fileName?: string;
document: React.ReactElement<DocumentProps>;
children?: React.ReactNode | React.FC<BlobProviderParams>;
onClick?: React.AnchorHTMLAttributes<HTMLAnchorElement>['onClick'] &
((
event: React.MouseEvent<HTMLAnchorElement, MouseEvent>,
instance: UsePDFInstance,
) => void);
}
/**
* Anchor tag to enable generate and download PDF documents on the fly.
* @see https://react-pdf.org/advanced#on-the-fly-rendering
* @platform web
*/
export class PDFDownloadLink extends React.Component<PDFDownloadLinkProps> {}
interface UsePDFInstance {
loading: boolean;
blob: Blob | null;
url: string | null;
error: string | null;
}
/**
* React hook for creating and updating a PDF document instance
* @platform web
*/
export function usePDF(options?: {
document?: React.ReactElement<DocumentProps>;
}): [
UsePDFInstance,
(newDocument: React.ReactElement<DocumentProps>) => void,
];
export const Font: FontStore;
export const StyleSheet: {
create: <T extends Styles>(styles: T) => T;
};
export const version: any;
export const PDFRenderer: any;
export const pdf: (initialValue?: React.ReactElement<DocumentProps>) => {
container: any;
isDirty: () => boolean;
toString: () => string;
toBlob: () => Promise<Blob>;
toBuffer: () => Promise<NodeJS.ReadableStream>;
on: (event: 'change', callback: () => void) => void;
updateContainer: (
document: React.ReactElement<any>,
callback?: () => void,
) => void;
removeListener: (event: 'change', callback: () => void) => void;
};
export const renderToStream: (
document: React.ReactElement<DocumentProps>,
) => Promise<NodeJS.ReadableStream>;
/**
* @deprecated use the `renderToBuffer` method
*/
export const renderToString: (
document: React.ReactElement<DocumentProps>,
) => Promise<string>;
export const renderToFile: (
document: React.ReactElement<DocumentProps>,
filePath: string,
callback?: (output: NodeJS.ReadableStream, _filePath: string) => any,
) => Promise<NodeJS.ReadableStream>;
const render: typeof renderToFile;
/**
* Render document into a nodejs buffer
* @platform node
*/
export const renderToBuffer: (
document: React.ReactElement<ReactPDF.DocumentProps>,
) => Promise<Buffer>;
}
+691
View File
@@ -0,0 +1,691 @@
/* eslint-disable max-classes-per-file */
import * as React from 'react';
import {
Style,
PageSize,
FontStore,
PDFVersion,
Orientation,
SourceObject,
HyphenationCallback,
SVGPresentationAttributes,
Bookmark,
PageLayout,
PageMode,
} from '@react-pdf/types';
declare class ReactPDF {
static default: typeof ReactPDF;
}
export = ReactPDF;
declare namespace ReactPDF {
interface Styles {
[key: string]: Style;
}
interface OnRenderProps {
blob?: Blob;
}
interface DocumentProps {
style?: Style | Style[];
title?: string;
author?: string;
subject?: string;
creator?: string;
keywords?: string;
producer?: string;
language?: string;
creationDate?: Date;
modificationDate?: Date;
pdfVersion?: PDFVersion;
pageMode?: PageMode;
pageLayout?: PageLayout;
onRender?: (props: OnRenderProps) => any;
}
/**
* This component represent the PDF document itself. It must be the root
* of your tree element structure, and under no circumstances should it be
* used as children of another react-pdf component. In addition, it should
* only have childs of type <Page />.
*/
export class Document extends React.Component<
React.PropsWithChildren<DocumentProps>
> {}
interface NodeProps {
id?: string;
style?: Style | Style[];
/**
* Render component in all wrapped pages.
* @see https://react-pdf.org/advanced#fixed-components
*/
fixed?: boolean;
/**
* Force the wrapping algorithm to start a new page when rendering the
* element.
* @see https://react-pdf.org/advanced#page-breaks
*/
break?: boolean;
/**
* Hint that no page wrapping should occur between all sibling elements following the element within n points
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
minPresenceAhead?: number;
}
interface PageProps extends NodeProps {
/**
* Enable page wrapping for this page.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
size?: PageSize;
orientation?: Orientation;
dpi?: number;
bookmark?: Bookmark;
}
/**
* Represents single page inside the PDF document, or a subset of them if
* using the wrapping feature. A <Document /> can contain as many pages as
* you want, but ensure not rendering a page inside any component besides
* Document.
*/
export class Page extends React.Component<
React.PropsWithChildren<PageProps>
> {}
interface ViewProps extends NodeProps {
id?: string;
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
render?: (props: {
pageNumber: number;
subPageNumber: number;
}) => React.ReactNode;
}
/**
* The most fundamental component for building a UI and is designed to be
* nested inside other views and can have 0 to many children.
*/
export class View extends React.Component<
React.PropsWithChildren<ViewProps>
> {}
interface BaseImageProps extends NodeProps {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
cache?: boolean;
}
interface ImageWithSrcProp extends BaseImageProps {
src: SourceObject;
}
interface ImageWithSourceProp extends BaseImageProps {
source: SourceObject;
}
type ImageProps = ImageWithSrcProp | ImageWithSourceProp;
/**
* A React component for displaying network or local (Node only) JPG or
* PNG images, as well as base64 encoded image strings.
*/
export class Image extends React.Component<ImageProps> {}
interface TextProps extends NodeProps {
id?: string;
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
render?: (props: {
pageNumber: number;
totalPages: number;
subPageNumber: number;
subPageTotalPages: number;
}) => React.ReactNode;
/**
* Override the default hyphenation-callback
* @see https://react-pdf.org/fonts#registerhyphenationcallback
*/
hyphenationCallback?: HyphenationCallback;
/**
* Specifies the minimum number of lines in a text element that must be shown at the bottom of a page or its container.
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
orphans?: number;
/**
* Specifies the minimum number of lines in a text element that must be shown at the top of a page or its container..
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
widows?: number;
}
interface SVGTextProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x: string | number;
y: string | number;
/**
* Override the default hyphenation-callback
* @see https://react-pdf.org/fonts#registerhyphenationcallback
*/
hyphenationCallback?: HyphenationCallback;
}
/**
* A React component for displaying text. Text supports nesting of other
* Text or Link components to create inline styling.
*/
export class Text extends React.Component<
React.PropsWithChildren<TextProps> | SVGTextProps
> {}
interface LinkProps extends NodeProps {
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
href?: string;
src?: string;
}
/**
* A React component for displaying a hyperlink. Links can be nested
* inside a Text component, or being inside any other valid primitive.
*/
export class Link extends React.Component<
React.PropsWithChildren<LinkProps>
> {}
interface FormCommonProps extends NodeProps {
name?: string;
required?: boolean;
noExport?: boolean;
readOnly?: boolean;
value?: number | string;
defaultValue?: number | string;
}
interface FieldSetProps extends NodeProps {
name: string;
}
export class FieldSet extends React.Component<
React.PropsWithChildren<FieldSetProps>
> {}
// see http://pdfkit.org/docs/forms.html#text_field_formatting
interface TextInputFormatting {
type:
| 'date'
| 'time'
| 'percent'
| 'number'
| 'zip'
| 'zipPlus4'
| 'phone'
| 'ssn';
param?: string;
nDec?: number;
sepComma?: boolean;
negStyle?: 'MinusBlack' | 'Red' | 'ParensBlack' | 'ParensRed';
currency?: string;
currencyPrepend?: boolean;
}
// see http://pdfkit.org/docs/forms.html#text_field_formatting
interface TextInputProps extends FormCommonProps {
align?: 'left' | 'center' | 'right';
multiline?: boolean;
/**
* The text will be masked (e.g. with asterisks).
*/
password?: boolean;
/**
* If set, text entered in the field is not spell-checked
*/
noSpell?: boolean;
format?: TextInputFormatting;
/**
* Sets the fontSize (default or 0 means auto sizing)
*/
fontSize?: number;
/**
* Sets the maximum length (characters) of the text in the field
*/
maxLength?: number;
}
export class TextInput extends React.Component<TextInputProps> {}
interface CheckboxProps extends FormCommonProps {
backgroundColor?: string;
borderColor?: string;
checked?: boolean;
onState?: string;
offState?: string;
xMark?: boolean;
}
export class Checkbox extends React.Component<CheckboxProps> {}
interface SelectAndListPropsBase extends FormCommonProps {
sort?: boolean;
edit?: boolean;
multiSelect?: boolean;
noSpell?: boolean;
select?: string[];
}
type SelectAndListPropsWithEdit = SelectAndListPropsBase & {
edit: true | false;
noSpell: boolean;
};
type SelectAndListPropsWithNoSpell = SelectAndListPropsBase & {
edit: boolean;
noSpell: true | false;
};
type SelectAndListProps =
| SelectAndListPropsWithEdit
| SelectAndListPropsWithNoSpell;
export class Select extends React.Component<SelectAndListProps> {}
export class List extends React.Component<SelectAndListProps> {}
interface NoteProps extends NodeProps {
children: string;
}
export class Note extends React.Component<NoteProps> {}
interface CanvasProps extends NodeProps {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
paint: (
painter: any,
availableWidth: number,
availableHeight: number,
) => null;
}
export class Canvas extends React.Component<CanvasProps> {}
interface SVGProps extends NodeProps, SVGPresentationAttributes {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
width?: string | number;
height?: string | number;
viewBox?: string;
preserveAspectRatio?: string;
}
/**
* The <SVG /> element is a container that defines a new coordinate system and viewport. It is used as the outermost element of SVG documents.
*/
export class Svg extends React.Component<React.PropsWithChildren<SVGProps>> {}
interface LineProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x1: string | number;
x2: string | number;
y1: string | number;
y2: string | number;
}
/**
* The <Line /> element is used to create a line.
*/
export class Line extends React.Component<
React.PropsWithChildren<LineProps>
> {}
interface PolylineProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
points: string;
}
/**
* The <Polyline /> element is used to create any shape that consists of only straight lines (that is connected at several points).
*/
export class Polyline extends React.Component<
React.PropsWithChildren<PolylineProps>
> {}
interface PolygonProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
points: string;
}
/**
* The <Polygon /> element is used to create a graphic that contains at least three sides.
* Polygons are made of straight lines, and the shape is "closed" (all the lines connect up).
*/
export class Polygon extends React.Component<
React.PropsWithChildren<PolygonProps>
> {}
interface PathProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
d: string;
}
/**
* The <Path /> element is the most powerful element in the SVG library of basic shapes. It can be used to create lines, curves, arcs, and more.
*/
export class Path extends React.Component<
React.PropsWithChildren<PathProps>
> {}
interface RectProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x?: string | number;
y?: string | number;
width: string | number;
height: string | number;
rx?: string | number;
ry?: string | number;
}
/**
* The <Rect /> element is used to create a rectangle and variations of a rectangle shape.
*/
export class Rect extends React.Component<
React.PropsWithChildren<RectProps>
> {}
interface CircleProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
cx?: string | number;
cy?: string | number;
r: string | number;
}
/**
* The <Circle /> element is used to create a circle.
*/
export class Circle extends React.Component<
React.PropsWithChildren<CircleProps>
> {}
interface EllipseProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
cx?: string | number;
cy?: string | number;
rx: string | number;
ry: string | number;
}
/**
* The <Ellipse /> element is used to create an ellipse.
* An ellipse is closely related to a circle. The difference is that an ellipse has an x and a y radius that differs from each other, while a circle has equal x and y radius.
*/
export class Ellipse extends React.Component<
React.PropsWithChildren<EllipseProps>
> {}
interface TspanProps extends SVGPresentationAttributes {
x?: string | number;
y?: string | number;
}
/**
* The <Tspan /> element defines a subtext within a <Text /> element or another <Tspan /> element.
* It allows for adjustment of the style and/or position of that subtext as needed.
*/
export class Tspan extends React.Component<
React.PropsWithChildren<TspanProps>
> {}
interface GProps extends SVGPresentationAttributes {
style?: Style;
}
/**
* The <G /> SVG element is a container used to group other SVG elements.
* Transformations applied to the <G /> element are performed on its child elements, and its attributes are inherited by its children.
*/
export class G extends React.Component<React.PropsWithChildren<GProps>> {}
interface StopProps {
offset: string | number;
stopColor: string;
stopOpacity?: string | number;
}
/**
* The SVG <Stop /> element defines a color and its position to use on a gradient. This element is always a child of a <LinearGradient /> or <RadialGradient /> element
*/
export class Stop extends React.Component<
React.PropsWithChildren<StopProps>
> {}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface DefsProps {}
/**
* The <Defs /> element is used to store graphical objects that will be used at a later time. Objects created inside a <Defs /> element are not rendered directly. To display them you have to reference them
*/
export class Defs extends React.Component<
React.PropsWithChildren<DefsProps>
> {}
interface ClipPathProps {
id?: string;
}
/**
* The <ClipPath /> SVG element defines a clipping path, to be used by the clipPath property.
* A clipping path restricts the region to which paint can be applied. Conceptually, parts of the drawing that lie outside of the region bounded by the clipping path are not drawn.
*/
export class ClipPath extends React.Component<
React.PropsWithChildren<ClipPathProps>
> {}
interface LinearGradientProps {
id: string;
x1?: string | number;
x2?: string | number;
y1?: string | number;
y2?: string | number;
xlinkHref?: string;
gradientTransform?: string;
gradientUnits?: 'userSpaceOnUse' | 'objectBoundingBox';
}
/**
* The <LinearGradient /> element lets authors define linear gradients that can be applied to fill or stroke of graphical elements.
*/
export class LinearGradient extends React.Component<
React.PropsWithChildren<LinearGradientProps>
> {}
interface RadialGradientProps {
id: string;
cx?: string | number;
cy?: string | number;
r?: string | number;
fx?: string | number;
fy?: string | number;
xlinkHref?: string;
gradientTransform?: string;
gradientUnits?: 'userSpaceOnUse' | 'objectBoundingBox';
}
/**
* The <RadialGradient /> element lets authors define radial gradients that can be applied to fill or stroke of graphical elements.
*/
export class RadialGradient extends React.Component<
React.PropsWithChildren<RadialGradientProps>
> {}
interface BlobProviderParams {
blob: Blob | null;
url: string | null;
loading: boolean;
error: Error | null;
}
interface BlobProviderProps {
document: React.ReactElement<DocumentProps>;
children: (params: BlobProviderParams) => React.ReactNode;
}
/**
* Easy and declarative way of getting document's blob data without
* showing it on screen.
* @see https://react-pdf.org/advanced#on-the-fly-rendering
* @platform web
*/
export class BlobProvider extends React.Component<BlobProviderProps> {}
interface PDFViewerProps {
width?: number | string;
height?: number | string;
style?: Style | Style[];
className?: string;
children?: React.ReactElement<DocumentProps>;
innerRef?: React.Ref<HTMLIFrameElement>;
showToolbar?: boolean;
}
/**
* Iframe PDF viewer for client-side generated documents.
* @platform web
*/
export class PDFViewer extends React.Component<PDFViewerProps> {}
interface PDFDownloadLinkProps
extends Omit<
React.AnchorHTMLAttributes<HTMLAnchorElement>,
'href' | 'children'
> {
/** PDF filename. Alias for anchor tag `download` attribute. */
fileName?: string;
document: React.ReactElement<DocumentProps>;
children?: React.ReactNode | React.FC<BlobProviderParams>;
onClick?: React.AnchorHTMLAttributes<HTMLAnchorElement>['onClick'] &
((
event: React.MouseEvent<HTMLAnchorElement, MouseEvent>,
instance: UsePDFInstance,
) => void);
}
/**
* Anchor tag to enable generate and download PDF documents on the fly.
* @see https://react-pdf.org/advanced#on-the-fly-rendering
* @platform web
*/
export class PDFDownloadLink extends React.Component<PDFDownloadLinkProps> {}
interface UsePDFInstance {
loading: boolean;
blob: Blob | null;
url: string | null;
error: string | null;
}
/**
* React hook for creating and updating a PDF document instance
* @platform web
*/
export function usePDF(options?: {
document?: React.ReactElement<DocumentProps>;
}): [
UsePDFInstance,
(newDocument: React.ReactElement<DocumentProps>) => void,
];
export const Font: FontStore;
export const StyleSheet: {
create: <T extends Styles>(styles: T) => T;
};
export const version: any;
export const PDFRenderer: any;
export const pdf: (initialValue?: React.ReactElement<DocumentProps>) => {
container: any;
isDirty: () => boolean;
toString: () => string;
toBlob: () => Promise<Blob>;
toBuffer: () => Promise<NodeJS.ReadableStream>;
on: (event: 'change', callback: () => void) => void;
updateContainer: (
document: React.ReactElement<any>,
callback?: () => void,
) => void;
removeListener: (event: 'change', callback: () => void) => void;
};
export const renderToStream: (
document: React.ReactElement<DocumentProps>,
) => Promise<NodeJS.ReadableStream>;
/**
* @deprecated use the `renderToBuffer` method
*/
export const renderToString: (
document: React.ReactElement<DocumentProps>,
) => Promise<string>;
export const renderToFile: (
document: React.ReactElement<DocumentProps>,
filePath: string,
callback?: (output: NodeJS.ReadableStream, _filePath: string) => any,
) => Promise<NodeJS.ReadableStream>;
const render: typeof renderToFile;
/**
* Render document into a nodejs buffer
* @platform node
*/
export const renderToBuffer: (
document: React.ReactElement<ReactPDF.DocumentProps>,
) => Promise<Buffer>;
}
+691
View File
@@ -0,0 +1,691 @@
/* eslint-disable max-classes-per-file */
import * as React from 'react';
import {
Style,
PageSize,
FontStore,
PDFVersion,
Orientation,
SourceObject,
HyphenationCallback,
SVGPresentationAttributes,
Bookmark,
PageLayout,
PageMode,
} from '@react-pdf/types';
declare class ReactPDF {
static default: typeof ReactPDF;
}
export = ReactPDF;
declare namespace ReactPDF {
interface Styles {
[key: string]: Style;
}
interface OnRenderProps {
blob?: Blob;
}
interface DocumentProps {
style?: Style | Style[];
title?: string;
author?: string;
subject?: string;
creator?: string;
keywords?: string;
producer?: string;
language?: string;
creationDate?: Date;
modificationDate?: Date;
pdfVersion?: PDFVersion;
pageMode?: PageMode;
pageLayout?: PageLayout;
onRender?: (props: OnRenderProps) => any;
}
/**
* This component represent the PDF document itself. It must be the root
* of your tree element structure, and under no circumstances should it be
* used as children of another react-pdf component. In addition, it should
* only have childs of type <Page />.
*/
export class Document extends React.Component<
React.PropsWithChildren<DocumentProps>
> {}
interface NodeProps {
id?: string;
style?: Style | Style[];
/**
* Render component in all wrapped pages.
* @see https://react-pdf.org/advanced#fixed-components
*/
fixed?: boolean;
/**
* Force the wrapping algorithm to start a new page when rendering the
* element.
* @see https://react-pdf.org/advanced#page-breaks
*/
break?: boolean;
/**
* Hint that no page wrapping should occur between all sibling elements following the element within n points
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
minPresenceAhead?: number;
}
interface PageProps extends NodeProps {
/**
* Enable page wrapping for this page.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
size?: PageSize;
orientation?: Orientation;
dpi?: number;
bookmark?: Bookmark;
}
/**
* Represents single page inside the PDF document, or a subset of them if
* using the wrapping feature. A <Document /> can contain as many pages as
* you want, but ensure not rendering a page inside any component besides
* Document.
*/
export class Page extends React.Component<
React.PropsWithChildren<PageProps>
> {}
interface ViewProps extends NodeProps {
id?: string;
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
render?: (props: {
pageNumber: number;
subPageNumber: number;
}) => React.ReactNode;
}
/**
* The most fundamental component for building a UI and is designed to be
* nested inside other views and can have 0 to many children.
*/
export class View extends React.Component<
React.PropsWithChildren<ViewProps>
> {}
interface BaseImageProps extends NodeProps {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
cache?: boolean;
}
interface ImageWithSrcProp extends BaseImageProps {
src: SourceObject;
}
interface ImageWithSourceProp extends BaseImageProps {
source: SourceObject;
}
type ImageProps = ImageWithSrcProp | ImageWithSourceProp;
/**
* A React component for displaying network or local (Node only) JPG or
* PNG images, as well as base64 encoded image strings.
*/
export class Image extends React.Component<ImageProps> {}
interface TextProps extends NodeProps {
id?: string;
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
render?: (props: {
pageNumber: number;
totalPages: number;
subPageNumber: number;
subPageTotalPages: number;
}) => React.ReactNode;
/**
* Override the default hyphenation-callback
* @see https://react-pdf.org/fonts#registerhyphenationcallback
*/
hyphenationCallback?: HyphenationCallback;
/**
* Specifies the minimum number of lines in a text element that must be shown at the bottom of a page or its container.
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
orphans?: number;
/**
* Specifies the minimum number of lines in a text element that must be shown at the top of a page or its container..
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
widows?: number;
}
interface SVGTextProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x: string | number;
y: string | number;
/**
* Override the default hyphenation-callback
* @see https://react-pdf.org/fonts#registerhyphenationcallback
*/
hyphenationCallback?: HyphenationCallback;
}
/**
* A React component for displaying text. Text supports nesting of other
* Text or Link components to create inline styling.
*/
export class Text extends React.Component<
React.PropsWithChildren<TextProps> | SVGTextProps
> {}
interface LinkProps extends NodeProps {
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
href?: string;
src?: string;
}
/**
* A React component for displaying a hyperlink. Links can be nested
* inside a Text component, or being inside any other valid primitive.
*/
export class Link extends React.Component<
React.PropsWithChildren<LinkProps>
> {}
interface FormCommonProps extends NodeProps {
name?: string;
required?: boolean;
noExport?: boolean;
readOnly?: boolean;
value?: number | string;
defaultValue?: number | string;
}
interface FieldSetProps extends NodeProps {
name: string;
}
export class FieldSet extends React.Component<
React.PropsWithChildren<FieldSetProps>
> {}
// see http://pdfkit.org/docs/forms.html#text_field_formatting
interface TextInputFormatting {
type:
| 'date'
| 'time'
| 'percent'
| 'number'
| 'zip'
| 'zipPlus4'
| 'phone'
| 'ssn';
param?: string;
nDec?: number;
sepComma?: boolean;
negStyle?: 'MinusBlack' | 'Red' | 'ParensBlack' | 'ParensRed';
currency?: string;
currencyPrepend?: boolean;
}
// see http://pdfkit.org/docs/forms.html#text_field_formatting
interface TextInputProps extends FormCommonProps {
align?: 'left' | 'center' | 'right';
multiline?: boolean;
/**
* The text will be masked (e.g. with asterisks).
*/
password?: boolean;
/**
* If set, text entered in the field is not spell-checked
*/
noSpell?: boolean;
format?: TextInputFormatting;
/**
* Sets the fontSize (default or 0 means auto sizing)
*/
fontSize?: number;
/**
* Sets the maximum length (characters) of the text in the field
*/
maxLength?: number;
}
export class TextInput extends React.Component<TextInputProps> {}
interface CheckboxProps extends FormCommonProps {
backgroundColor?: string;
borderColor?: string;
checked?: boolean;
onState?: string;
offState?: string;
xMark?: boolean;
}
export class Checkbox extends React.Component<CheckboxProps> {}
interface SelectAndListPropsBase extends FormCommonProps {
sort?: boolean;
edit?: boolean;
multiSelect?: boolean;
noSpell?: boolean;
select?: string[];
}
type SelectAndListPropsWithEdit = SelectAndListPropsBase & {
edit: true | false;
noSpell: boolean;
};
type SelectAndListPropsWithNoSpell = SelectAndListPropsBase & {
edit: boolean;
noSpell: true | false;
};
type SelectAndListProps =
| SelectAndListPropsWithEdit
| SelectAndListPropsWithNoSpell;
export class Select extends React.Component<SelectAndListProps> {}
export class List extends React.Component<SelectAndListProps> {}
interface NoteProps extends NodeProps {
children: string;
}
export class Note extends React.Component<NoteProps> {}
interface CanvasProps extends NodeProps {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
paint: (
painter: any,
availableWidth: number,
availableHeight: number,
) => null;
}
export class Canvas extends React.Component<CanvasProps> {}
interface SVGProps extends NodeProps, SVGPresentationAttributes {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
width?: string | number;
height?: string | number;
viewBox?: string;
preserveAspectRatio?: string;
}
/**
* The <SVG /> element is a container that defines a new coordinate system and viewport. It is used as the outermost element of SVG documents.
*/
export class Svg extends React.Component<React.PropsWithChildren<SVGProps>> {}
interface LineProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x1: string | number;
x2: string | number;
y1: string | number;
y2: string | number;
}
/**
* The <Line /> element is used to create a line.
*/
export class Line extends React.Component<
React.PropsWithChildren<LineProps>
> {}
interface PolylineProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
points: string;
}
/**
* The <Polyline /> element is used to create any shape that consists of only straight lines (that is connected at several points).
*/
export class Polyline extends React.Component<
React.PropsWithChildren<PolylineProps>
> {}
interface PolygonProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
points: string;
}
/**
* The <Polygon /> element is used to create a graphic that contains at least three sides.
* Polygons are made of straight lines, and the shape is "closed" (all the lines connect up).
*/
export class Polygon extends React.Component<
React.PropsWithChildren<PolygonProps>
> {}
interface PathProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
d: string;
}
/**
* The <Path /> element is the most powerful element in the SVG library of basic shapes. It can be used to create lines, curves, arcs, and more.
*/
export class Path extends React.Component<
React.PropsWithChildren<PathProps>
> {}
interface RectProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x?: string | number;
y?: string | number;
width: string | number;
height: string | number;
rx?: string | number;
ry?: string | number;
}
/**
* The <Rect /> element is used to create a rectangle and variations of a rectangle shape.
*/
export class Rect extends React.Component<
React.PropsWithChildren<RectProps>
> {}
interface CircleProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
cx?: string | number;
cy?: string | number;
r: string | number;
}
/**
* The <Circle /> element is used to create a circle.
*/
export class Circle extends React.Component<
React.PropsWithChildren<CircleProps>
> {}
interface EllipseProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
cx?: string | number;
cy?: string | number;
rx: string | number;
ry: string | number;
}
/**
* The <Ellipse /> element is used to create an ellipse.
* An ellipse is closely related to a circle. The difference is that an ellipse has an x and a y radius that differs from each other, while a circle has equal x and y radius.
*/
export class Ellipse extends React.Component<
React.PropsWithChildren<EllipseProps>
> {}
interface TspanProps extends SVGPresentationAttributes {
x?: string | number;
y?: string | number;
}
/**
* The <Tspan /> element defines a subtext within a <Text /> element or another <Tspan /> element.
* It allows for adjustment of the style and/or position of that subtext as needed.
*/
export class Tspan extends React.Component<
React.PropsWithChildren<TspanProps>
> {}
interface GProps extends SVGPresentationAttributes {
style?: Style;
}
/**
* The <G /> SVG element is a container used to group other SVG elements.
* Transformations applied to the <G /> element are performed on its child elements, and its attributes are inherited by its children.
*/
export class G extends React.Component<React.PropsWithChildren<GProps>> {}
interface StopProps {
offset: string | number;
stopColor: string;
stopOpacity?: string | number;
}
/**
* The SVG <Stop /> element defines a color and its position to use on a gradient. This element is always a child of a <LinearGradient /> or <RadialGradient /> element
*/
export class Stop extends React.Component<
React.PropsWithChildren<StopProps>
> {}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface DefsProps {}
/**
* The <Defs /> element is used to store graphical objects that will be used at a later time. Objects created inside a <Defs /> element are not rendered directly. To display them you have to reference them
*/
export class Defs extends React.Component<
React.PropsWithChildren<DefsProps>
> {}
interface ClipPathProps {
id?: string;
}
/**
* The <ClipPath /> SVG element defines a clipping path, to be used by the clipPath property.
* A clipping path restricts the region to which paint can be applied. Conceptually, parts of the drawing that lie outside of the region bounded by the clipping path are not drawn.
*/
export class ClipPath extends React.Component<
React.PropsWithChildren<ClipPathProps>
> {}
interface LinearGradientProps {
id: string;
x1?: string | number;
x2?: string | number;
y1?: string | number;
y2?: string | number;
xlinkHref?: string;
gradientTransform?: string;
gradientUnits?: 'userSpaceOnUse' | 'objectBoundingBox';
}
/**
* The <LinearGradient /> element lets authors define linear gradients that can be applied to fill or stroke of graphical elements.
*/
export class LinearGradient extends React.Component<
React.PropsWithChildren<LinearGradientProps>
> {}
interface RadialGradientProps {
id: string;
cx?: string | number;
cy?: string | number;
r?: string | number;
fx?: string | number;
fy?: string | number;
xlinkHref?: string;
gradientTransform?: string;
gradientUnits?: 'userSpaceOnUse' | 'objectBoundingBox';
}
/**
* The <RadialGradient /> element lets authors define radial gradients that can be applied to fill or stroke of graphical elements.
*/
export class RadialGradient extends React.Component<
React.PropsWithChildren<RadialGradientProps>
> {}
interface BlobProviderParams {
blob: Blob | null;
url: string | null;
loading: boolean;
error: Error | null;
}
interface BlobProviderProps {
document: React.ReactElement<DocumentProps>;
children: (params: BlobProviderParams) => React.ReactNode;
}
/**
* Easy and declarative way of getting document's blob data without
* showing it on screen.
* @see https://react-pdf.org/advanced#on-the-fly-rendering
* @platform web
*/
export class BlobProvider extends React.Component<BlobProviderProps> {}
interface PDFViewerProps {
width?: number | string;
height?: number | string;
style?: Style | Style[];
className?: string;
children?: React.ReactElement<DocumentProps>;
innerRef?: React.Ref<HTMLIFrameElement>;
showToolbar?: boolean;
}
/**
* Iframe PDF viewer for client-side generated documents.
* @platform web
*/
export class PDFViewer extends React.Component<PDFViewerProps> {}
interface PDFDownloadLinkProps
extends Omit<
React.AnchorHTMLAttributes<HTMLAnchorElement>,
'href' | 'children'
> {
/** PDF filename. Alias for anchor tag `download` attribute. */
fileName?: string;
document: React.ReactElement<DocumentProps>;
children?: React.ReactNode | React.FC<BlobProviderParams>;
onClick?: React.AnchorHTMLAttributes<HTMLAnchorElement>['onClick'] &
((
event: React.MouseEvent<HTMLAnchorElement, MouseEvent>,
instance: UsePDFInstance,
) => void);
}
/**
* Anchor tag to enable generate and download PDF documents on the fly.
* @see https://react-pdf.org/advanced#on-the-fly-rendering
* @platform web
*/
export class PDFDownloadLink extends React.Component<PDFDownloadLinkProps> {}
interface UsePDFInstance {
loading: boolean;
blob: Blob | null;
url: string | null;
error: string | null;
}
/**
* React hook for creating and updating a PDF document instance
* @platform web
*/
export function usePDF(options?: {
document?: React.ReactElement<DocumentProps>;
}): [
UsePDFInstance,
(newDocument: React.ReactElement<DocumentProps>) => void,
];
export const Font: FontStore;
export const StyleSheet: {
create: <T extends Styles>(styles: T) => T;
};
export const version: any;
export const PDFRenderer: any;
export const pdf: (initialValue?: React.ReactElement<DocumentProps>) => {
container: any;
isDirty: () => boolean;
toString: () => string;
toBlob: () => Promise<Blob>;
toBuffer: () => Promise<NodeJS.ReadableStream>;
on: (event: 'change', callback: () => void) => void;
updateContainer: (
document: React.ReactElement<any>,
callback?: () => void,
) => void;
removeListener: (event: 'change', callback: () => void) => void;
};
export const renderToStream: (
document: React.ReactElement<DocumentProps>,
) => Promise<NodeJS.ReadableStream>;
/**
* @deprecated use the `renderToBuffer` method
*/
export const renderToString: (
document: React.ReactElement<DocumentProps>,
) => Promise<string>;
export const renderToFile: (
document: React.ReactElement<DocumentProps>,
filePath: string,
callback?: (output: NodeJS.ReadableStream, _filePath: string) => any,
) => Promise<NodeJS.ReadableStream>;
const render: typeof renderToFile;
/**
* Render document into a nodejs buffer
* @platform node
*/
export const renderToBuffer: (
document: React.ReactElement<ReactPDF.DocumentProps>,
) => Promise<Buffer>;
}
+467
View File
@@ -0,0 +1,467 @@
import * as primitives from '@react-pdf/primitives';
export * from '@react-pdf/primitives';
import queue from 'queue';
import { useRef, useState, useEffect, useCallback } from 'react';
import FontStore from '@react-pdf/font';
import renderPDF from '@react-pdf/render';
import PDFDocument from '@react-pdf/pdfkit';
import layoutDocument from '@react-pdf/layout';
import { upperFirst } from '@react-pdf/fns';
import Reconciler from '@react-pdf/reconciler';
import { jsx } from 'react/jsx-runtime';
const omitNils = object => Object.fromEntries(Object.entries(object).filter(_ref => {
let [, value] = _ref;
return value !== undefined;
}));
const createInstance = (type, _ref) => {
let {
style,
children,
...props
} = _ref;
return {
type,
box: {},
style: style || {},
props: props || {},
children: []
};
};
const createTextInstance = text => ({
type: 'TEXT_INSTANCE',
value: text
});
const appendChild = (parent, child) => {
const isParentText = parent.type === 'TEXT' || parent.type === 'LINK' || parent.type === 'TSPAN' || parent.type === 'NOTE';
const isChildTextInstance = child.type === 'TEXT_INSTANCE';
const isOrphanTextInstance = isChildTextInstance && !isParentText;
// Ignore orphan text instances.
// Caused by cases such as <>{name && <Text>{name}</Text>}</>
if (isOrphanTextInstance) {
console.warn(`Invalid '${child.value}' string child outside <Text> component`);
return;
}
parent.children.push(child);
};
const appendChildToContainer = (parentInstance, child) => {
if (parentInstance.type === 'ROOT') {
parentInstance.document = child;
} else {
appendChild(parentInstance, child);
}
};
const insertBefore = (parentInstance, child, beforeChild) => {
var _parentInstance$child;
const index = (_parentInstance$child = parentInstance.children) === null || _parentInstance$child === void 0 ? void 0 : _parentInstance$child.indexOf(beforeChild);
if (index === undefined) return;
if (index !== -1 && child) parentInstance.children.splice(index, 0, child);
};
const removeChild = (parentInstance, child) => {
var _parentInstance$child2;
const index = (_parentInstance$child2 = parentInstance.children) === null || _parentInstance$child2 === void 0 ? void 0 : _parentInstance$child2.indexOf(child);
if (index === undefined) return;
if (index !== -1) parentInstance.children.splice(index, 1);
};
const removeChildFromContainer = (parentInstance, child) => {
var _parentInstance$child3;
const index = (_parentInstance$child3 = parentInstance.children) === null || _parentInstance$child3 === void 0 ? void 0 : _parentInstance$child3.indexOf(child);
if (index === undefined) return;
if (index !== -1) parentInstance.children.splice(index, 1);
};
const commitTextUpdate = (textInstance, oldText, newText) => {
textInstance.value = newText;
};
const commitUpdate = (instance, updatePayload, type, oldProps, newProps) => {
const {
style,
...props
} = newProps;
instance.props = props;
instance.style = style;
};
const createRenderer = _ref2 => {
let {
onChange = () => {}
} = _ref2;
return Reconciler({
appendChild,
appendChildToContainer,
commitTextUpdate,
commitUpdate,
createInstance,
createTextInstance,
insertBefore,
removeChild,
removeChildFromContainer,
resetAfterCommit: onChange
});
};
var version$1 = "4.3.0";
var packageJson = {
version: version$1};
const {
version
} = packageJson;
const fontStore = new FontStore();
// We must keep a single renderer instance, otherwise React will complain
let renderer;
// The pdf instance acts as an event emitter for DOM usage.
// We only want to trigger an update when PDF content changes
const events = {};
const pdf = initialValue => {
const onChange = () => {
var _events$change;
const listeners = ((_events$change = events.change) === null || _events$change === void 0 ? void 0 : _events$change.slice()) || [];
for (let i = 0; i < listeners.length; i += 1) listeners[i]();
};
const container = {
type: 'ROOT',
document: null
};
renderer = renderer || createRenderer({
onChange
});
const mountNode = renderer.createContainer(container);
const updateContainer = (doc, callback) => {
renderer.updateContainer(doc, mountNode, null, callback);
};
if (initialValue) updateContainer(initialValue);
const render = async function (compress) {
if (compress === void 0) {
compress = true;
}
const props = container.document.props || {};
const {
pdfVersion,
language,
pageLayout,
pageMode,
title,
author,
subject,
keyboards,
creator = 'react-pdf',
producer = 'react-pdf',
creationDate = new Date(),
modificationDate
} = props;
const ctx = new PDFDocument({
compress,
pdfVersion,
lang: language,
displayTitle: true,
autoFirstPage: false,
info: omitNils({
Title: title,
Author: author,
Subject: subject,
Keywords: keyboards,
Creator: creator,
Producer: producer,
CreationDate: creationDate,
ModificationDate: modificationDate
})
});
if (pageLayout) {
ctx._root.data.PageLayout = upperFirst(pageLayout);
}
if (pageMode) {
ctx._root.data.PageMode = upperFirst(pageMode);
}
const layout = await layoutDocument(container.document, fontStore);
const fileStream = renderPDF(ctx, layout);
return {
layout,
fileStream
};
};
const callOnRender = function (params) {
if (params === void 0) {
params = {};
}
if (container.document.props.onRender) {
container.document.props.onRender(params);
}
};
const toBlob = async () => {
const chunks = [];
const {
layout: _INTERNAL__LAYOUT__DATA_,
fileStream: instance
} = await render();
return new Promise((resolve, reject) => {
instance.on('data', chunk => {
chunks.push(chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk));
});
instance.on('end', () => {
try {
const blob = new Blob(chunks, {
type: 'application/pdf'
});
callOnRender({
blob,
_INTERNAL__LAYOUT__DATA_
});
resolve(blob);
} catch (error) {
reject(error);
}
});
});
};
// TODO: rename this method to `toStream` in next major release, because it return stream not a buffer
const toBuffer = async () => {
const {
layout: _INTERNAL__LAYOUT__DATA_,
fileStream
} = await render();
callOnRender({
_INTERNAL__LAYOUT__DATA_
});
return fileStream;
};
/*
* TODO: remove this method in next major release. it is buggy
* see
* - https://github.com/diegomura/react-pdf/issues/2112
* - https://github.com/diegomura/react-pdf/issues/2095
*/
const toString = async () => {
if (process.env.NODE_ENV === 'development') {
console.warn('`toString` is deprecated and will be removed in next major release');
}
let result = '';
const {
fileStream: instance
} = await render(false); // For some reason, when rendering to string if compress=true the document is blank
return new Promise((resolve, reject) => {
try {
instance.on('data', buffer => {
result += buffer;
});
instance.on('end', () => {
callOnRender();
resolve(result);
});
} catch (error) {
reject(error);
}
});
};
const on = (event, listener) => {
if (!events[event]) events[event] = [];
events[event].push(listener);
};
const removeListener = (event, listener) => {
if (!events[event]) return;
const idx = events[event].indexOf(listener);
if (idx > -1) events[event].splice(idx, 1);
};
return {
on,
container,
toBlob,
toBuffer,
toString,
removeListener,
updateContainer
};
};
const Font = fontStore;
const StyleSheet = {
create: s => s
};
/**
* PDF hook
*
* @param {Object} [options] hook options
* @returns {[Object, Function]} pdf state and update function
*/
const usePDF = function (_temp) {
let {
document
} = _temp === void 0 ? {} : _temp;
const pdfInstance = useRef(null);
const [state, setState] = useState({
url: null,
blob: null,
error: null,
loading: !!document
});
// Setup rendering queue
useEffect(() => {
const renderQueue = queue({
autostart: true,
concurrency: 1
});
const queueDocumentRender = () => {
setState(prev => ({
...prev,
loading: true
}));
renderQueue.splice(0, renderQueue.length, () => state.error ? Promise.resolve() : pdfInstance.current.toBlob());
};
const onRenderFailed = error => {
console.error(error);
setState(prev => ({
...prev,
loading: false,
error
}));
};
const onRenderSuccessful = blob => {
setState({
blob,
error: null,
loading: false,
url: URL.createObjectURL(blob)
});
};
pdfInstance.current = pdf();
pdfInstance.current.on('change', queueDocumentRender);
if (document) {
pdfInstance.current.updateContainer(document);
}
renderQueue.on('error', onRenderFailed);
renderQueue.on('success', onRenderSuccessful);
return () => {
renderQueue.end();
pdfInstance.current.removeListener('change', queueDocumentRender);
};
}, []);
// Revoke old unused url instances
useEffect(() => {
return () => {
if (state.url) {
URL.revokeObjectURL(state.url);
}
};
}, [state.url]);
const update = useCallback(newDoc => {
pdfInstance.current.updateContainer(newDoc);
}, []);
return [state, update];
};
const PDFViewer = _ref => {
let {
title,
style,
className,
children,
innerRef,
showToolbar = true,
...props
} = _ref;
const [instance, updateInstance] = usePDF();
useEffect(() => updateInstance(children), [children]);
const src = instance.url ? `${instance.url}#toolbar=${showToolbar ? 1 : 0}` : null;
return /*#__PURE__*/jsx("iframe", {
src: src,
title: title,
ref: innerRef,
style: style,
className: className,
...props
});
};
const BlobProvider = _ref => {
let {
document: doc,
children
} = _ref;
const [instance, updateInstance] = usePDF();
useEffect(() => updateInstance(doc), [doc]);
if (!doc) {
console.warn('You should pass a valid document to BlobProvider');
return null;
}
return children(instance);
};
const PDFDownloadLink = _ref => {
let {
fileName = 'document.pdf',
document: doc,
children,
onClick,
href,
...rest
} = _ref;
const [instance, updateInstance] = usePDF();
useEffect(() => updateInstance(doc), [doc]);
if (!doc) {
console.warn('You should pass a valid document to PDFDownloadLink');
return null;
}
const handleDownloadIE = () => {
if (instance && window.navigator.msSaveBlob) {
// IE
window.navigator.msSaveBlob(instance.blob, fileName);
}
};
const handleClick = event => {
handleDownloadIE();
if (typeof onClick === 'function') onClick(event, instance);
};
return /*#__PURE__*/jsx("a", {
href: instance.url,
download: fileName,
onClick: handleClick,
...rest,
children: typeof children === 'function' ? children(instance) : children
});
};
const throwEnvironmentError = name => {
throw new Error(`${name} is a Node specific API. You're either using this method in a browser, or your bundler is not loading react-pdf from the appropriate web build.`);
};
const renderToStream = () => {
throwEnvironmentError('renderToStream');
};
const renderToBuffer = () => {
throwEnvironmentError('renderToBuffer');
};
const renderToString = () => {
throwEnvironmentError('renderToString');
};
const renderToFile = () => {
throwEnvironmentError('renderToFile');
};
const render = () => {
throwEnvironmentError('render');
};
// TODO: remove this default export in next major release because it breaks tree-shacking
var index = {
pdf,
usePDF,
Font,
version,
StyleSheet,
PDFViewer,
BlobProvider,
PDFDownloadLink,
renderToStream,
renderToString,
renderToFile,
render,
...primitives
};
export { BlobProvider, Font, PDFDownloadLink, PDFViewer, StyleSheet, createRenderer, index as default, pdf, render, renderToBuffer, renderToFile, renderToStream, renderToString, usePDF, version };
//# sourceMappingURL=react-pdf.browser.js.map
File diff suppressed because one or more lines are too long
+691
View File
@@ -0,0 +1,691 @@
/* eslint-disable max-classes-per-file */
import * as React from 'react';
import {
Style,
PageSize,
FontStore,
PDFVersion,
Orientation,
SourceObject,
HyphenationCallback,
SVGPresentationAttributes,
Bookmark,
PageLayout,
PageMode,
} from '@react-pdf/types';
declare class ReactPDF {
static default: typeof ReactPDF;
}
export = ReactPDF;
declare namespace ReactPDF {
interface Styles {
[key: string]: Style;
}
interface OnRenderProps {
blob?: Blob;
}
interface DocumentProps {
style?: Style | Style[];
title?: string;
author?: string;
subject?: string;
creator?: string;
keywords?: string;
producer?: string;
language?: string;
creationDate?: Date;
modificationDate?: Date;
pdfVersion?: PDFVersion;
pageMode?: PageMode;
pageLayout?: PageLayout;
onRender?: (props: OnRenderProps) => any;
}
/**
* This component represent the PDF document itself. It must be the root
* of your tree element structure, and under no circumstances should it be
* used as children of another react-pdf component. In addition, it should
* only have childs of type <Page />.
*/
export class Document extends React.Component<
React.PropsWithChildren<DocumentProps>
> {}
interface NodeProps {
id?: string;
style?: Style | Style[];
/**
* Render component in all wrapped pages.
* @see https://react-pdf.org/advanced#fixed-components
*/
fixed?: boolean;
/**
* Force the wrapping algorithm to start a new page when rendering the
* element.
* @see https://react-pdf.org/advanced#page-breaks
*/
break?: boolean;
/**
* Hint that no page wrapping should occur between all sibling elements following the element within n points
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
minPresenceAhead?: number;
}
interface PageProps extends NodeProps {
/**
* Enable page wrapping for this page.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
size?: PageSize;
orientation?: Orientation;
dpi?: number;
bookmark?: Bookmark;
}
/**
* Represents single page inside the PDF document, or a subset of them if
* using the wrapping feature. A <Document /> can contain as many pages as
* you want, but ensure not rendering a page inside any component besides
* Document.
*/
export class Page extends React.Component<
React.PropsWithChildren<PageProps>
> {}
interface ViewProps extends NodeProps {
id?: string;
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
render?: (props: {
pageNumber: number;
subPageNumber: number;
}) => React.ReactNode;
}
/**
* The most fundamental component for building a UI and is designed to be
* nested inside other views and can have 0 to many children.
*/
export class View extends React.Component<
React.PropsWithChildren<ViewProps>
> {}
interface BaseImageProps extends NodeProps {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
cache?: boolean;
}
interface ImageWithSrcProp extends BaseImageProps {
src: SourceObject;
}
interface ImageWithSourceProp extends BaseImageProps {
source: SourceObject;
}
type ImageProps = ImageWithSrcProp | ImageWithSourceProp;
/**
* A React component for displaying network or local (Node only) JPG or
* PNG images, as well as base64 encoded image strings.
*/
export class Image extends React.Component<ImageProps> {}
interface TextProps extends NodeProps {
id?: string;
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
render?: (props: {
pageNumber: number;
totalPages: number;
subPageNumber: number;
subPageTotalPages: number;
}) => React.ReactNode;
/**
* Override the default hyphenation-callback
* @see https://react-pdf.org/fonts#registerhyphenationcallback
*/
hyphenationCallback?: HyphenationCallback;
/**
* Specifies the minimum number of lines in a text element that must be shown at the bottom of a page or its container.
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
orphans?: number;
/**
* Specifies the minimum number of lines in a text element that must be shown at the top of a page or its container..
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
widows?: number;
}
interface SVGTextProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x: string | number;
y: string | number;
/**
* Override the default hyphenation-callback
* @see https://react-pdf.org/fonts#registerhyphenationcallback
*/
hyphenationCallback?: HyphenationCallback;
}
/**
* A React component for displaying text. Text supports nesting of other
* Text or Link components to create inline styling.
*/
export class Text extends React.Component<
React.PropsWithChildren<TextProps> | SVGTextProps
> {}
interface LinkProps extends NodeProps {
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
href?: string;
src?: string;
}
/**
* A React component for displaying a hyperlink. Links can be nested
* inside a Text component, or being inside any other valid primitive.
*/
export class Link extends React.Component<
React.PropsWithChildren<LinkProps>
> {}
interface FormCommonProps extends NodeProps {
name?: string;
required?: boolean;
noExport?: boolean;
readOnly?: boolean;
value?: number | string;
defaultValue?: number | string;
}
interface FieldSetProps extends NodeProps {
name: string;
}
export class FieldSet extends React.Component<
React.PropsWithChildren<FieldSetProps>
> {}
// see http://pdfkit.org/docs/forms.html#text_field_formatting
interface TextInputFormatting {
type:
| 'date'
| 'time'
| 'percent'
| 'number'
| 'zip'
| 'zipPlus4'
| 'phone'
| 'ssn';
param?: string;
nDec?: number;
sepComma?: boolean;
negStyle?: 'MinusBlack' | 'Red' | 'ParensBlack' | 'ParensRed';
currency?: string;
currencyPrepend?: boolean;
}
// see http://pdfkit.org/docs/forms.html#text_field_formatting
interface TextInputProps extends FormCommonProps {
align?: 'left' | 'center' | 'right';
multiline?: boolean;
/**
* The text will be masked (e.g. with asterisks).
*/
password?: boolean;
/**
* If set, text entered in the field is not spell-checked
*/
noSpell?: boolean;
format?: TextInputFormatting;
/**
* Sets the fontSize (default or 0 means auto sizing)
*/
fontSize?: number;
/**
* Sets the maximum length (characters) of the text in the field
*/
maxLength?: number;
}
export class TextInput extends React.Component<TextInputProps> {}
interface CheckboxProps extends FormCommonProps {
backgroundColor?: string;
borderColor?: string;
checked?: boolean;
onState?: string;
offState?: string;
xMark?: boolean;
}
export class Checkbox extends React.Component<CheckboxProps> {}
interface SelectAndListPropsBase extends FormCommonProps {
sort?: boolean;
edit?: boolean;
multiSelect?: boolean;
noSpell?: boolean;
select?: string[];
}
type SelectAndListPropsWithEdit = SelectAndListPropsBase & {
edit: true | false;
noSpell: boolean;
};
type SelectAndListPropsWithNoSpell = SelectAndListPropsBase & {
edit: boolean;
noSpell: true | false;
};
type SelectAndListProps =
| SelectAndListPropsWithEdit
| SelectAndListPropsWithNoSpell;
export class Select extends React.Component<SelectAndListProps> {}
export class List extends React.Component<SelectAndListProps> {}
interface NoteProps extends NodeProps {
children: string;
}
export class Note extends React.Component<NoteProps> {}
interface CanvasProps extends NodeProps {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
paint: (
painter: any,
availableWidth: number,
availableHeight: number,
) => null;
}
export class Canvas extends React.Component<CanvasProps> {}
interface SVGProps extends NodeProps, SVGPresentationAttributes {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
width?: string | number;
height?: string | number;
viewBox?: string;
preserveAspectRatio?: string;
}
/**
* The <SVG /> element is a container that defines a new coordinate system and viewport. It is used as the outermost element of SVG documents.
*/
export class Svg extends React.Component<React.PropsWithChildren<SVGProps>> {}
interface LineProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x1: string | number;
x2: string | number;
y1: string | number;
y2: string | number;
}
/**
* The <Line /> element is used to create a line.
*/
export class Line extends React.Component<
React.PropsWithChildren<LineProps>
> {}
interface PolylineProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
points: string;
}
/**
* The <Polyline /> element is used to create any shape that consists of only straight lines (that is connected at several points).
*/
export class Polyline extends React.Component<
React.PropsWithChildren<PolylineProps>
> {}
interface PolygonProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
points: string;
}
/**
* The <Polygon /> element is used to create a graphic that contains at least three sides.
* Polygons are made of straight lines, and the shape is "closed" (all the lines connect up).
*/
export class Polygon extends React.Component<
React.PropsWithChildren<PolygonProps>
> {}
interface PathProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
d: string;
}
/**
* The <Path /> element is the most powerful element in the SVG library of basic shapes. It can be used to create lines, curves, arcs, and more.
*/
export class Path extends React.Component<
React.PropsWithChildren<PathProps>
> {}
interface RectProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x?: string | number;
y?: string | number;
width: string | number;
height: string | number;
rx?: string | number;
ry?: string | number;
}
/**
* The <Rect /> element is used to create a rectangle and variations of a rectangle shape.
*/
export class Rect extends React.Component<
React.PropsWithChildren<RectProps>
> {}
interface CircleProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
cx?: string | number;
cy?: string | number;
r: string | number;
}
/**
* The <Circle /> element is used to create a circle.
*/
export class Circle extends React.Component<
React.PropsWithChildren<CircleProps>
> {}
interface EllipseProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
cx?: string | number;
cy?: string | number;
rx: string | number;
ry: string | number;
}
/**
* The <Ellipse /> element is used to create an ellipse.
* An ellipse is closely related to a circle. The difference is that an ellipse has an x and a y radius that differs from each other, while a circle has equal x and y radius.
*/
export class Ellipse extends React.Component<
React.PropsWithChildren<EllipseProps>
> {}
interface TspanProps extends SVGPresentationAttributes {
x?: string | number;
y?: string | number;
}
/**
* The <Tspan /> element defines a subtext within a <Text /> element or another <Tspan /> element.
* It allows for adjustment of the style and/or position of that subtext as needed.
*/
export class Tspan extends React.Component<
React.PropsWithChildren<TspanProps>
> {}
interface GProps extends SVGPresentationAttributes {
style?: Style;
}
/**
* The <G /> SVG element is a container used to group other SVG elements.
* Transformations applied to the <G /> element are performed on its child elements, and its attributes are inherited by its children.
*/
export class G extends React.Component<React.PropsWithChildren<GProps>> {}
interface StopProps {
offset: string | number;
stopColor: string;
stopOpacity?: string | number;
}
/**
* The SVG <Stop /> element defines a color and its position to use on a gradient. This element is always a child of a <LinearGradient /> or <RadialGradient /> element
*/
export class Stop extends React.Component<
React.PropsWithChildren<StopProps>
> {}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface DefsProps {}
/**
* The <Defs /> element is used to store graphical objects that will be used at a later time. Objects created inside a <Defs /> element are not rendered directly. To display them you have to reference them
*/
export class Defs extends React.Component<
React.PropsWithChildren<DefsProps>
> {}
interface ClipPathProps {
id?: string;
}
/**
* The <ClipPath /> SVG element defines a clipping path, to be used by the clipPath property.
* A clipping path restricts the region to which paint can be applied. Conceptually, parts of the drawing that lie outside of the region bounded by the clipping path are not drawn.
*/
export class ClipPath extends React.Component<
React.PropsWithChildren<ClipPathProps>
> {}
interface LinearGradientProps {
id: string;
x1?: string | number;
x2?: string | number;
y1?: string | number;
y2?: string | number;
xlinkHref?: string;
gradientTransform?: string;
gradientUnits?: 'userSpaceOnUse' | 'objectBoundingBox';
}
/**
* The <LinearGradient /> element lets authors define linear gradients that can be applied to fill or stroke of graphical elements.
*/
export class LinearGradient extends React.Component<
React.PropsWithChildren<LinearGradientProps>
> {}
interface RadialGradientProps {
id: string;
cx?: string | number;
cy?: string | number;
r?: string | number;
fx?: string | number;
fy?: string | number;
xlinkHref?: string;
gradientTransform?: string;
gradientUnits?: 'userSpaceOnUse' | 'objectBoundingBox';
}
/**
* The <RadialGradient /> element lets authors define radial gradients that can be applied to fill or stroke of graphical elements.
*/
export class RadialGradient extends React.Component<
React.PropsWithChildren<RadialGradientProps>
> {}
interface BlobProviderParams {
blob: Blob | null;
url: string | null;
loading: boolean;
error: Error | null;
}
interface BlobProviderProps {
document: React.ReactElement<DocumentProps>;
children: (params: BlobProviderParams) => React.ReactNode;
}
/**
* Easy and declarative way of getting document's blob data without
* showing it on screen.
* @see https://react-pdf.org/advanced#on-the-fly-rendering
* @platform web
*/
export class BlobProvider extends React.Component<BlobProviderProps> {}
interface PDFViewerProps {
width?: number | string;
height?: number | string;
style?: Style | Style[];
className?: string;
children?: React.ReactElement<DocumentProps>;
innerRef?: React.Ref<HTMLIFrameElement>;
showToolbar?: boolean;
}
/**
* Iframe PDF viewer for client-side generated documents.
* @platform web
*/
export class PDFViewer extends React.Component<PDFViewerProps> {}
interface PDFDownloadLinkProps
extends Omit<
React.AnchorHTMLAttributes<HTMLAnchorElement>,
'href' | 'children'
> {
/** PDF filename. Alias for anchor tag `download` attribute. */
fileName?: string;
document: React.ReactElement<DocumentProps>;
children?: React.ReactNode | React.FC<BlobProviderParams>;
onClick?: React.AnchorHTMLAttributes<HTMLAnchorElement>['onClick'] &
((
event: React.MouseEvent<HTMLAnchorElement, MouseEvent>,
instance: UsePDFInstance,
) => void);
}
/**
* Anchor tag to enable generate and download PDF documents on the fly.
* @see https://react-pdf.org/advanced#on-the-fly-rendering
* @platform web
*/
export class PDFDownloadLink extends React.Component<PDFDownloadLinkProps> {}
interface UsePDFInstance {
loading: boolean;
blob: Blob | null;
url: string | null;
error: string | null;
}
/**
* React hook for creating and updating a PDF document instance
* @platform web
*/
export function usePDF(options?: {
document?: React.ReactElement<DocumentProps>;
}): [
UsePDFInstance,
(newDocument: React.ReactElement<DocumentProps>) => void,
];
export const Font: FontStore;
export const StyleSheet: {
create: <T extends Styles>(styles: T) => T;
};
export const version: any;
export const PDFRenderer: any;
export const pdf: (initialValue?: React.ReactElement<DocumentProps>) => {
container: any;
isDirty: () => boolean;
toString: () => string;
toBlob: () => Promise<Blob>;
toBuffer: () => Promise<NodeJS.ReadableStream>;
on: (event: 'change', callback: () => void) => void;
updateContainer: (
document: React.ReactElement<any>,
callback?: () => void,
) => void;
removeListener: (event: 'change', callback: () => void) => void;
};
export const renderToStream: (
document: React.ReactElement<DocumentProps>,
) => Promise<NodeJS.ReadableStream>;
/**
* @deprecated use the `renderToBuffer` method
*/
export const renderToString: (
document: React.ReactElement<DocumentProps>,
) => Promise<string>;
export const renderToFile: (
document: React.ReactElement<DocumentProps>,
filePath: string,
callback?: (output: NodeJS.ReadableStream, _filePath: string) => any,
) => Promise<NodeJS.ReadableStream>;
const render: typeof renderToFile;
/**
* Render document into a nodejs buffer
* @platform node
*/
export const renderToBuffer: (
document: React.ReactElement<ReactPDF.DocumentProps>,
) => Promise<Buffer>;
}
+691
View File
@@ -0,0 +1,691 @@
/* eslint-disable max-classes-per-file */
import * as React from 'react';
import {
Style,
PageSize,
FontStore,
PDFVersion,
Orientation,
SourceObject,
HyphenationCallback,
SVGPresentationAttributes,
Bookmark,
PageLayout,
PageMode,
} from '@react-pdf/types';
declare class ReactPDF {
static default: typeof ReactPDF;
}
export = ReactPDF;
declare namespace ReactPDF {
interface Styles {
[key: string]: Style;
}
interface OnRenderProps {
blob?: Blob;
}
interface DocumentProps {
style?: Style | Style[];
title?: string;
author?: string;
subject?: string;
creator?: string;
keywords?: string;
producer?: string;
language?: string;
creationDate?: Date;
modificationDate?: Date;
pdfVersion?: PDFVersion;
pageMode?: PageMode;
pageLayout?: PageLayout;
onRender?: (props: OnRenderProps) => any;
}
/**
* This component represent the PDF document itself. It must be the root
* of your tree element structure, and under no circumstances should it be
* used as children of another react-pdf component. In addition, it should
* only have childs of type <Page />.
*/
export class Document extends React.Component<
React.PropsWithChildren<DocumentProps>
> {}
interface NodeProps {
id?: string;
style?: Style | Style[];
/**
* Render component in all wrapped pages.
* @see https://react-pdf.org/advanced#fixed-components
*/
fixed?: boolean;
/**
* Force the wrapping algorithm to start a new page when rendering the
* element.
* @see https://react-pdf.org/advanced#page-breaks
*/
break?: boolean;
/**
* Hint that no page wrapping should occur between all sibling elements following the element within n points
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
minPresenceAhead?: number;
}
interface PageProps extends NodeProps {
/**
* Enable page wrapping for this page.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
size?: PageSize;
orientation?: Orientation;
dpi?: number;
bookmark?: Bookmark;
}
/**
* Represents single page inside the PDF document, or a subset of them if
* using the wrapping feature. A <Document /> can contain as many pages as
* you want, but ensure not rendering a page inside any component besides
* Document.
*/
export class Page extends React.Component<
React.PropsWithChildren<PageProps>
> {}
interface ViewProps extends NodeProps {
id?: string;
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
render?: (props: {
pageNumber: number;
subPageNumber: number;
}) => React.ReactNode;
}
/**
* The most fundamental component for building a UI and is designed to be
* nested inside other views and can have 0 to many children.
*/
export class View extends React.Component<
React.PropsWithChildren<ViewProps>
> {}
interface BaseImageProps extends NodeProps {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
cache?: boolean;
}
interface ImageWithSrcProp extends BaseImageProps {
src: SourceObject;
}
interface ImageWithSourceProp extends BaseImageProps {
source: SourceObject;
}
type ImageProps = ImageWithSrcProp | ImageWithSourceProp;
/**
* A React component for displaying network or local (Node only) JPG or
* PNG images, as well as base64 encoded image strings.
*/
export class Image extends React.Component<ImageProps> {}
interface TextProps extends NodeProps {
id?: string;
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
render?: (props: {
pageNumber: number;
totalPages: number;
subPageNumber: number;
subPageTotalPages: number;
}) => React.ReactNode;
/**
* Override the default hyphenation-callback
* @see https://react-pdf.org/fonts#registerhyphenationcallback
*/
hyphenationCallback?: HyphenationCallback;
/**
* Specifies the minimum number of lines in a text element that must be shown at the bottom of a page or its container.
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
orphans?: number;
/**
* Specifies the minimum number of lines in a text element that must be shown at the top of a page or its container..
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
widows?: number;
}
interface SVGTextProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x: string | number;
y: string | number;
/**
* Override the default hyphenation-callback
* @see https://react-pdf.org/fonts#registerhyphenationcallback
*/
hyphenationCallback?: HyphenationCallback;
}
/**
* A React component for displaying text. Text supports nesting of other
* Text or Link components to create inline styling.
*/
export class Text extends React.Component<
React.PropsWithChildren<TextProps> | SVGTextProps
> {}
interface LinkProps extends NodeProps {
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
href?: string;
src?: string;
}
/**
* A React component for displaying a hyperlink. Links can be nested
* inside a Text component, or being inside any other valid primitive.
*/
export class Link extends React.Component<
React.PropsWithChildren<LinkProps>
> {}
interface FormCommonProps extends NodeProps {
name?: string;
required?: boolean;
noExport?: boolean;
readOnly?: boolean;
value?: number | string;
defaultValue?: number | string;
}
interface FieldSetProps extends NodeProps {
name: string;
}
export class FieldSet extends React.Component<
React.PropsWithChildren<FieldSetProps>
> {}
// see http://pdfkit.org/docs/forms.html#text_field_formatting
interface TextInputFormatting {
type:
| 'date'
| 'time'
| 'percent'
| 'number'
| 'zip'
| 'zipPlus4'
| 'phone'
| 'ssn';
param?: string;
nDec?: number;
sepComma?: boolean;
negStyle?: 'MinusBlack' | 'Red' | 'ParensBlack' | 'ParensRed';
currency?: string;
currencyPrepend?: boolean;
}
// see http://pdfkit.org/docs/forms.html#text_field_formatting
interface TextInputProps extends FormCommonProps {
align?: 'left' | 'center' | 'right';
multiline?: boolean;
/**
* The text will be masked (e.g. with asterisks).
*/
password?: boolean;
/**
* If set, text entered in the field is not spell-checked
*/
noSpell?: boolean;
format?: TextInputFormatting;
/**
* Sets the fontSize (default or 0 means auto sizing)
*/
fontSize?: number;
/**
* Sets the maximum length (characters) of the text in the field
*/
maxLength?: number;
}
export class TextInput extends React.Component<TextInputProps> {}
interface CheckboxProps extends FormCommonProps {
backgroundColor?: string;
borderColor?: string;
checked?: boolean;
onState?: string;
offState?: string;
xMark?: boolean;
}
export class Checkbox extends React.Component<CheckboxProps> {}
interface SelectAndListPropsBase extends FormCommonProps {
sort?: boolean;
edit?: boolean;
multiSelect?: boolean;
noSpell?: boolean;
select?: string[];
}
type SelectAndListPropsWithEdit = SelectAndListPropsBase & {
edit: true | false;
noSpell: boolean;
};
type SelectAndListPropsWithNoSpell = SelectAndListPropsBase & {
edit: boolean;
noSpell: true | false;
};
type SelectAndListProps =
| SelectAndListPropsWithEdit
| SelectAndListPropsWithNoSpell;
export class Select extends React.Component<SelectAndListProps> {}
export class List extends React.Component<SelectAndListProps> {}
interface NoteProps extends NodeProps {
children: string;
}
export class Note extends React.Component<NoteProps> {}
interface CanvasProps extends NodeProps {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
paint: (
painter: any,
availableWidth: number,
availableHeight: number,
) => null;
}
export class Canvas extends React.Component<CanvasProps> {}
interface SVGProps extends NodeProps, SVGPresentationAttributes {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
width?: string | number;
height?: string | number;
viewBox?: string;
preserveAspectRatio?: string;
}
/**
* The <SVG /> element is a container that defines a new coordinate system and viewport. It is used as the outermost element of SVG documents.
*/
export class Svg extends React.Component<React.PropsWithChildren<SVGProps>> {}
interface LineProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x1: string | number;
x2: string | number;
y1: string | number;
y2: string | number;
}
/**
* The <Line /> element is used to create a line.
*/
export class Line extends React.Component<
React.PropsWithChildren<LineProps>
> {}
interface PolylineProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
points: string;
}
/**
* The <Polyline /> element is used to create any shape that consists of only straight lines (that is connected at several points).
*/
export class Polyline extends React.Component<
React.PropsWithChildren<PolylineProps>
> {}
interface PolygonProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
points: string;
}
/**
* The <Polygon /> element is used to create a graphic that contains at least three sides.
* Polygons are made of straight lines, and the shape is "closed" (all the lines connect up).
*/
export class Polygon extends React.Component<
React.PropsWithChildren<PolygonProps>
> {}
interface PathProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
d: string;
}
/**
* The <Path /> element is the most powerful element in the SVG library of basic shapes. It can be used to create lines, curves, arcs, and more.
*/
export class Path extends React.Component<
React.PropsWithChildren<PathProps>
> {}
interface RectProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x?: string | number;
y?: string | number;
width: string | number;
height: string | number;
rx?: string | number;
ry?: string | number;
}
/**
* The <Rect /> element is used to create a rectangle and variations of a rectangle shape.
*/
export class Rect extends React.Component<
React.PropsWithChildren<RectProps>
> {}
interface CircleProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
cx?: string | number;
cy?: string | number;
r: string | number;
}
/**
* The <Circle /> element is used to create a circle.
*/
export class Circle extends React.Component<
React.PropsWithChildren<CircleProps>
> {}
interface EllipseProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
cx?: string | number;
cy?: string | number;
rx: string | number;
ry: string | number;
}
/**
* The <Ellipse /> element is used to create an ellipse.
* An ellipse is closely related to a circle. The difference is that an ellipse has an x and a y radius that differs from each other, while a circle has equal x and y radius.
*/
export class Ellipse extends React.Component<
React.PropsWithChildren<EllipseProps>
> {}
interface TspanProps extends SVGPresentationAttributes {
x?: string | number;
y?: string | number;
}
/**
* The <Tspan /> element defines a subtext within a <Text /> element or another <Tspan /> element.
* It allows for adjustment of the style and/or position of that subtext as needed.
*/
export class Tspan extends React.Component<
React.PropsWithChildren<TspanProps>
> {}
interface GProps extends SVGPresentationAttributes {
style?: Style;
}
/**
* The <G /> SVG element is a container used to group other SVG elements.
* Transformations applied to the <G /> element are performed on its child elements, and its attributes are inherited by its children.
*/
export class G extends React.Component<React.PropsWithChildren<GProps>> {}
interface StopProps {
offset: string | number;
stopColor: string;
stopOpacity?: string | number;
}
/**
* The SVG <Stop /> element defines a color and its position to use on a gradient. This element is always a child of a <LinearGradient /> or <RadialGradient /> element
*/
export class Stop extends React.Component<
React.PropsWithChildren<StopProps>
> {}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface DefsProps {}
/**
* The <Defs /> element is used to store graphical objects that will be used at a later time. Objects created inside a <Defs /> element are not rendered directly. To display them you have to reference them
*/
export class Defs extends React.Component<
React.PropsWithChildren<DefsProps>
> {}
interface ClipPathProps {
id?: string;
}
/**
* The <ClipPath /> SVG element defines a clipping path, to be used by the clipPath property.
* A clipping path restricts the region to which paint can be applied. Conceptually, parts of the drawing that lie outside of the region bounded by the clipping path are not drawn.
*/
export class ClipPath extends React.Component<
React.PropsWithChildren<ClipPathProps>
> {}
interface LinearGradientProps {
id: string;
x1?: string | number;
x2?: string | number;
y1?: string | number;
y2?: string | number;
xlinkHref?: string;
gradientTransform?: string;
gradientUnits?: 'userSpaceOnUse' | 'objectBoundingBox';
}
/**
* The <LinearGradient /> element lets authors define linear gradients that can be applied to fill or stroke of graphical elements.
*/
export class LinearGradient extends React.Component<
React.PropsWithChildren<LinearGradientProps>
> {}
interface RadialGradientProps {
id: string;
cx?: string | number;
cy?: string | number;
r?: string | number;
fx?: string | number;
fy?: string | number;
xlinkHref?: string;
gradientTransform?: string;
gradientUnits?: 'userSpaceOnUse' | 'objectBoundingBox';
}
/**
* The <RadialGradient /> element lets authors define radial gradients that can be applied to fill or stroke of graphical elements.
*/
export class RadialGradient extends React.Component<
React.PropsWithChildren<RadialGradientProps>
> {}
interface BlobProviderParams {
blob: Blob | null;
url: string | null;
loading: boolean;
error: Error | null;
}
interface BlobProviderProps {
document: React.ReactElement<DocumentProps>;
children: (params: BlobProviderParams) => React.ReactNode;
}
/**
* Easy and declarative way of getting document's blob data without
* showing it on screen.
* @see https://react-pdf.org/advanced#on-the-fly-rendering
* @platform web
*/
export class BlobProvider extends React.Component<BlobProviderProps> {}
interface PDFViewerProps {
width?: number | string;
height?: number | string;
style?: Style | Style[];
className?: string;
children?: React.ReactElement<DocumentProps>;
innerRef?: React.Ref<HTMLIFrameElement>;
showToolbar?: boolean;
}
/**
* Iframe PDF viewer for client-side generated documents.
* @platform web
*/
export class PDFViewer extends React.Component<PDFViewerProps> {}
interface PDFDownloadLinkProps
extends Omit<
React.AnchorHTMLAttributes<HTMLAnchorElement>,
'href' | 'children'
> {
/** PDF filename. Alias for anchor tag `download` attribute. */
fileName?: string;
document: React.ReactElement<DocumentProps>;
children?: React.ReactNode | React.FC<BlobProviderParams>;
onClick?: React.AnchorHTMLAttributes<HTMLAnchorElement>['onClick'] &
((
event: React.MouseEvent<HTMLAnchorElement, MouseEvent>,
instance: UsePDFInstance,
) => void);
}
/**
* Anchor tag to enable generate and download PDF documents on the fly.
* @see https://react-pdf.org/advanced#on-the-fly-rendering
* @platform web
*/
export class PDFDownloadLink extends React.Component<PDFDownloadLinkProps> {}
interface UsePDFInstance {
loading: boolean;
blob: Blob | null;
url: string | null;
error: string | null;
}
/**
* React hook for creating and updating a PDF document instance
* @platform web
*/
export function usePDF(options?: {
document?: React.ReactElement<DocumentProps>;
}): [
UsePDFInstance,
(newDocument: React.ReactElement<DocumentProps>) => void,
];
export const Font: FontStore;
export const StyleSheet: {
create: <T extends Styles>(styles: T) => T;
};
export const version: any;
export const PDFRenderer: any;
export const pdf: (initialValue?: React.ReactElement<DocumentProps>) => {
container: any;
isDirty: () => boolean;
toString: () => string;
toBlob: () => Promise<Blob>;
toBuffer: () => Promise<NodeJS.ReadableStream>;
on: (event: 'change', callback: () => void) => void;
updateContainer: (
document: React.ReactElement<any>,
callback?: () => void,
) => void;
removeListener: (event: 'change', callback: () => void) => void;
};
export const renderToStream: (
document: React.ReactElement<DocumentProps>,
) => Promise<NodeJS.ReadableStream>;
/**
* @deprecated use the `renderToBuffer` method
*/
export const renderToString: (
document: React.ReactElement<DocumentProps>,
) => Promise<string>;
export const renderToFile: (
document: React.ReactElement<DocumentProps>,
filePath: string,
callback?: (output: NodeJS.ReadableStream, _filePath: string) => any,
) => Promise<NodeJS.ReadableStream>;
const render: typeof renderToFile;
/**
* Render document into a nodejs buffer
* @platform node
*/
export const renderToBuffer: (
document: React.ReactElement<ReactPDF.DocumentProps>,
) => Promise<Buffer>;
}
File diff suppressed because one or more lines are too long
+691
View File
@@ -0,0 +1,691 @@
/* eslint-disable max-classes-per-file */
import * as React from 'react';
import {
Style,
PageSize,
FontStore,
PDFVersion,
Orientation,
SourceObject,
HyphenationCallback,
SVGPresentationAttributes,
Bookmark,
PageLayout,
PageMode,
} from '@react-pdf/types';
declare class ReactPDF {
static default: typeof ReactPDF;
}
export = ReactPDF;
declare namespace ReactPDF {
interface Styles {
[key: string]: Style;
}
interface OnRenderProps {
blob?: Blob;
}
interface DocumentProps {
style?: Style | Style[];
title?: string;
author?: string;
subject?: string;
creator?: string;
keywords?: string;
producer?: string;
language?: string;
creationDate?: Date;
modificationDate?: Date;
pdfVersion?: PDFVersion;
pageMode?: PageMode;
pageLayout?: PageLayout;
onRender?: (props: OnRenderProps) => any;
}
/**
* This component represent the PDF document itself. It must be the root
* of your tree element structure, and under no circumstances should it be
* used as children of another react-pdf component. In addition, it should
* only have childs of type <Page />.
*/
export class Document extends React.Component<
React.PropsWithChildren<DocumentProps>
> {}
interface NodeProps {
id?: string;
style?: Style | Style[];
/**
* Render component in all wrapped pages.
* @see https://react-pdf.org/advanced#fixed-components
*/
fixed?: boolean;
/**
* Force the wrapping algorithm to start a new page when rendering the
* element.
* @see https://react-pdf.org/advanced#page-breaks
*/
break?: boolean;
/**
* Hint that no page wrapping should occur between all sibling elements following the element within n points
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
minPresenceAhead?: number;
}
interface PageProps extends NodeProps {
/**
* Enable page wrapping for this page.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
size?: PageSize;
orientation?: Orientation;
dpi?: number;
bookmark?: Bookmark;
}
/**
* Represents single page inside the PDF document, or a subset of them if
* using the wrapping feature. A <Document /> can contain as many pages as
* you want, but ensure not rendering a page inside any component besides
* Document.
*/
export class Page extends React.Component<
React.PropsWithChildren<PageProps>
> {}
interface ViewProps extends NodeProps {
id?: string;
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
render?: (props: {
pageNumber: number;
subPageNumber: number;
}) => React.ReactNode;
}
/**
* The most fundamental component for building a UI and is designed to be
* nested inside other views and can have 0 to many children.
*/
export class View extends React.Component<
React.PropsWithChildren<ViewProps>
> {}
interface BaseImageProps extends NodeProps {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
cache?: boolean;
}
interface ImageWithSrcProp extends BaseImageProps {
src: SourceObject;
}
interface ImageWithSourceProp extends BaseImageProps {
source: SourceObject;
}
type ImageProps = ImageWithSrcProp | ImageWithSourceProp;
/**
* A React component for displaying network or local (Node only) JPG or
* PNG images, as well as base64 encoded image strings.
*/
export class Image extends React.Component<ImageProps> {}
interface TextProps extends NodeProps {
id?: string;
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
render?: (props: {
pageNumber: number;
totalPages: number;
subPageNumber: number;
subPageTotalPages: number;
}) => React.ReactNode;
/**
* Override the default hyphenation-callback
* @see https://react-pdf.org/fonts#registerhyphenationcallback
*/
hyphenationCallback?: HyphenationCallback;
/**
* Specifies the minimum number of lines in a text element that must be shown at the bottom of a page or its container.
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
orphans?: number;
/**
* Specifies the minimum number of lines in a text element that must be shown at the top of a page or its container..
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
widows?: number;
}
interface SVGTextProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x: string | number;
y: string | number;
/**
* Override the default hyphenation-callback
* @see https://react-pdf.org/fonts#registerhyphenationcallback
*/
hyphenationCallback?: HyphenationCallback;
}
/**
* A React component for displaying text. Text supports nesting of other
* Text or Link components to create inline styling.
*/
export class Text extends React.Component<
React.PropsWithChildren<TextProps> | SVGTextProps
> {}
interface LinkProps extends NodeProps {
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
href?: string;
src?: string;
}
/**
* A React component for displaying a hyperlink. Links can be nested
* inside a Text component, or being inside any other valid primitive.
*/
export class Link extends React.Component<
React.PropsWithChildren<LinkProps>
> {}
interface FormCommonProps extends NodeProps {
name?: string;
required?: boolean;
noExport?: boolean;
readOnly?: boolean;
value?: number | string;
defaultValue?: number | string;
}
interface FieldSetProps extends NodeProps {
name: string;
}
export class FieldSet extends React.Component<
React.PropsWithChildren<FieldSetProps>
> {}
// see http://pdfkit.org/docs/forms.html#text_field_formatting
interface TextInputFormatting {
type:
| 'date'
| 'time'
| 'percent'
| 'number'
| 'zip'
| 'zipPlus4'
| 'phone'
| 'ssn';
param?: string;
nDec?: number;
sepComma?: boolean;
negStyle?: 'MinusBlack' | 'Red' | 'ParensBlack' | 'ParensRed';
currency?: string;
currencyPrepend?: boolean;
}
// see http://pdfkit.org/docs/forms.html#text_field_formatting
interface TextInputProps extends FormCommonProps {
align?: 'left' | 'center' | 'right';
multiline?: boolean;
/**
* The text will be masked (e.g. with asterisks).
*/
password?: boolean;
/**
* If set, text entered in the field is not spell-checked
*/
noSpell?: boolean;
format?: TextInputFormatting;
/**
* Sets the fontSize (default or 0 means auto sizing)
*/
fontSize?: number;
/**
* Sets the maximum length (characters) of the text in the field
*/
maxLength?: number;
}
export class TextInput extends React.Component<TextInputProps> {}
interface CheckboxProps extends FormCommonProps {
backgroundColor?: string;
borderColor?: string;
checked?: boolean;
onState?: string;
offState?: string;
xMark?: boolean;
}
export class Checkbox extends React.Component<CheckboxProps> {}
interface SelectAndListPropsBase extends FormCommonProps {
sort?: boolean;
edit?: boolean;
multiSelect?: boolean;
noSpell?: boolean;
select?: string[];
}
type SelectAndListPropsWithEdit = SelectAndListPropsBase & {
edit: true | false;
noSpell: boolean;
};
type SelectAndListPropsWithNoSpell = SelectAndListPropsBase & {
edit: boolean;
noSpell: true | false;
};
type SelectAndListProps =
| SelectAndListPropsWithEdit
| SelectAndListPropsWithNoSpell;
export class Select extends React.Component<SelectAndListProps> {}
export class List extends React.Component<SelectAndListProps> {}
interface NoteProps extends NodeProps {
children: string;
}
export class Note extends React.Component<NoteProps> {}
interface CanvasProps extends NodeProps {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
paint: (
painter: any,
availableWidth: number,
availableHeight: number,
) => null;
}
export class Canvas extends React.Component<CanvasProps> {}
interface SVGProps extends NodeProps, SVGPresentationAttributes {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
width?: string | number;
height?: string | number;
viewBox?: string;
preserveAspectRatio?: string;
}
/**
* The <SVG /> element is a container that defines a new coordinate system and viewport. It is used as the outermost element of SVG documents.
*/
export class Svg extends React.Component<React.PropsWithChildren<SVGProps>> {}
interface LineProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x1: string | number;
x2: string | number;
y1: string | number;
y2: string | number;
}
/**
* The <Line /> element is used to create a line.
*/
export class Line extends React.Component<
React.PropsWithChildren<LineProps>
> {}
interface PolylineProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
points: string;
}
/**
* The <Polyline /> element is used to create any shape that consists of only straight lines (that is connected at several points).
*/
export class Polyline extends React.Component<
React.PropsWithChildren<PolylineProps>
> {}
interface PolygonProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
points: string;
}
/**
* The <Polygon /> element is used to create a graphic that contains at least three sides.
* Polygons are made of straight lines, and the shape is "closed" (all the lines connect up).
*/
export class Polygon extends React.Component<
React.PropsWithChildren<PolygonProps>
> {}
interface PathProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
d: string;
}
/**
* The <Path /> element is the most powerful element in the SVG library of basic shapes. It can be used to create lines, curves, arcs, and more.
*/
export class Path extends React.Component<
React.PropsWithChildren<PathProps>
> {}
interface RectProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x?: string | number;
y?: string | number;
width: string | number;
height: string | number;
rx?: string | number;
ry?: string | number;
}
/**
* The <Rect /> element is used to create a rectangle and variations of a rectangle shape.
*/
export class Rect extends React.Component<
React.PropsWithChildren<RectProps>
> {}
interface CircleProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
cx?: string | number;
cy?: string | number;
r: string | number;
}
/**
* The <Circle /> element is used to create a circle.
*/
export class Circle extends React.Component<
React.PropsWithChildren<CircleProps>
> {}
interface EllipseProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
cx?: string | number;
cy?: string | number;
rx: string | number;
ry: string | number;
}
/**
* The <Ellipse /> element is used to create an ellipse.
* An ellipse is closely related to a circle. The difference is that an ellipse has an x and a y radius that differs from each other, while a circle has equal x and y radius.
*/
export class Ellipse extends React.Component<
React.PropsWithChildren<EllipseProps>
> {}
interface TspanProps extends SVGPresentationAttributes {
x?: string | number;
y?: string | number;
}
/**
* The <Tspan /> element defines a subtext within a <Text /> element or another <Tspan /> element.
* It allows for adjustment of the style and/or position of that subtext as needed.
*/
export class Tspan extends React.Component<
React.PropsWithChildren<TspanProps>
> {}
interface GProps extends SVGPresentationAttributes {
style?: Style;
}
/**
* The <G /> SVG element is a container used to group other SVG elements.
* Transformations applied to the <G /> element are performed on its child elements, and its attributes are inherited by its children.
*/
export class G extends React.Component<React.PropsWithChildren<GProps>> {}
interface StopProps {
offset: string | number;
stopColor: string;
stopOpacity?: string | number;
}
/**
* The SVG <Stop /> element defines a color and its position to use on a gradient. This element is always a child of a <LinearGradient /> or <RadialGradient /> element
*/
export class Stop extends React.Component<
React.PropsWithChildren<StopProps>
> {}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface DefsProps {}
/**
* The <Defs /> element is used to store graphical objects that will be used at a later time. Objects created inside a <Defs /> element are not rendered directly. To display them you have to reference them
*/
export class Defs extends React.Component<
React.PropsWithChildren<DefsProps>
> {}
interface ClipPathProps {
id?: string;
}
/**
* The <ClipPath /> SVG element defines a clipping path, to be used by the clipPath property.
* A clipping path restricts the region to which paint can be applied. Conceptually, parts of the drawing that lie outside of the region bounded by the clipping path are not drawn.
*/
export class ClipPath extends React.Component<
React.PropsWithChildren<ClipPathProps>
> {}
interface LinearGradientProps {
id: string;
x1?: string | number;
x2?: string | number;
y1?: string | number;
y2?: string | number;
xlinkHref?: string;
gradientTransform?: string;
gradientUnits?: 'userSpaceOnUse' | 'objectBoundingBox';
}
/**
* The <LinearGradient /> element lets authors define linear gradients that can be applied to fill or stroke of graphical elements.
*/
export class LinearGradient extends React.Component<
React.PropsWithChildren<LinearGradientProps>
> {}
interface RadialGradientProps {
id: string;
cx?: string | number;
cy?: string | number;
r?: string | number;
fx?: string | number;
fy?: string | number;
xlinkHref?: string;
gradientTransform?: string;
gradientUnits?: 'userSpaceOnUse' | 'objectBoundingBox';
}
/**
* The <RadialGradient /> element lets authors define radial gradients that can be applied to fill or stroke of graphical elements.
*/
export class RadialGradient extends React.Component<
React.PropsWithChildren<RadialGradientProps>
> {}
interface BlobProviderParams {
blob: Blob | null;
url: string | null;
loading: boolean;
error: Error | null;
}
interface BlobProviderProps {
document: React.ReactElement<DocumentProps>;
children: (params: BlobProviderParams) => React.ReactNode;
}
/**
* Easy and declarative way of getting document's blob data without
* showing it on screen.
* @see https://react-pdf.org/advanced#on-the-fly-rendering
* @platform web
*/
export class BlobProvider extends React.Component<BlobProviderProps> {}
interface PDFViewerProps {
width?: number | string;
height?: number | string;
style?: Style | Style[];
className?: string;
children?: React.ReactElement<DocumentProps>;
innerRef?: React.Ref<HTMLIFrameElement>;
showToolbar?: boolean;
}
/**
* Iframe PDF viewer for client-side generated documents.
* @platform web
*/
export class PDFViewer extends React.Component<PDFViewerProps> {}
interface PDFDownloadLinkProps
extends Omit<
React.AnchorHTMLAttributes<HTMLAnchorElement>,
'href' | 'children'
> {
/** PDF filename. Alias for anchor tag `download` attribute. */
fileName?: string;
document: React.ReactElement<DocumentProps>;
children?: React.ReactNode | React.FC<BlobProviderParams>;
onClick?: React.AnchorHTMLAttributes<HTMLAnchorElement>['onClick'] &
((
event: React.MouseEvent<HTMLAnchorElement, MouseEvent>,
instance: UsePDFInstance,
) => void);
}
/**
* Anchor tag to enable generate and download PDF documents on the fly.
* @see https://react-pdf.org/advanced#on-the-fly-rendering
* @platform web
*/
export class PDFDownloadLink extends React.Component<PDFDownloadLinkProps> {}
interface UsePDFInstance {
loading: boolean;
blob: Blob | null;
url: string | null;
error: string | null;
}
/**
* React hook for creating and updating a PDF document instance
* @platform web
*/
export function usePDF(options?: {
document?: React.ReactElement<DocumentProps>;
}): [
UsePDFInstance,
(newDocument: React.ReactElement<DocumentProps>) => void,
];
export const Font: FontStore;
export const StyleSheet: {
create: <T extends Styles>(styles: T) => T;
};
export const version: any;
export const PDFRenderer: any;
export const pdf: (initialValue?: React.ReactElement<DocumentProps>) => {
container: any;
isDirty: () => boolean;
toString: () => string;
toBlob: () => Promise<Blob>;
toBuffer: () => Promise<NodeJS.ReadableStream>;
on: (event: 'change', callback: () => void) => void;
updateContainer: (
document: React.ReactElement<any>,
callback?: () => void,
) => void;
removeListener: (event: 'change', callback: () => void) => void;
};
export const renderToStream: (
document: React.ReactElement<DocumentProps>,
) => Promise<NodeJS.ReadableStream>;
/**
* @deprecated use the `renderToBuffer` method
*/
export const renderToString: (
document: React.ReactElement<DocumentProps>,
) => Promise<string>;
export const renderToFile: (
document: React.ReactElement<DocumentProps>,
filePath: string,
callback?: (output: NodeJS.ReadableStream, _filePath: string) => any,
) => Promise<NodeJS.ReadableStream>;
const render: typeof renderToFile;
/**
* Render document into a nodejs buffer
* @platform node
*/
export const renderToBuffer: (
document: React.ReactElement<ReactPDF.DocumentProps>,
) => Promise<Buffer>;
}
+691
View File
@@ -0,0 +1,691 @@
/* eslint-disable max-classes-per-file */
import * as React from 'react';
import {
Style,
PageSize,
FontStore,
PDFVersion,
Orientation,
SourceObject,
HyphenationCallback,
SVGPresentationAttributes,
Bookmark,
PageLayout,
PageMode,
} from '@react-pdf/types';
declare class ReactPDF {
static default: typeof ReactPDF;
}
export = ReactPDF;
declare namespace ReactPDF {
interface Styles {
[key: string]: Style;
}
interface OnRenderProps {
blob?: Blob;
}
interface DocumentProps {
style?: Style | Style[];
title?: string;
author?: string;
subject?: string;
creator?: string;
keywords?: string;
producer?: string;
language?: string;
creationDate?: Date;
modificationDate?: Date;
pdfVersion?: PDFVersion;
pageMode?: PageMode;
pageLayout?: PageLayout;
onRender?: (props: OnRenderProps) => any;
}
/**
* This component represent the PDF document itself. It must be the root
* of your tree element structure, and under no circumstances should it be
* used as children of another react-pdf component. In addition, it should
* only have childs of type <Page />.
*/
export class Document extends React.Component<
React.PropsWithChildren<DocumentProps>
> {}
interface NodeProps {
id?: string;
style?: Style | Style[];
/**
* Render component in all wrapped pages.
* @see https://react-pdf.org/advanced#fixed-components
*/
fixed?: boolean;
/**
* Force the wrapping algorithm to start a new page when rendering the
* element.
* @see https://react-pdf.org/advanced#page-breaks
*/
break?: boolean;
/**
* Hint that no page wrapping should occur between all sibling elements following the element within n points
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
minPresenceAhead?: number;
}
interface PageProps extends NodeProps {
/**
* Enable page wrapping for this page.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
size?: PageSize;
orientation?: Orientation;
dpi?: number;
bookmark?: Bookmark;
}
/**
* Represents single page inside the PDF document, or a subset of them if
* using the wrapping feature. A <Document /> can contain as many pages as
* you want, but ensure not rendering a page inside any component besides
* Document.
*/
export class Page extends React.Component<
React.PropsWithChildren<PageProps>
> {}
interface ViewProps extends NodeProps {
id?: string;
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
render?: (props: {
pageNumber: number;
subPageNumber: number;
}) => React.ReactNode;
}
/**
* The most fundamental component for building a UI and is designed to be
* nested inside other views and can have 0 to many children.
*/
export class View extends React.Component<
React.PropsWithChildren<ViewProps>
> {}
interface BaseImageProps extends NodeProps {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
cache?: boolean;
}
interface ImageWithSrcProp extends BaseImageProps {
src: SourceObject;
}
interface ImageWithSourceProp extends BaseImageProps {
source: SourceObject;
}
type ImageProps = ImageWithSrcProp | ImageWithSourceProp;
/**
* A React component for displaying network or local (Node only) JPG or
* PNG images, as well as base64 encoded image strings.
*/
export class Image extends React.Component<ImageProps> {}
interface TextProps extends NodeProps {
id?: string;
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
render?: (props: {
pageNumber: number;
totalPages: number;
subPageNumber: number;
subPageTotalPages: number;
}) => React.ReactNode;
/**
* Override the default hyphenation-callback
* @see https://react-pdf.org/fonts#registerhyphenationcallback
*/
hyphenationCallback?: HyphenationCallback;
/**
* Specifies the minimum number of lines in a text element that must be shown at the bottom of a page or its container.
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
orphans?: number;
/**
* Specifies the minimum number of lines in a text element that must be shown at the top of a page or its container..
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
widows?: number;
}
interface SVGTextProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x: string | number;
y: string | number;
/**
* Override the default hyphenation-callback
* @see https://react-pdf.org/fonts#registerhyphenationcallback
*/
hyphenationCallback?: HyphenationCallback;
}
/**
* A React component for displaying text. Text supports nesting of other
* Text or Link components to create inline styling.
*/
export class Text extends React.Component<
React.PropsWithChildren<TextProps> | SVGTextProps
> {}
interface LinkProps extends NodeProps {
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
href?: string;
src?: string;
}
/**
* A React component for displaying a hyperlink. Links can be nested
* inside a Text component, or being inside any other valid primitive.
*/
export class Link extends React.Component<
React.PropsWithChildren<LinkProps>
> {}
interface FormCommonProps extends NodeProps {
name?: string;
required?: boolean;
noExport?: boolean;
readOnly?: boolean;
value?: number | string;
defaultValue?: number | string;
}
interface FieldSetProps extends NodeProps {
name: string;
}
export class FieldSet extends React.Component<
React.PropsWithChildren<FieldSetProps>
> {}
// see http://pdfkit.org/docs/forms.html#text_field_formatting
interface TextInputFormatting {
type:
| 'date'
| 'time'
| 'percent'
| 'number'
| 'zip'
| 'zipPlus4'
| 'phone'
| 'ssn';
param?: string;
nDec?: number;
sepComma?: boolean;
negStyle?: 'MinusBlack' | 'Red' | 'ParensBlack' | 'ParensRed';
currency?: string;
currencyPrepend?: boolean;
}
// see http://pdfkit.org/docs/forms.html#text_field_formatting
interface TextInputProps extends FormCommonProps {
align?: 'left' | 'center' | 'right';
multiline?: boolean;
/**
* The text will be masked (e.g. with asterisks).
*/
password?: boolean;
/**
* If set, text entered in the field is not spell-checked
*/
noSpell?: boolean;
format?: TextInputFormatting;
/**
* Sets the fontSize (default or 0 means auto sizing)
*/
fontSize?: number;
/**
* Sets the maximum length (characters) of the text in the field
*/
maxLength?: number;
}
export class TextInput extends React.Component<TextInputProps> {}
interface CheckboxProps extends FormCommonProps {
backgroundColor?: string;
borderColor?: string;
checked?: boolean;
onState?: string;
offState?: string;
xMark?: boolean;
}
export class Checkbox extends React.Component<CheckboxProps> {}
interface SelectAndListPropsBase extends FormCommonProps {
sort?: boolean;
edit?: boolean;
multiSelect?: boolean;
noSpell?: boolean;
select?: string[];
}
type SelectAndListPropsWithEdit = SelectAndListPropsBase & {
edit: true | false;
noSpell: boolean;
};
type SelectAndListPropsWithNoSpell = SelectAndListPropsBase & {
edit: boolean;
noSpell: true | false;
};
type SelectAndListProps =
| SelectAndListPropsWithEdit
| SelectAndListPropsWithNoSpell;
export class Select extends React.Component<SelectAndListProps> {}
export class List extends React.Component<SelectAndListProps> {}
interface NoteProps extends NodeProps {
children: string;
}
export class Note extends React.Component<NoteProps> {}
interface CanvasProps extends NodeProps {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
paint: (
painter: any,
availableWidth: number,
availableHeight: number,
) => null;
}
export class Canvas extends React.Component<CanvasProps> {}
interface SVGProps extends NodeProps, SVGPresentationAttributes {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
width?: string | number;
height?: string | number;
viewBox?: string;
preserveAspectRatio?: string;
}
/**
* The <SVG /> element is a container that defines a new coordinate system and viewport. It is used as the outermost element of SVG documents.
*/
export class Svg extends React.Component<React.PropsWithChildren<SVGProps>> {}
interface LineProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x1: string | number;
x2: string | number;
y1: string | number;
y2: string | number;
}
/**
* The <Line /> element is used to create a line.
*/
export class Line extends React.Component<
React.PropsWithChildren<LineProps>
> {}
interface PolylineProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
points: string;
}
/**
* The <Polyline /> element is used to create any shape that consists of only straight lines (that is connected at several points).
*/
export class Polyline extends React.Component<
React.PropsWithChildren<PolylineProps>
> {}
interface PolygonProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
points: string;
}
/**
* The <Polygon /> element is used to create a graphic that contains at least three sides.
* Polygons are made of straight lines, and the shape is "closed" (all the lines connect up).
*/
export class Polygon extends React.Component<
React.PropsWithChildren<PolygonProps>
> {}
interface PathProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
d: string;
}
/**
* The <Path /> element is the most powerful element in the SVG library of basic shapes. It can be used to create lines, curves, arcs, and more.
*/
export class Path extends React.Component<
React.PropsWithChildren<PathProps>
> {}
interface RectProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x?: string | number;
y?: string | number;
width: string | number;
height: string | number;
rx?: string | number;
ry?: string | number;
}
/**
* The <Rect /> element is used to create a rectangle and variations of a rectangle shape.
*/
export class Rect extends React.Component<
React.PropsWithChildren<RectProps>
> {}
interface CircleProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
cx?: string | number;
cy?: string | number;
r: string | number;
}
/**
* The <Circle /> element is used to create a circle.
*/
export class Circle extends React.Component<
React.PropsWithChildren<CircleProps>
> {}
interface EllipseProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
cx?: string | number;
cy?: string | number;
rx: string | number;
ry: string | number;
}
/**
* The <Ellipse /> element is used to create an ellipse.
* An ellipse is closely related to a circle. The difference is that an ellipse has an x and a y radius that differs from each other, while a circle has equal x and y radius.
*/
export class Ellipse extends React.Component<
React.PropsWithChildren<EllipseProps>
> {}
interface TspanProps extends SVGPresentationAttributes {
x?: string | number;
y?: string | number;
}
/**
* The <Tspan /> element defines a subtext within a <Text /> element or another <Tspan /> element.
* It allows for adjustment of the style and/or position of that subtext as needed.
*/
export class Tspan extends React.Component<
React.PropsWithChildren<TspanProps>
> {}
interface GProps extends SVGPresentationAttributes {
style?: Style;
}
/**
* The <G /> SVG element is a container used to group other SVG elements.
* Transformations applied to the <G /> element are performed on its child elements, and its attributes are inherited by its children.
*/
export class G extends React.Component<React.PropsWithChildren<GProps>> {}
interface StopProps {
offset: string | number;
stopColor: string;
stopOpacity?: string | number;
}
/**
* The SVG <Stop /> element defines a color and its position to use on a gradient. This element is always a child of a <LinearGradient /> or <RadialGradient /> element
*/
export class Stop extends React.Component<
React.PropsWithChildren<StopProps>
> {}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface DefsProps {}
/**
* The <Defs /> element is used to store graphical objects that will be used at a later time. Objects created inside a <Defs /> element are not rendered directly. To display them you have to reference them
*/
export class Defs extends React.Component<
React.PropsWithChildren<DefsProps>
> {}
interface ClipPathProps {
id?: string;
}
/**
* The <ClipPath /> SVG element defines a clipping path, to be used by the clipPath property.
* A clipping path restricts the region to which paint can be applied. Conceptually, parts of the drawing that lie outside of the region bounded by the clipping path are not drawn.
*/
export class ClipPath extends React.Component<
React.PropsWithChildren<ClipPathProps>
> {}
interface LinearGradientProps {
id: string;
x1?: string | number;
x2?: string | number;
y1?: string | number;
y2?: string | number;
xlinkHref?: string;
gradientTransform?: string;
gradientUnits?: 'userSpaceOnUse' | 'objectBoundingBox';
}
/**
* The <LinearGradient /> element lets authors define linear gradients that can be applied to fill or stroke of graphical elements.
*/
export class LinearGradient extends React.Component<
React.PropsWithChildren<LinearGradientProps>
> {}
interface RadialGradientProps {
id: string;
cx?: string | number;
cy?: string | number;
r?: string | number;
fx?: string | number;
fy?: string | number;
xlinkHref?: string;
gradientTransform?: string;
gradientUnits?: 'userSpaceOnUse' | 'objectBoundingBox';
}
/**
* The <RadialGradient /> element lets authors define radial gradients that can be applied to fill or stroke of graphical elements.
*/
export class RadialGradient extends React.Component<
React.PropsWithChildren<RadialGradientProps>
> {}
interface BlobProviderParams {
blob: Blob | null;
url: string | null;
loading: boolean;
error: Error | null;
}
interface BlobProviderProps {
document: React.ReactElement<DocumentProps>;
children: (params: BlobProviderParams) => React.ReactNode;
}
/**
* Easy and declarative way of getting document's blob data without
* showing it on screen.
* @see https://react-pdf.org/advanced#on-the-fly-rendering
* @platform web
*/
export class BlobProvider extends React.Component<BlobProviderProps> {}
interface PDFViewerProps {
width?: number | string;
height?: number | string;
style?: Style | Style[];
className?: string;
children?: React.ReactElement<DocumentProps>;
innerRef?: React.Ref<HTMLIFrameElement>;
showToolbar?: boolean;
}
/**
* Iframe PDF viewer for client-side generated documents.
* @platform web
*/
export class PDFViewer extends React.Component<PDFViewerProps> {}
interface PDFDownloadLinkProps
extends Omit<
React.AnchorHTMLAttributes<HTMLAnchorElement>,
'href' | 'children'
> {
/** PDF filename. Alias for anchor tag `download` attribute. */
fileName?: string;
document: React.ReactElement<DocumentProps>;
children?: React.ReactNode | React.FC<BlobProviderParams>;
onClick?: React.AnchorHTMLAttributes<HTMLAnchorElement>['onClick'] &
((
event: React.MouseEvent<HTMLAnchorElement, MouseEvent>,
instance: UsePDFInstance,
) => void);
}
/**
* Anchor tag to enable generate and download PDF documents on the fly.
* @see https://react-pdf.org/advanced#on-the-fly-rendering
* @platform web
*/
export class PDFDownloadLink extends React.Component<PDFDownloadLinkProps> {}
interface UsePDFInstance {
loading: boolean;
blob: Blob | null;
url: string | null;
error: string | null;
}
/**
* React hook for creating and updating a PDF document instance
* @platform web
*/
export function usePDF(options?: {
document?: React.ReactElement<DocumentProps>;
}): [
UsePDFInstance,
(newDocument: React.ReactElement<DocumentProps>) => void,
];
export const Font: FontStore;
export const StyleSheet: {
create: <T extends Styles>(styles: T) => T;
};
export const version: any;
export const PDFRenderer: any;
export const pdf: (initialValue?: React.ReactElement<DocumentProps>) => {
container: any;
isDirty: () => boolean;
toString: () => string;
toBlob: () => Promise<Blob>;
toBuffer: () => Promise<NodeJS.ReadableStream>;
on: (event: 'change', callback: () => void) => void;
updateContainer: (
document: React.ReactElement<any>,
callback?: () => void,
) => void;
removeListener: (event: 'change', callback: () => void) => void;
};
export const renderToStream: (
document: React.ReactElement<DocumentProps>,
) => Promise<NodeJS.ReadableStream>;
/**
* @deprecated use the `renderToBuffer` method
*/
export const renderToString: (
document: React.ReactElement<DocumentProps>,
) => Promise<string>;
export const renderToFile: (
document: React.ReactElement<DocumentProps>,
filePath: string,
callback?: (output: NodeJS.ReadableStream, _filePath: string) => any,
) => Promise<NodeJS.ReadableStream>;
const render: typeof renderToFile;
/**
* Render document into a nodejs buffer
* @platform node
*/
export const renderToBuffer: (
document: React.ReactElement<ReactPDF.DocumentProps>,
) => Promise<Buffer>;
}
+364
View File
@@ -0,0 +1,364 @@
import * as primitives from '@react-pdf/primitives';
export * from '@react-pdf/primitives';
import fs from 'fs';
import { Buffer } from 'buffer';
import FontStore from '@react-pdf/font';
import renderPDF from '@react-pdf/render';
import PDFDocument from '@react-pdf/pdfkit';
import layoutDocument from '@react-pdf/layout';
import { upperFirst } from '@react-pdf/fns';
import Reconciler from '@react-pdf/reconciler';
const omitNils = object => Object.fromEntries(Object.entries(object).filter(_ref => {
let [, value] = _ref;
return value !== undefined;
}));
const createInstance = (type, _ref) => {
let {
style,
children,
...props
} = _ref;
return {
type,
box: {},
style: style || {},
props: props || {},
children: []
};
};
const createTextInstance = text => ({
type: 'TEXT_INSTANCE',
value: text
});
const appendChild = (parent, child) => {
const isParentText = parent.type === 'TEXT' || parent.type === 'LINK' || parent.type === 'TSPAN' || parent.type === 'NOTE';
const isChildTextInstance = child.type === 'TEXT_INSTANCE';
const isOrphanTextInstance = isChildTextInstance && !isParentText;
// Ignore orphan text instances.
// Caused by cases such as <>{name && <Text>{name}</Text>}</>
if (isOrphanTextInstance) {
console.warn(`Invalid '${child.value}' string child outside <Text> component`);
return;
}
parent.children.push(child);
};
const appendChildToContainer = (parentInstance, child) => {
if (parentInstance.type === 'ROOT') {
parentInstance.document = child;
} else {
appendChild(parentInstance, child);
}
};
const insertBefore = (parentInstance, child, beforeChild) => {
var _parentInstance$child;
const index = (_parentInstance$child = parentInstance.children) === null || _parentInstance$child === void 0 ? void 0 : _parentInstance$child.indexOf(beforeChild);
if (index === undefined) return;
if (index !== -1 && child) parentInstance.children.splice(index, 0, child);
};
const removeChild = (parentInstance, child) => {
var _parentInstance$child2;
const index = (_parentInstance$child2 = parentInstance.children) === null || _parentInstance$child2 === void 0 ? void 0 : _parentInstance$child2.indexOf(child);
if (index === undefined) return;
if (index !== -1) parentInstance.children.splice(index, 1);
};
const removeChildFromContainer = (parentInstance, child) => {
var _parentInstance$child3;
const index = (_parentInstance$child3 = parentInstance.children) === null || _parentInstance$child3 === void 0 ? void 0 : _parentInstance$child3.indexOf(child);
if (index === undefined) return;
if (index !== -1) parentInstance.children.splice(index, 1);
};
const commitTextUpdate = (textInstance, oldText, newText) => {
textInstance.value = newText;
};
const commitUpdate = (instance, updatePayload, type, oldProps, newProps) => {
const {
style,
...props
} = newProps;
instance.props = props;
instance.style = style;
};
const createRenderer = _ref2 => {
let {
onChange = () => {}
} = _ref2;
return Reconciler({
appendChild,
appendChildToContainer,
commitTextUpdate,
commitUpdate,
createInstance,
createTextInstance,
insertBefore,
removeChild,
removeChildFromContainer,
resetAfterCommit: onChange
});
};
var version$1 = "4.3.0";
var packageJson = {
version: version$1};
const {
version
} = packageJson;
const fontStore = new FontStore();
// We must keep a single renderer instance, otherwise React will complain
let renderer;
// The pdf instance acts as an event emitter for DOM usage.
// We only want to trigger an update when PDF content changes
const events = {};
const pdf = initialValue => {
const onChange = () => {
var _events$change;
const listeners = ((_events$change = events.change) === null || _events$change === void 0 ? void 0 : _events$change.slice()) || [];
for (let i = 0; i < listeners.length; i += 1) listeners[i]();
};
const container = {
type: 'ROOT',
document: null
};
renderer = renderer || createRenderer({
onChange
});
const mountNode = renderer.createContainer(container);
const updateContainer = (doc, callback) => {
renderer.updateContainer(doc, mountNode, null, callback);
};
if (initialValue) updateContainer(initialValue);
const render = async function (compress) {
if (compress === void 0) {
compress = true;
}
const props = container.document.props || {};
const {
pdfVersion,
language,
pageLayout,
pageMode,
title,
author,
subject,
keyboards,
creator = 'react-pdf',
producer = 'react-pdf',
creationDate = new Date(),
modificationDate
} = props;
const ctx = new PDFDocument({
compress,
pdfVersion,
lang: language,
displayTitle: true,
autoFirstPage: false,
info: omitNils({
Title: title,
Author: author,
Subject: subject,
Keywords: keyboards,
Creator: creator,
Producer: producer,
CreationDate: creationDate,
ModificationDate: modificationDate
})
});
if (pageLayout) {
ctx._root.data.PageLayout = upperFirst(pageLayout);
}
if (pageMode) {
ctx._root.data.PageMode = upperFirst(pageMode);
}
const layout = await layoutDocument(container.document, fontStore);
const fileStream = renderPDF(ctx, layout);
return {
layout,
fileStream
};
};
const callOnRender = function (params) {
if (params === void 0) {
params = {};
}
if (container.document.props.onRender) {
container.document.props.onRender(params);
}
};
const toBlob = async () => {
const chunks = [];
const {
layout: _INTERNAL__LAYOUT__DATA_,
fileStream: instance
} = await render();
return new Promise((resolve, reject) => {
instance.on('data', chunk => {
chunks.push(chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk));
});
instance.on('end', () => {
try {
const blob = new Blob(chunks, {
type: 'application/pdf'
});
callOnRender({
blob,
_INTERNAL__LAYOUT__DATA_
});
resolve(blob);
} catch (error) {
reject(error);
}
});
});
};
// TODO: rename this method to `toStream` in next major release, because it return stream not a buffer
const toBuffer = async () => {
const {
layout: _INTERNAL__LAYOUT__DATA_,
fileStream
} = await render();
callOnRender({
_INTERNAL__LAYOUT__DATA_
});
return fileStream;
};
/*
* TODO: remove this method in next major release. it is buggy
* see
* - https://github.com/diegomura/react-pdf/issues/2112
* - https://github.com/diegomura/react-pdf/issues/2095
*/
const toString = async () => {
if (process.env.NODE_ENV === 'development') {
console.warn('`toString` is deprecated and will be removed in next major release');
}
let result = '';
const {
fileStream: instance
} = await render(false); // For some reason, when rendering to string if compress=true the document is blank
return new Promise((resolve, reject) => {
try {
instance.on('data', buffer => {
result += buffer;
});
instance.on('end', () => {
callOnRender();
resolve(result);
});
} catch (error) {
reject(error);
}
});
};
const on = (event, listener) => {
if (!events[event]) events[event] = [];
events[event].push(listener);
};
const removeListener = (event, listener) => {
if (!events[event]) return;
const idx = events[event].indexOf(listener);
if (idx > -1) events[event].splice(idx, 1);
};
return {
on,
container,
toBlob,
toBuffer,
toString,
removeListener,
updateContainer
};
};
const Font = fontStore;
const StyleSheet = {
create: s => s
};
/**
* @param {React.ReactElement} element
* @returns {Promise<NodeJS.ReadableStream>}
*/
const renderToStream = async element => {
const instance = pdf(element);
const stream = await instance.toBuffer();
return stream;
};
/**
* @param {React.ReactElement} element
* @param {string} filePath
* @param {Function} [callback]
*/
const renderToFile = async (element, filePath, callback) => {
const output = await renderToStream(element);
const stream = fs.createWriteStream(filePath);
output.pipe(stream);
return new Promise((resolve, reject) => {
stream.on('finish', () => {
if (callback) callback(output, filePath);
resolve(output);
});
stream.on('error', reject);
});
};
/**
* @param {React.ReactElement} element
* @returns {Promise<Buffer>}
*/
const renderToBuffer = element => renderToStream(element).then(stream => new Promise((resolve, reject) => {
const chunks = [];
stream.on('data', chunk => chunks.push(chunk));
stream.on('end', () => resolve(Buffer.concat(chunks)));
stream.on('error', error => reject(error));
}));
const renderToString = element => {
if (process.env.NODE_ENV === 'development') {
console.warn('`renderToString` is deprecated and will be removed in next major release, use `renderToBuffer` instead');
}
return renderToBuffer(element).then(buffer => buffer.toString());
};
const throwEnvironmentError = name => {
throw new Error(`${name} is a web specific API. You're either using this component on Node, or your bundler is not loading react-pdf from the appropriate web build.`);
};
const usePDF = () => {
throwEnvironmentError('usePDF');
};
const PDFViewer = () => {
throwEnvironmentError('PDFViewer');
};
const PDFDownloadLink = () => {
throwEnvironmentError('PDFDownloadLink');
};
const BlobProvider = () => {
throwEnvironmentError('BlobProvider');
};
const render = renderToFile;
// TODO: remove this default export in next major release because it breaks tree-shacking
var index = {
pdf,
Font,
version,
StyleSheet,
usePDF,
PDFViewer,
BlobProvider,
PDFDownloadLink,
renderToStream,
renderToString,
renderToFile,
render,
...primitives
};
export { BlobProvider, Font, PDFDownloadLink, PDFViewer, StyleSheet, createRenderer, index as default, pdf, render, renderToBuffer, renderToFile, renderToStream, renderToString, usePDF, version };
//# sourceMappingURL=react-pdf.js.map
File diff suppressed because one or more lines are too long
+691
View File
@@ -0,0 +1,691 @@
/* eslint-disable max-classes-per-file */
import * as React from 'react';
import {
Style,
PageSize,
FontStore,
PDFVersion,
Orientation,
SourceObject,
HyphenationCallback,
SVGPresentationAttributes,
Bookmark,
PageLayout,
PageMode,
} from '@react-pdf/types';
declare class ReactPDF {
static default: typeof ReactPDF;
}
export = ReactPDF;
declare namespace ReactPDF {
interface Styles {
[key: string]: Style;
}
interface OnRenderProps {
blob?: Blob;
}
interface DocumentProps {
style?: Style | Style[];
title?: string;
author?: string;
subject?: string;
creator?: string;
keywords?: string;
producer?: string;
language?: string;
creationDate?: Date;
modificationDate?: Date;
pdfVersion?: PDFVersion;
pageMode?: PageMode;
pageLayout?: PageLayout;
onRender?: (props: OnRenderProps) => any;
}
/**
* This component represent the PDF document itself. It must be the root
* of your tree element structure, and under no circumstances should it be
* used as children of another react-pdf component. In addition, it should
* only have childs of type <Page />.
*/
export class Document extends React.Component<
React.PropsWithChildren<DocumentProps>
> {}
interface NodeProps {
id?: string;
style?: Style | Style[];
/**
* Render component in all wrapped pages.
* @see https://react-pdf.org/advanced#fixed-components
*/
fixed?: boolean;
/**
* Force the wrapping algorithm to start a new page when rendering the
* element.
* @see https://react-pdf.org/advanced#page-breaks
*/
break?: boolean;
/**
* Hint that no page wrapping should occur between all sibling elements following the element within n points
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
minPresenceAhead?: number;
}
interface PageProps extends NodeProps {
/**
* Enable page wrapping for this page.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
size?: PageSize;
orientation?: Orientation;
dpi?: number;
bookmark?: Bookmark;
}
/**
* Represents single page inside the PDF document, or a subset of them if
* using the wrapping feature. A <Document /> can contain as many pages as
* you want, but ensure not rendering a page inside any component besides
* Document.
*/
export class Page extends React.Component<
React.PropsWithChildren<PageProps>
> {}
interface ViewProps extends NodeProps {
id?: string;
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
render?: (props: {
pageNumber: number;
subPageNumber: number;
}) => React.ReactNode;
}
/**
* The most fundamental component for building a UI and is designed to be
* nested inside other views and can have 0 to many children.
*/
export class View extends React.Component<
React.PropsWithChildren<ViewProps>
> {}
interface BaseImageProps extends NodeProps {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
cache?: boolean;
}
interface ImageWithSrcProp extends BaseImageProps {
src: SourceObject;
}
interface ImageWithSourceProp extends BaseImageProps {
source: SourceObject;
}
type ImageProps = ImageWithSrcProp | ImageWithSourceProp;
/**
* A React component for displaying network or local (Node only) JPG or
* PNG images, as well as base64 encoded image strings.
*/
export class Image extends React.Component<ImageProps> {}
interface TextProps extends NodeProps {
id?: string;
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
render?: (props: {
pageNumber: number;
totalPages: number;
subPageNumber: number;
subPageTotalPages: number;
}) => React.ReactNode;
/**
* Override the default hyphenation-callback
* @see https://react-pdf.org/fonts#registerhyphenationcallback
*/
hyphenationCallback?: HyphenationCallback;
/**
* Specifies the minimum number of lines in a text element that must be shown at the bottom of a page or its container.
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
orphans?: number;
/**
* Specifies the minimum number of lines in a text element that must be shown at the top of a page or its container..
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
widows?: number;
}
interface SVGTextProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x: string | number;
y: string | number;
/**
* Override the default hyphenation-callback
* @see https://react-pdf.org/fonts#registerhyphenationcallback
*/
hyphenationCallback?: HyphenationCallback;
}
/**
* A React component for displaying text. Text supports nesting of other
* Text or Link components to create inline styling.
*/
export class Text extends React.Component<
React.PropsWithChildren<TextProps> | SVGTextProps
> {}
interface LinkProps extends NodeProps {
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
href?: string;
src?: string;
}
/**
* A React component for displaying a hyperlink. Links can be nested
* inside a Text component, or being inside any other valid primitive.
*/
export class Link extends React.Component<
React.PropsWithChildren<LinkProps>
> {}
interface FormCommonProps extends NodeProps {
name?: string;
required?: boolean;
noExport?: boolean;
readOnly?: boolean;
value?: number | string;
defaultValue?: number | string;
}
interface FieldSetProps extends NodeProps {
name: string;
}
export class FieldSet extends React.Component<
React.PropsWithChildren<FieldSetProps>
> {}
// see http://pdfkit.org/docs/forms.html#text_field_formatting
interface TextInputFormatting {
type:
| 'date'
| 'time'
| 'percent'
| 'number'
| 'zip'
| 'zipPlus4'
| 'phone'
| 'ssn';
param?: string;
nDec?: number;
sepComma?: boolean;
negStyle?: 'MinusBlack' | 'Red' | 'ParensBlack' | 'ParensRed';
currency?: string;
currencyPrepend?: boolean;
}
// see http://pdfkit.org/docs/forms.html#text_field_formatting
interface TextInputProps extends FormCommonProps {
align?: 'left' | 'center' | 'right';
multiline?: boolean;
/**
* The text will be masked (e.g. with asterisks).
*/
password?: boolean;
/**
* If set, text entered in the field is not spell-checked
*/
noSpell?: boolean;
format?: TextInputFormatting;
/**
* Sets the fontSize (default or 0 means auto sizing)
*/
fontSize?: number;
/**
* Sets the maximum length (characters) of the text in the field
*/
maxLength?: number;
}
export class TextInput extends React.Component<TextInputProps> {}
interface CheckboxProps extends FormCommonProps {
backgroundColor?: string;
borderColor?: string;
checked?: boolean;
onState?: string;
offState?: string;
xMark?: boolean;
}
export class Checkbox extends React.Component<CheckboxProps> {}
interface SelectAndListPropsBase extends FormCommonProps {
sort?: boolean;
edit?: boolean;
multiSelect?: boolean;
noSpell?: boolean;
select?: string[];
}
type SelectAndListPropsWithEdit = SelectAndListPropsBase & {
edit: true | false;
noSpell: boolean;
};
type SelectAndListPropsWithNoSpell = SelectAndListPropsBase & {
edit: boolean;
noSpell: true | false;
};
type SelectAndListProps =
| SelectAndListPropsWithEdit
| SelectAndListPropsWithNoSpell;
export class Select extends React.Component<SelectAndListProps> {}
export class List extends React.Component<SelectAndListProps> {}
interface NoteProps extends NodeProps {
children: string;
}
export class Note extends React.Component<NoteProps> {}
interface CanvasProps extends NodeProps {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
paint: (
painter: any,
availableWidth: number,
availableHeight: number,
) => null;
}
export class Canvas extends React.Component<CanvasProps> {}
interface SVGProps extends NodeProps, SVGPresentationAttributes {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
width?: string | number;
height?: string | number;
viewBox?: string;
preserveAspectRatio?: string;
}
/**
* The <SVG /> element is a container that defines a new coordinate system and viewport. It is used as the outermost element of SVG documents.
*/
export class Svg extends React.Component<React.PropsWithChildren<SVGProps>> {}
interface LineProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x1: string | number;
x2: string | number;
y1: string | number;
y2: string | number;
}
/**
* The <Line /> element is used to create a line.
*/
export class Line extends React.Component<
React.PropsWithChildren<LineProps>
> {}
interface PolylineProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
points: string;
}
/**
* The <Polyline /> element is used to create any shape that consists of only straight lines (that is connected at several points).
*/
export class Polyline extends React.Component<
React.PropsWithChildren<PolylineProps>
> {}
interface PolygonProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
points: string;
}
/**
* The <Polygon /> element is used to create a graphic that contains at least three sides.
* Polygons are made of straight lines, and the shape is "closed" (all the lines connect up).
*/
export class Polygon extends React.Component<
React.PropsWithChildren<PolygonProps>
> {}
interface PathProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
d: string;
}
/**
* The <Path /> element is the most powerful element in the SVG library of basic shapes. It can be used to create lines, curves, arcs, and more.
*/
export class Path extends React.Component<
React.PropsWithChildren<PathProps>
> {}
interface RectProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x?: string | number;
y?: string | number;
width: string | number;
height: string | number;
rx?: string | number;
ry?: string | number;
}
/**
* The <Rect /> element is used to create a rectangle and variations of a rectangle shape.
*/
export class Rect extends React.Component<
React.PropsWithChildren<RectProps>
> {}
interface CircleProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
cx?: string | number;
cy?: string | number;
r: string | number;
}
/**
* The <Circle /> element is used to create a circle.
*/
export class Circle extends React.Component<
React.PropsWithChildren<CircleProps>
> {}
interface EllipseProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
cx?: string | number;
cy?: string | number;
rx: string | number;
ry: string | number;
}
/**
* The <Ellipse /> element is used to create an ellipse.
* An ellipse is closely related to a circle. The difference is that an ellipse has an x and a y radius that differs from each other, while a circle has equal x and y radius.
*/
export class Ellipse extends React.Component<
React.PropsWithChildren<EllipseProps>
> {}
interface TspanProps extends SVGPresentationAttributes {
x?: string | number;
y?: string | number;
}
/**
* The <Tspan /> element defines a subtext within a <Text /> element or another <Tspan /> element.
* It allows for adjustment of the style and/or position of that subtext as needed.
*/
export class Tspan extends React.Component<
React.PropsWithChildren<TspanProps>
> {}
interface GProps extends SVGPresentationAttributes {
style?: Style;
}
/**
* The <G /> SVG element is a container used to group other SVG elements.
* Transformations applied to the <G /> element are performed on its child elements, and its attributes are inherited by its children.
*/
export class G extends React.Component<React.PropsWithChildren<GProps>> {}
interface StopProps {
offset: string | number;
stopColor: string;
stopOpacity?: string | number;
}
/**
* The SVG <Stop /> element defines a color and its position to use on a gradient. This element is always a child of a <LinearGradient /> or <RadialGradient /> element
*/
export class Stop extends React.Component<
React.PropsWithChildren<StopProps>
> {}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface DefsProps {}
/**
* The <Defs /> element is used to store graphical objects that will be used at a later time. Objects created inside a <Defs /> element are not rendered directly. To display them you have to reference them
*/
export class Defs extends React.Component<
React.PropsWithChildren<DefsProps>
> {}
interface ClipPathProps {
id?: string;
}
/**
* The <ClipPath /> SVG element defines a clipping path, to be used by the clipPath property.
* A clipping path restricts the region to which paint can be applied. Conceptually, parts of the drawing that lie outside of the region bounded by the clipping path are not drawn.
*/
export class ClipPath extends React.Component<
React.PropsWithChildren<ClipPathProps>
> {}
interface LinearGradientProps {
id: string;
x1?: string | number;
x2?: string | number;
y1?: string | number;
y2?: string | number;
xlinkHref?: string;
gradientTransform?: string;
gradientUnits?: 'userSpaceOnUse' | 'objectBoundingBox';
}
/**
* The <LinearGradient /> element lets authors define linear gradients that can be applied to fill or stroke of graphical elements.
*/
export class LinearGradient extends React.Component<
React.PropsWithChildren<LinearGradientProps>
> {}
interface RadialGradientProps {
id: string;
cx?: string | number;
cy?: string | number;
r?: string | number;
fx?: string | number;
fy?: string | number;
xlinkHref?: string;
gradientTransform?: string;
gradientUnits?: 'userSpaceOnUse' | 'objectBoundingBox';
}
/**
* The <RadialGradient /> element lets authors define radial gradients that can be applied to fill or stroke of graphical elements.
*/
export class RadialGradient extends React.Component<
React.PropsWithChildren<RadialGradientProps>
> {}
interface BlobProviderParams {
blob: Blob | null;
url: string | null;
loading: boolean;
error: Error | null;
}
interface BlobProviderProps {
document: React.ReactElement<DocumentProps>;
children: (params: BlobProviderParams) => React.ReactNode;
}
/**
* Easy and declarative way of getting document's blob data without
* showing it on screen.
* @see https://react-pdf.org/advanced#on-the-fly-rendering
* @platform web
*/
export class BlobProvider extends React.Component<BlobProviderProps> {}
interface PDFViewerProps {
width?: number | string;
height?: number | string;
style?: Style | Style[];
className?: string;
children?: React.ReactElement<DocumentProps>;
innerRef?: React.Ref<HTMLIFrameElement>;
showToolbar?: boolean;
}
/**
* Iframe PDF viewer for client-side generated documents.
* @platform web
*/
export class PDFViewer extends React.Component<PDFViewerProps> {}
interface PDFDownloadLinkProps
extends Omit<
React.AnchorHTMLAttributes<HTMLAnchorElement>,
'href' | 'children'
> {
/** PDF filename. Alias for anchor tag `download` attribute. */
fileName?: string;
document: React.ReactElement<DocumentProps>;
children?: React.ReactNode | React.FC<BlobProviderParams>;
onClick?: React.AnchorHTMLAttributes<HTMLAnchorElement>['onClick'] &
((
event: React.MouseEvent<HTMLAnchorElement, MouseEvent>,
instance: UsePDFInstance,
) => void);
}
/**
* Anchor tag to enable generate and download PDF documents on the fly.
* @see https://react-pdf.org/advanced#on-the-fly-rendering
* @platform web
*/
export class PDFDownloadLink extends React.Component<PDFDownloadLinkProps> {}
interface UsePDFInstance {
loading: boolean;
blob: Blob | null;
url: string | null;
error: string | null;
}
/**
* React hook for creating and updating a PDF document instance
* @platform web
*/
export function usePDF(options?: {
document?: React.ReactElement<DocumentProps>;
}): [
UsePDFInstance,
(newDocument: React.ReactElement<DocumentProps>) => void,
];
export const Font: FontStore;
export const StyleSheet: {
create: <T extends Styles>(styles: T) => T;
};
export const version: any;
export const PDFRenderer: any;
export const pdf: (initialValue?: React.ReactElement<DocumentProps>) => {
container: any;
isDirty: () => boolean;
toString: () => string;
toBlob: () => Promise<Blob>;
toBuffer: () => Promise<NodeJS.ReadableStream>;
on: (event: 'change', callback: () => void) => void;
updateContainer: (
document: React.ReactElement<any>,
callback?: () => void,
) => void;
removeListener: (event: 'change', callback: () => void) => void;
};
export const renderToStream: (
document: React.ReactElement<DocumentProps>,
) => Promise<NodeJS.ReadableStream>;
/**
* @deprecated use the `renderToBuffer` method
*/
export const renderToString: (
document: React.ReactElement<DocumentProps>,
) => Promise<string>;
export const renderToFile: (
document: React.ReactElement<DocumentProps>,
filePath: string,
callback?: (output: NodeJS.ReadableStream, _filePath: string) => any,
) => Promise<NodeJS.ReadableStream>;
const render: typeof renderToFile;
/**
* Render document into a nodejs buffer
* @platform node
*/
export const renderToBuffer: (
document: React.ReactElement<ReactPDF.DocumentProps>,
) => Promise<Buffer>;
}
+691
View File
@@ -0,0 +1,691 @@
/* eslint-disable max-classes-per-file */
import * as React from 'react';
import {
Style,
PageSize,
FontStore,
PDFVersion,
Orientation,
SourceObject,
HyphenationCallback,
SVGPresentationAttributes,
Bookmark,
PageLayout,
PageMode,
} from '@react-pdf/types';
declare class ReactPDF {
static default: typeof ReactPDF;
}
export = ReactPDF;
declare namespace ReactPDF {
interface Styles {
[key: string]: Style;
}
interface OnRenderProps {
blob?: Blob;
}
interface DocumentProps {
style?: Style | Style[];
title?: string;
author?: string;
subject?: string;
creator?: string;
keywords?: string;
producer?: string;
language?: string;
creationDate?: Date;
modificationDate?: Date;
pdfVersion?: PDFVersion;
pageMode?: PageMode;
pageLayout?: PageLayout;
onRender?: (props: OnRenderProps) => any;
}
/**
* This component represent the PDF document itself. It must be the root
* of your tree element structure, and under no circumstances should it be
* used as children of another react-pdf component. In addition, it should
* only have childs of type <Page />.
*/
export class Document extends React.Component<
React.PropsWithChildren<DocumentProps>
> {}
interface NodeProps {
id?: string;
style?: Style | Style[];
/**
* Render component in all wrapped pages.
* @see https://react-pdf.org/advanced#fixed-components
*/
fixed?: boolean;
/**
* Force the wrapping algorithm to start a new page when rendering the
* element.
* @see https://react-pdf.org/advanced#page-breaks
*/
break?: boolean;
/**
* Hint that no page wrapping should occur between all sibling elements following the element within n points
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
minPresenceAhead?: number;
}
interface PageProps extends NodeProps {
/**
* Enable page wrapping for this page.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
size?: PageSize;
orientation?: Orientation;
dpi?: number;
bookmark?: Bookmark;
}
/**
* Represents single page inside the PDF document, or a subset of them if
* using the wrapping feature. A <Document /> can contain as many pages as
* you want, but ensure not rendering a page inside any component besides
* Document.
*/
export class Page extends React.Component<
React.PropsWithChildren<PageProps>
> {}
interface ViewProps extends NodeProps {
id?: string;
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
render?: (props: {
pageNumber: number;
subPageNumber: number;
}) => React.ReactNode;
}
/**
* The most fundamental component for building a UI and is designed to be
* nested inside other views and can have 0 to many children.
*/
export class View extends React.Component<
React.PropsWithChildren<ViewProps>
> {}
interface BaseImageProps extends NodeProps {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
cache?: boolean;
}
interface ImageWithSrcProp extends BaseImageProps {
src: SourceObject;
}
interface ImageWithSourceProp extends BaseImageProps {
source: SourceObject;
}
type ImageProps = ImageWithSrcProp | ImageWithSourceProp;
/**
* A React component for displaying network or local (Node only) JPG or
* PNG images, as well as base64 encoded image strings.
*/
export class Image extends React.Component<ImageProps> {}
interface TextProps extends NodeProps {
id?: string;
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
render?: (props: {
pageNumber: number;
totalPages: number;
subPageNumber: number;
subPageTotalPages: number;
}) => React.ReactNode;
/**
* Override the default hyphenation-callback
* @see https://react-pdf.org/fonts#registerhyphenationcallback
*/
hyphenationCallback?: HyphenationCallback;
/**
* Specifies the minimum number of lines in a text element that must be shown at the bottom of a page or its container.
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
orphans?: number;
/**
* Specifies the minimum number of lines in a text element that must be shown at the top of a page or its container..
* @see https://react-pdf.org/advanced#orphan-&-widow-protection
*/
widows?: number;
}
interface SVGTextProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x: string | number;
y: string | number;
/**
* Override the default hyphenation-callback
* @see https://react-pdf.org/fonts#registerhyphenationcallback
*/
hyphenationCallback?: HyphenationCallback;
}
/**
* A React component for displaying text. Text supports nesting of other
* Text or Link components to create inline styling.
*/
export class Text extends React.Component<
React.PropsWithChildren<TextProps> | SVGTextProps
> {}
interface LinkProps extends NodeProps {
/**
* Enable/disable page wrapping for element.
* @see https://react-pdf.org/components#page-wrapping
*/
wrap?: boolean;
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
href?: string;
src?: string;
}
/**
* A React component for displaying a hyperlink. Links can be nested
* inside a Text component, or being inside any other valid primitive.
*/
export class Link extends React.Component<
React.PropsWithChildren<LinkProps>
> {}
interface FormCommonProps extends NodeProps {
name?: string;
required?: boolean;
noExport?: boolean;
readOnly?: boolean;
value?: number | string;
defaultValue?: number | string;
}
interface FieldSetProps extends NodeProps {
name: string;
}
export class FieldSet extends React.Component<
React.PropsWithChildren<FieldSetProps>
> {}
// see http://pdfkit.org/docs/forms.html#text_field_formatting
interface TextInputFormatting {
type:
| 'date'
| 'time'
| 'percent'
| 'number'
| 'zip'
| 'zipPlus4'
| 'phone'
| 'ssn';
param?: string;
nDec?: number;
sepComma?: boolean;
negStyle?: 'MinusBlack' | 'Red' | 'ParensBlack' | 'ParensRed';
currency?: string;
currencyPrepend?: boolean;
}
// see http://pdfkit.org/docs/forms.html#text_field_formatting
interface TextInputProps extends FormCommonProps {
align?: 'left' | 'center' | 'right';
multiline?: boolean;
/**
* The text will be masked (e.g. with asterisks).
*/
password?: boolean;
/**
* If set, text entered in the field is not spell-checked
*/
noSpell?: boolean;
format?: TextInputFormatting;
/**
* Sets the fontSize (default or 0 means auto sizing)
*/
fontSize?: number;
/**
* Sets the maximum length (characters) of the text in the field
*/
maxLength?: number;
}
export class TextInput extends React.Component<TextInputProps> {}
interface CheckboxProps extends FormCommonProps {
backgroundColor?: string;
borderColor?: string;
checked?: boolean;
onState?: string;
offState?: string;
xMark?: boolean;
}
export class Checkbox extends React.Component<CheckboxProps> {}
interface SelectAndListPropsBase extends FormCommonProps {
sort?: boolean;
edit?: boolean;
multiSelect?: boolean;
noSpell?: boolean;
select?: string[];
}
type SelectAndListPropsWithEdit = SelectAndListPropsBase & {
edit: true | false;
noSpell: boolean;
};
type SelectAndListPropsWithNoSpell = SelectAndListPropsBase & {
edit: boolean;
noSpell: true | false;
};
type SelectAndListProps =
| SelectAndListPropsWithEdit
| SelectAndListPropsWithNoSpell;
export class Select extends React.Component<SelectAndListProps> {}
export class List extends React.Component<SelectAndListProps> {}
interface NoteProps extends NodeProps {
children: string;
}
export class Note extends React.Component<NoteProps> {}
interface CanvasProps extends NodeProps {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
paint: (
painter: any,
availableWidth: number,
availableHeight: number,
) => null;
}
export class Canvas extends React.Component<CanvasProps> {}
interface SVGProps extends NodeProps, SVGPresentationAttributes {
/**
* Enables debug mode on page bounding box.
* @see https://react-pdf.org/advanced#debugging
*/
debug?: boolean;
width?: string | number;
height?: string | number;
viewBox?: string;
preserveAspectRatio?: string;
}
/**
* The <SVG /> element is a container that defines a new coordinate system and viewport. It is used as the outermost element of SVG documents.
*/
export class Svg extends React.Component<React.PropsWithChildren<SVGProps>> {}
interface LineProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x1: string | number;
x2: string | number;
y1: string | number;
y2: string | number;
}
/**
* The <Line /> element is used to create a line.
*/
export class Line extends React.Component<
React.PropsWithChildren<LineProps>
> {}
interface PolylineProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
points: string;
}
/**
* The <Polyline /> element is used to create any shape that consists of only straight lines (that is connected at several points).
*/
export class Polyline extends React.Component<
React.PropsWithChildren<PolylineProps>
> {}
interface PolygonProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
points: string;
}
/**
* The <Polygon /> element is used to create a graphic that contains at least three sides.
* Polygons are made of straight lines, and the shape is "closed" (all the lines connect up).
*/
export class Polygon extends React.Component<
React.PropsWithChildren<PolygonProps>
> {}
interface PathProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
d: string;
}
/**
* The <Path /> element is the most powerful element in the SVG library of basic shapes. It can be used to create lines, curves, arcs, and more.
*/
export class Path extends React.Component<
React.PropsWithChildren<PathProps>
> {}
interface RectProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
x?: string | number;
y?: string | number;
width: string | number;
height: string | number;
rx?: string | number;
ry?: string | number;
}
/**
* The <Rect /> element is used to create a rectangle and variations of a rectangle shape.
*/
export class Rect extends React.Component<
React.PropsWithChildren<RectProps>
> {}
interface CircleProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
cx?: string | number;
cy?: string | number;
r: string | number;
}
/**
* The <Circle /> element is used to create a circle.
*/
export class Circle extends React.Component<
React.PropsWithChildren<CircleProps>
> {}
interface EllipseProps extends SVGPresentationAttributes {
style?: SVGPresentationAttributes;
cx?: string | number;
cy?: string | number;
rx: string | number;
ry: string | number;
}
/**
* The <Ellipse /> element is used to create an ellipse.
* An ellipse is closely related to a circle. The difference is that an ellipse has an x and a y radius that differs from each other, while a circle has equal x and y radius.
*/
export class Ellipse extends React.Component<
React.PropsWithChildren<EllipseProps>
> {}
interface TspanProps extends SVGPresentationAttributes {
x?: string | number;
y?: string | number;
}
/**
* The <Tspan /> element defines a subtext within a <Text /> element or another <Tspan /> element.
* It allows for adjustment of the style and/or position of that subtext as needed.
*/
export class Tspan extends React.Component<
React.PropsWithChildren<TspanProps>
> {}
interface GProps extends SVGPresentationAttributes {
style?: Style;
}
/**
* The <G /> SVG element is a container used to group other SVG elements.
* Transformations applied to the <G /> element are performed on its child elements, and its attributes are inherited by its children.
*/
export class G extends React.Component<React.PropsWithChildren<GProps>> {}
interface StopProps {
offset: string | number;
stopColor: string;
stopOpacity?: string | number;
}
/**
* The SVG <Stop /> element defines a color and its position to use on a gradient. This element is always a child of a <LinearGradient /> or <RadialGradient /> element
*/
export class Stop extends React.Component<
React.PropsWithChildren<StopProps>
> {}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface DefsProps {}
/**
* The <Defs /> element is used to store graphical objects that will be used at a later time. Objects created inside a <Defs /> element are not rendered directly. To display them you have to reference them
*/
export class Defs extends React.Component<
React.PropsWithChildren<DefsProps>
> {}
interface ClipPathProps {
id?: string;
}
/**
* The <ClipPath /> SVG element defines a clipping path, to be used by the clipPath property.
* A clipping path restricts the region to which paint can be applied. Conceptually, parts of the drawing that lie outside of the region bounded by the clipping path are not drawn.
*/
export class ClipPath extends React.Component<
React.PropsWithChildren<ClipPathProps>
> {}
interface LinearGradientProps {
id: string;
x1?: string | number;
x2?: string | number;
y1?: string | number;
y2?: string | number;
xlinkHref?: string;
gradientTransform?: string;
gradientUnits?: 'userSpaceOnUse' | 'objectBoundingBox';
}
/**
* The <LinearGradient /> element lets authors define linear gradients that can be applied to fill or stroke of graphical elements.
*/
export class LinearGradient extends React.Component<
React.PropsWithChildren<LinearGradientProps>
> {}
interface RadialGradientProps {
id: string;
cx?: string | number;
cy?: string | number;
r?: string | number;
fx?: string | number;
fy?: string | number;
xlinkHref?: string;
gradientTransform?: string;
gradientUnits?: 'userSpaceOnUse' | 'objectBoundingBox';
}
/**
* The <RadialGradient /> element lets authors define radial gradients that can be applied to fill or stroke of graphical elements.
*/
export class RadialGradient extends React.Component<
React.PropsWithChildren<RadialGradientProps>
> {}
interface BlobProviderParams {
blob: Blob | null;
url: string | null;
loading: boolean;
error: Error | null;
}
interface BlobProviderProps {
document: React.ReactElement<DocumentProps>;
children: (params: BlobProviderParams) => React.ReactNode;
}
/**
* Easy and declarative way of getting document's blob data without
* showing it on screen.
* @see https://react-pdf.org/advanced#on-the-fly-rendering
* @platform web
*/
export class BlobProvider extends React.Component<BlobProviderProps> {}
interface PDFViewerProps {
width?: number | string;
height?: number | string;
style?: Style | Style[];
className?: string;
children?: React.ReactElement<DocumentProps>;
innerRef?: React.Ref<HTMLIFrameElement>;
showToolbar?: boolean;
}
/**
* Iframe PDF viewer for client-side generated documents.
* @platform web
*/
export class PDFViewer extends React.Component<PDFViewerProps> {}
interface PDFDownloadLinkProps
extends Omit<
React.AnchorHTMLAttributes<HTMLAnchorElement>,
'href' | 'children'
> {
/** PDF filename. Alias for anchor tag `download` attribute. */
fileName?: string;
document: React.ReactElement<DocumentProps>;
children?: React.ReactNode | React.FC<BlobProviderParams>;
onClick?: React.AnchorHTMLAttributes<HTMLAnchorElement>['onClick'] &
((
event: React.MouseEvent<HTMLAnchorElement, MouseEvent>,
instance: UsePDFInstance,
) => void);
}
/**
* Anchor tag to enable generate and download PDF documents on the fly.
* @see https://react-pdf.org/advanced#on-the-fly-rendering
* @platform web
*/
export class PDFDownloadLink extends React.Component<PDFDownloadLinkProps> {}
interface UsePDFInstance {
loading: boolean;
blob: Blob | null;
url: string | null;
error: string | null;
}
/**
* React hook for creating and updating a PDF document instance
* @platform web
*/
export function usePDF(options?: {
document?: React.ReactElement<DocumentProps>;
}): [
UsePDFInstance,
(newDocument: React.ReactElement<DocumentProps>) => void,
];
export const Font: FontStore;
export const StyleSheet: {
create: <T extends Styles>(styles: T) => T;
};
export const version: any;
export const PDFRenderer: any;
export const pdf: (initialValue?: React.ReactElement<DocumentProps>) => {
container: any;
isDirty: () => boolean;
toString: () => string;
toBlob: () => Promise<Blob>;
toBuffer: () => Promise<NodeJS.ReadableStream>;
on: (event: 'change', callback: () => void) => void;
updateContainer: (
document: React.ReactElement<any>,
callback?: () => void,
) => void;
removeListener: (event: 'change', callback: () => void) => void;
};
export const renderToStream: (
document: React.ReactElement<DocumentProps>,
) => Promise<NodeJS.ReadableStream>;
/**
* @deprecated use the `renderToBuffer` method
*/
export const renderToString: (
document: React.ReactElement<DocumentProps>,
) => Promise<string>;
export const renderToFile: (
document: React.ReactElement<DocumentProps>,
filePath: string,
callback?: (output: NodeJS.ReadableStream, _filePath: string) => any,
) => Promise<NodeJS.ReadableStream>;
const render: typeof renderToFile;
/**
* Render document into a nodejs buffer
* @platform node
*/
export const renderToBuffer: (
document: React.ReactElement<ReactPDF.DocumentProps>,
) => Promise<Buffer>;
}
+1
View File
@@ -0,0 +1 @@
import*as e from"@react-pdf/primitives";export*from"@react-pdf/primitives";import t from"fs";import{Buffer as r}from"buffer";import o from"@react-pdf/font";import n from"@react-pdf/render";import i from"@react-pdf/pdfkit";import a from"@react-pdf/layout";import{upperFirst as d}from"@react-pdf/fns";import c from"@react-pdf/reconciler";const s=(e,t)=>{let{style:r,children:o,...n}=t;return{type:e,box:{},style:r||{},props:n||{},children:[]}},l=e=>({type:"TEXT_INSTANCE",value:e}),p=(e,t)=>{const r="TEXT"===e.type||"LINK"===e.type||"TSPAN"===e.type||"NOTE"===e.type;"TEXT_INSTANCE"!==t.type||r?e.children.push(t):console.warn(`Invalid '${t.value}' string child outside <Text> component`)},u=(e,t)=>{"ROOT"===e.type?e.document=t:p(e,t)},f=(e,t,r)=>{var o;const n=null===(o=e.children)||void 0===o?void 0:o.indexOf(r);void 0!==n&&-1!==n&&t&&e.children.splice(n,0,t)},m=(e,t)=>{var r;const o=null===(r=e.children)||void 0===r?void 0:r.indexOf(t);void 0!==o&&-1!==o&&e.children.splice(o,1)},v=(e,t)=>{var r;const o=null===(r=e.children)||void 0===r?void 0:r.indexOf(t);void 0!==o&&-1!==o&&e.children.splice(o,1)},y=(e,t,r)=>{e.value=r},h=(e,t,r,o,n)=>{const{style:i,...a}=n;e.props=a,e.style=i},w=e=>{let{onChange:t=(()=>{})}=e;return c({appendChild:p,appendChildToContainer:u,commitTextUpdate:y,commitUpdate:h,createInstance:s,createTextInstance:l,insertBefore:f,removeChild:m,removeChildFromContainer:v,resetAfterCommit:t})};var T={version:"4.3.0"};const{version:g}=T,b=new o;let P;const _={},D=e=>{const t={type:"ROOT",document:null};P=P||w({onChange:()=>{var e;const t=(null===(e=_.change)||void 0===e?void 0:e.slice())||[];for(let e=0;e<t.length;e+=1)t[e]()}});const r=P.createContainer(t),o=(e,t)=>{P.updateContainer(e,r,null,t)};e&&o(e);const c=async function(e){void 0===e&&(e=!0);const r=t.document.props||{},{pdfVersion:o,language:c,pageLayout:s,pageMode:l,title:p,author:u,subject:f,keyboards:m,creator:v="react-pdf",producer:y="react-pdf",creationDate:h=new Date,modificationDate:w}=r,T=new i({compress:e,pdfVersion:o,lang:c,displayTitle:!0,autoFirstPage:!1,info:(g={Title:p,Author:u,Subject:f,Keywords:m,Creator:v,Producer:y,CreationDate:h,ModificationDate:w},Object.fromEntries(Object.entries(g).filter((e=>{let[,t]=e;return void 0!==t}))))});var g;s&&(T._root.data.PageLayout=d(s)),l&&(T._root.data.PageMode=d(l));const P=await a(t.document,b);return{layout:P,fileStream:n(T,P)}},s=function(e){void 0===e&&(e={}),t.document.props.onRender&&t.document.props.onRender(e)};return{on:(e,t)=>{_[e]||(_[e]=[]),_[e].push(t)},container:t,toBlob:async()=>{const e=[],{layout:t,fileStream:r}=await c();return new Promise(((o,n)=>{r.on("data",(t=>{e.push(t instanceof Uint8Array?t:new Uint8Array(t))})),r.on("end",(()=>{try{const r=new Blob(e,{type:"application/pdf"});s({blob:r,_INTERNAL__LAYOUT__DATA_:t}),o(r)}catch(e){n(e)}}))}))},toBuffer:async()=>{const{layout:e,fileStream:t}=await c();return s({_INTERNAL__LAYOUT__DATA_:e}),t},toString:async()=>{"development"===process.env.NODE_ENV&&console.warn("`toString` is deprecated and will be removed in next major release");let e="";const{fileStream:t}=await c(!1);return new Promise(((r,o)=>{try{t.on("data",(t=>{e+=t})),t.on("end",(()=>{s(),r(e)}))}catch(e){o(e)}}))},removeListener:(e,t)=>{if(!_[e])return;const r=_[e].indexOf(t);r>-1&&_[e].splice(r,1)},updateContainer:o}},S=b,A={create:e=>e},C=async e=>{const t=D(e);return await t.toBuffer()},N=async(e,r,o)=>{const n=await C(e),i=t.createWriteStream(r);return n.pipe(i),new Promise(((e,t)=>{i.on("finish",(()=>{o&&o(n,r),e(n)})),i.on("error",t)}))},O=e=>C(e).then((e=>new Promise(((t,o)=>{const n=[];e.on("data",(e=>n.push(e))),e.on("end",(()=>t(r.concat(n)))),e.on("error",(e=>o(e)))})))),E=e=>("development"===process.env.NODE_ENV&&console.warn("`renderToString` is deprecated and will be removed in next major release, use `renderToBuffer` instead"),O(e).then((e=>e.toString()))),x=e=>{throw new Error(`${e} is a web specific API. You're either using this component on Node, or your bundler is not loading react-pdf from the appropriate web build.`)},F=()=>{x("usePDF")},L=()=>{x("PDFViewer")},I=()=>{x("PDFDownloadLink")},B=()=>{x("BlobProvider")},j=N;var R={pdf:D,Font:S,version:g,StyleSheet:A,usePDF:F,PDFViewer:L,BlobProvider:B,PDFDownloadLink:I,renderToStream:C,renderToString:E,renderToFile:N,render:j,...e};export{B as BlobProvider,S as Font,I as PDFDownloadLink,L as PDFViewer,A as StyleSheet,w as createRenderer,R as default,D as pdf,j as render,O as renderToBuffer,N as renderToFile,C as renderToStream,E as renderToString,F as usePDF,g as version};
+67
View File
@@ -0,0 +1,67 @@
{
"name": "@react-pdf/renderer",
"version": "4.3.0",
"license": "MIT",
"description": "Create PDF files on the browser and server",
"author": "Diego Muracciole <diegomuracciole@gmail.com>",
"homepage": "https://github.com/diegomura/react-pdf#readme",
"type": "module",
"main": "./lib/react-pdf.js",
"browser": {
"./lib/react-pdf.js": "./lib/react-pdf.browser.js"
},
"repository": {
"type": "git",
"url": "https://github.com/diegomura/react-pdf.git",
"directory": "packages/renderer"
},
"scripts": {
"build": "rimraf ./lib && rollup -c",
"watch": "rimraf ./lib && rollup -c -w",
"size": "size-limit",
"lint": "eslint src",
"test": "vitest && vitest --config vitest.browser.config.js"
},
"dependencies": {
"@babel/runtime": "^7.20.13",
"@react-pdf/fns": "3.1.2",
"@react-pdf/font": "^4.0.2",
"@react-pdf/layout": "^4.4.0",
"@react-pdf/pdfkit": "^4.0.3",
"@react-pdf/primitives": "^4.1.1",
"@react-pdf/reconciler": "^1.1.4",
"@react-pdf/render": "^4.3.0",
"@react-pdf/types": "^2.9.0",
"events": "^3.3.0",
"object-assign": "^4.1.1",
"prop-types": "^15.6.2",
"queue": "^6.0.1"
},
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
},
"lint-staged": {
"*.js": [
"yarn lint",
"prettier --write"
]
},
"files": [
"lib",
"index.d.ts"
],
"collective": {
"type": "opencollective",
"url": "https://opencollective.com/react-pdf",
"logo": "https://opencollective.com/opencollective/logo.txt"
},
"devDependencies": {
"@size-limit/preset-big-lib": "^11.0.1",
"assert": "^2.0.0",
"browserify-zlib": "^0.2.0",
"buffer": "^6.0.3",
"process": "^0.11.10",
"size-limit": "^11.0.1",
"util": "^0.12.4"
}
}
+68
View File
@@ -0,0 +1,68 @@
<p align="center">
<img src="https://user-images.githubusercontent.com/5600341/27505816-c8bc37aa-587f-11e7-9a86-08a2d081a8b9.png" height="280px">
</p>
# @react-pdf/stylesheet
> React-pdf styles engine
## How to install
```sh
yarn add @react-pdf/stylesheet
```
## How it works
```js
import stylesheet from '@react-pdf/stylesheet';
const container = {
width: 400,
height: 600,
orientation: 'portrait',
};
const style = {
margin: 20,
width: '50vw',
height: '20vh',
borderRadius: 5,
fontWeight: 'semibold',
borderBottom: '2 solid yellow',
'@media max-width: 500': {
backgroundColor: 'rgb(255, 0, 0)',
},
};
const computed = stylesheet(container, style);
// Computed
// {
// width: 200,
// height: 120,
// marginTop: 20,
// marginLeft: 20,
// marginRight: 20,
// marginBottom: 20,
// marginBottom: 20,
// borderTopLeftRadius: 5,
// borderTopRightRadius: 5,
// borderBottomLeftRadius: 5,
// borderBottomRightRadius: 5,
// fontWeight: 600,
// borderBottomWidth: 2,
// borderBottomStyle: 'solid',
// borderBottomColor: 'yellow',
// backgroundColor: '#FF0000'
// }
```
This library exports a `stylesheet` function that takes two arguments:
- _container_: Container where the styles are being computed into. It specifies the `width` and `height` in points (needed for media queries and unit conversions), and optionally the container `orientation` (needed for certain media queries).
- _style_: Style to be computed. JS object with raw styles that you would like to get in a normalized format.
## License
MIT © [Diego Muracciole](http://github.com/diegomura)
+314
View File
@@ -0,0 +1,314 @@
type Container = {
width: number;
height: number;
dpi?: number;
remBase?: number;
orientation?: 'landscape' | 'portrait';
};
type Percentage = `${string}%`;
type BorderStyleValue = 'dashed' | 'dotted' | 'solid';
type BorderShorthandStyle = {
border?: number | string;
borderTop?: number | string;
borderRight?: number | string;
borderBottom?: number | string;
borderLeft?: number | string;
borderColor?: string;
borderRadius?: number | string;
borderStyle?: BorderStyleValue;
borderWidth?: number | string;
};
type BorderExpandedStyle = {
borderTopColor?: string;
borderTopStyle?: BorderStyleValue;
borderTopWidth?: number | string;
borderRightColor?: string;
borderRightStyle?: BorderStyleValue;
borderRightWidth?: number | string;
borderBottomColor?: string;
borderBottomStyle?: BorderStyleValue;
borderBottomWidth?: number | string;
borderLeftColor?: string;
borderLeftStyle?: BorderStyleValue;
borderLeftWidth?: number | string;
borderTopLeftRadius?: number | string;
borderTopRightRadius?: number | string;
borderBottomRightRadius?: number | string;
borderBottomLeftRadius?: number | string;
};
type BorderSafeStyle = BorderExpandedStyle & {
borderTopWidth?: number;
borderRightWidth?: number;
borderBottomWidth?: number;
borderLeftWidth?: number;
borderTopLeftRadius?: number | Percentage;
borderTopRightRadius?: number | Percentage;
borderBottomRightRadius?: number | Percentage;
borderBottomLeftRadius?: number | Percentage;
};
type BorderStyle = BorderShorthandStyle & BorderExpandedStyle;
type FlexboxShorthandStyle = {
flex?: number | string;
};
type AlignContent = 'flex-start' | 'flex-end' | 'center' | 'stretch' | 'space-between' | 'space-around' | 'space-evenly';
type AlignItems = 'flex-start' | 'flex-end' | 'center' | 'stretch' | 'baseline';
type AlignSelf = 'auto' | 'flex-start' | 'flex-end' | 'center' | 'baseline' | 'stretch';
type FlexDirection = 'row' | 'row-reverse' | 'column' | 'column-reverse';
type FlexWrap = 'nowrap' | 'wrap' | 'wrap-reverse';
type JustifyContent = 'flex-start' | 'flex-end' | 'center' | 'space-around' | 'space-between' | 'space-evenly';
type JustifySelf = string;
type FlexboxExpandedStyle = {
alignContent?: AlignContent;
alignItems?: AlignItems;
alignSelf?: AlignSelf;
flexDirection?: FlexDirection;
flexWrap?: FlexWrap;
flexFlow?: number | string;
flexGrow?: number | string;
flexShrink?: number | string;
flexBasis?: number | string;
justifySelf?: JustifySelf;
justifyContent?: JustifyContent;
};
type FlexboxSafeStyle = FlexboxExpandedStyle & {
flexGrow?: number;
flexShrink?: number;
};
type FlexboxStyle = FlexboxShorthandStyle & FlexboxExpandedStyle;
type GapShorthandStyle = {
gap?: number | string;
};
type GapExpandedStyle = {
rowGap?: number | string;
columnGap?: number | string;
};
type GapSafeStyle = {
rowGap?: number | Percentage;
columnGap?: number | Percentage;
};
type GapStyle = GapShorthandStyle & GapExpandedStyle;
type PositionShorthandStyle = {
objectPosition?: number | string;
};
type PositionExpandedStyle = {
objectPositionX?: number | string;
objectPositionY?: number | string;
objectFit?: string;
};
type PositionSafeStyle = PositionExpandedStyle & {
objectPositionX?: number;
objectPositionY?: number;
};
type PositioningStyle = PositionShorthandStyle & PositionExpandedStyle;
type ScaleTransform = {
operation: 'scale';
value: [number, number];
};
type TranslateTransform = {
operation: 'translate';
value: [number, number];
};
type RotateTransform = {
operation: 'rotate';
value: [number];
};
type SkewTransform = {
operation: 'skew';
value: [number, number];
};
type MatrixTransform = {
operation: 'matrix';
value: [number, number, number, number, number, number];
};
type Transform = ScaleTransform | TranslateTransform | RotateTransform | SkewTransform | MatrixTransform;
type TransformShorthandStyle = {
transformOrigin?: number | string;
};
type TransformExpandedStyle = {
transformOriginX?: number | string;
transformOriginY?: number | string;
transform?: string | Transform[];
gradientTransform?: string | Transform[];
};
type TransformSafeStyle = Omit<TransformExpandedStyle, 'transform'> & {
transformOriginX?: number | Percentage;
transformOriginY?: number | Percentage;
transform?: Transform[];
gradientTransform?: Transform[];
};
type TransformStyle = TransformShorthandStyle & TransformExpandedStyle;
type Display = 'flex' | 'none';
type Position = 'absolute' | 'relative' | 'static';
type LayoutStyle = {
aspectRatio?: number | string;
bottom?: number | string;
display?: Display;
left?: number | string;
position?: Position;
right?: number | string;
top?: number | string;
overflow?: 'hidden';
zIndex?: number | string;
};
type LayoutExpandedStyle = LayoutStyle;
type LayoutSafeStyle = LayoutExpandedStyle & {
aspectRatio?: number;
bottom?: number;
left?: number;
right?: number;
top?: number;
zIndex?: number;
};
type DimensionStyle = {
height?: number | string;
maxHeight?: number | string;
maxWidth?: number | string;
minHeight?: number | string;
minWidth?: number | string;
width?: number | string;
};
type DimensionExpandedStyle = DimensionStyle;
type DimensionSafeStyle = DimensionExpandedStyle & {
height?: number | Percentage;
maxHeight?: number | Percentage;
maxWidth?: number | Percentage;
minHeight?: number | Percentage;
minWidth?: number | Percentage;
width?: number | Percentage;
};
type ColorStyle = {
backgroundColor?: string;
color?: string;
opacity?: number | string;
};
type ColorExpandedStyle = ColorStyle;
type ColorSafeStyle = {
backgroundColor?: string;
color?: string;
opacity?: number;
};
type FontStyle = 'normal' | 'italic' | 'oblique';
type FontWeight = string | number | 'thin' | 'hairline' | 'ultralight' | 'extralight' | 'light' | 'normal' | 'medium' | 'semibold' | 'demibold' | 'bold' | 'ultrabold' | 'extrabold' | 'heavy' | 'black';
type TextAlign = 'left' | 'right' | 'center' | 'justify';
type TextDecoration = 'line-through' | 'underline' | 'none' | 'line-through underline' | 'underline line-through';
type TextDecorationStyle = 'dashed' | 'dotted' | 'solid' | string;
type TextTransform = 'capitalize' | 'lowercase' | 'uppercase' | 'upperfirst' | 'none';
type VerticalAlign = 'sub' | 'super';
type TextStyle = {
direction?: 'ltr' | 'rtl';
fontSize?: number | string;
fontFamily?: string | string[];
fontStyle?: FontStyle;
fontWeight?: FontWeight;
letterSpacing?: number | string;
lineHeight?: number | string;
maxLines?: number;
textAlign?: TextAlign;
textDecoration?: TextDecoration;
textDecorationColor?: string;
textDecorationStyle?: TextDecorationStyle;
textIndent?: any;
textOverflow?: 'ellipsis';
textTransform?: TextTransform;
verticalAlign?: VerticalAlign;
};
type TextExpandedStyle = TextStyle;
type TextSafeStyle = TextExpandedStyle & {
fontSize?: number;
fontWeight?: number;
letterSpacing?: number;
lineHeight?: number;
};
type MarginShorthandStyle = {
margin?: number | string;
marginHorizontal?: number | string;
marginVertical?: number | string;
};
type MarginExpandedStyle = {
marginTop?: number | string;
marginRight?: number | string;
marginBottom?: number | string;
marginLeft?: number | string;
};
type MarginSafeStyle = MarginExpandedStyle & {
marginTop?: number | Percentage;
marginRight?: number | Percentage;
marginBottom?: number | Percentage;
marginLeft?: number | Percentage;
};
type MarginStyle = MarginShorthandStyle & MarginExpandedStyle;
type PaddingShorthandStyle = {
padding?: number | string;
paddingHorizontal?: number | string;
paddingVertical?: number | string;
};
type PaddingExpandedStyle = {
paddingTop?: number | string;
paddingRight?: number | string;
paddingBottom?: number | string;
paddingLeft?: number | string;
};
type PaddingSafeStyle = PaddingExpandedStyle & {
paddingTop?: number | Percentage;
paddingRight?: number | Percentage;
paddingBottom?: number | Percentage;
paddingLeft?: number | Percentage;
};
type PaddingStyle = PaddingShorthandStyle & PaddingExpandedStyle;
interface SvgStyle {
fill?: string;
stroke?: string;
strokeDasharray?: string;
strokeWidth?: string | number;
fillOpacity?: string | number;
fillRule?: 'nonzero' | 'evenodd';
strokeOpacity?: string | number;
textAnchor?: 'start' | 'middle' | 'end';
strokeLinecap?: 'butt' | 'round' | 'square';
strokeLinejoin?: 'butt' | 'round' | 'square' | 'miter' | 'bevel';
visibility?: 'visible' | 'hidden' | 'collapse';
clipPath?: string;
dominantBaseline?: 'auto' | 'middle' | 'central' | 'hanging' | 'mathematical' | 'text-after-edge' | 'text-before-edge';
}
type SvgExpandedStyle = SvgStyle;
type SvgSafeStyle = SvgStyle & {
strokeWidth?: number;
fillOpacity?: number;
strokeOpacity?: number;
};
type BaseStyle = BorderStyle & ColorStyle & DimensionStyle & FlexboxStyle & GapStyle & LayoutStyle & MarginStyle & PaddingStyle & PositioningStyle & TextStyle & TransformStyle & SvgStyle;
type MediaQueryStyle = {
[key in `@media${string}`]: BaseStyle;
};
type Style = BaseStyle & MediaQueryStyle;
type StyleKey = keyof BaseStyle;
type ExpandedStyle = BorderExpandedStyle & ColorExpandedStyle & DimensionExpandedStyle & FlexboxExpandedStyle & GapExpandedStyle & LayoutExpandedStyle & MarginExpandedStyle & PaddingExpandedStyle & PositionExpandedStyle & TextExpandedStyle & TransformExpandedStyle & SvgExpandedStyle;
type SafeStyle = BorderSafeStyle & ColorSafeStyle & DimensionSafeStyle & FlexboxSafeStyle & GapSafeStyle & LayoutSafeStyle & MarginSafeStyle & PaddingSafeStyle & PositionSafeStyle & TextSafeStyle & TransformSafeStyle & SvgSafeStyle;
/**
* Transform given color to hexa
*
* @param value - Styles value
* @returns Transformed value
*/
declare const transformColor: (value: string) => string;
/**
* Flattens an array of style objects, into one aggregated style object.
*
* @param styles - Style or style array
* @returns Flattened style object
*/
declare const flatten: (value: Style | Style[], ...args: any[]) => Style;
type StyleParam = Style | null | undefined;
/**
* Resolves styles
*
* @param container
* @param style - Style
* @returns Resolved style
*/
declare const resolveStyles: (container: Container, style: StyleParam | StyleParam[]) => SafeStyle;
export { type AlignContent, type AlignItems, type AlignSelf, type BorderExpandedStyle, type BorderSafeStyle, type BorderShorthandStyle, type BorderStyle, type BorderStyleValue, type ColorExpandedStyle, type ColorSafeStyle, type ColorStyle, type Container, type DimensionExpandedStyle, type DimensionSafeStyle, type DimensionStyle, type Display, type ExpandedStyle, type FlexDirection, type FlexWrap, type FlexboxExpandedStyle, type FlexboxSafeStyle, type FlexboxShorthandStyle, type FlexboxStyle, type FontStyle, type FontWeight, type GapExpandedStyle, type GapSafeStyle, type GapShorthandStyle, type GapStyle, type JustifyContent, type JustifySelf, type LayoutExpandedStyle, type LayoutSafeStyle, type LayoutStyle, type MarginExpandedStyle, type MarginSafeStyle, type MarginShorthandStyle, type MarginStyle, type MatrixTransform, type PaddingExpandedStyle, type PaddingSafeStyle, type PaddingShorthandStyle, type PaddingStyle, type Percentage, type Position, type PositionExpandedStyle, type PositionSafeStyle, type PositionShorthandStyle, type PositioningStyle, type RotateTransform, type SafeStyle, type ScaleTransform, type SkewTransform, type Style, type StyleKey, type SvgExpandedStyle, type SvgSafeStyle, type SvgStyle, type TextAlign, type TextDecoration, type TextDecorationStyle, type TextExpandedStyle, type TextSafeStyle, type TextStyle, type TextTransform, type Transform, type TransformExpandedStyle, type TransformSafeStyle, type TransformShorthandStyle, type TransformStyle, type TranslateTransform, type VerticalAlign, resolveStyles as default, flatten, transformColor };
+765
View File
@@ -0,0 +1,765 @@
import { compose, castArray, parseFloat as parseFloat$1, matchPercent } from '@react-pdf/fns';
import matchMedia from 'media-engine';
import hlsToHex from 'hsl-to-hex';
import colorString from 'color-string';
import parse$1 from 'postcss-value-parser/lib/parse.js';
import parseUnit from 'postcss-value-parser/lib/unit.js';
/**
* Remove nil values from array
*
* @param array - Style array
* @returns Style array without nils
*/
const compact = (array) => array.filter(Boolean);
/**
* Merges style objects array
*
* @param styles - Style array
* @returns Merged style object
*/
const mergeStyles = (styles) => styles.reduce((acc, style) => {
const s = Array.isArray(style) ? flatten(style) : style;
Object.keys(s).forEach((key) => {
if (s[key] !== null && s[key] !== undefined) {
acc[key] = s[key];
}
});
return acc;
}, {});
/**
* Flattens an array of style objects, into one aggregated style object.
*
* @param styles - Style or style array
* @returns Flattened style object
*/
const flatten = compose(mergeStyles, compact, (castArray));
/**
* Resolves media queries in styles object
*
* @param container - Container for which styles are resolved
* @param style - Style description
* @returns Resolved style object
*/
const resolveMediaQueries = (container, style) => {
return Object.keys(style).reduce((acc, key) => {
if (/@media/.test(key)) {
return {
...acc,
...matchMedia({ [key]: style[key] }, container),
};
}
return { ...acc, [key]: style[key] };
}, {});
};
const isRgb = (value) => /rgba?/g.test(value);
const isHsl = (value) => /hsla?/g.test(value);
/**
* Transform rgb color to hexa
*
* @param value - Styles value
* @returns Transformed value
*/
const parseRgb = (value) => {
const rgb = colorString.get.rgb(value);
return colorString.to.hex(rgb);
};
/**
* Transform Hsl color to hexa
*
* @param value - Styles value
* @returns Transformed value
*/
const parseHsl = (value) => {
const hsl = colorString.get.hsl(value).map(Math.round);
const hex = hlsToHex(...hsl);
return hex.toUpperCase();
};
/**
* Transform given color to hexa
*
* @param value - Styles value
* @returns Transformed value
*/
const transformColor = (value) => {
if (isRgb(value))
return parseRgb(value);
if (isHsl(value))
return parseHsl(value);
return value;
};
/**
* Parses scalar value in value and unit pairs
*
* @param value - Scalar value
* @returns Parsed value
*/
const parseValue = (value) => {
if (typeof value === 'number')
return { value, unit: undefined };
const match = /^(-?\d*\.?\d+)(in|mm|cm|pt|vh|vw|px|rem)?$/g.exec(value);
return match
? { value: parseFloat(match[1]), unit: match[2] || 'pt' }
: { value, unit: undefined };
};
/**
* Transform given scalar value
*
* @param container
* @param value - Styles value
* @returns Transformed value
*/
const transformUnit = (container, value) => {
const scalar = parseValue(value);
const outputDpi = 72;
const inputDpi = container.dpi || 72;
const mmFactor = (1 / 25.4) * outputDpi;
const cmFactor = (1 / 2.54) * outputDpi;
if (typeof scalar.value !== 'number')
return scalar.value;
switch (scalar.unit) {
case 'rem':
return scalar.value * (container.remBase || 18);
case 'in':
return scalar.value * outputDpi;
case 'mm':
return scalar.value * mmFactor;
case 'cm':
return scalar.value * cmFactor;
case 'vh':
return scalar.value * (container.height / 100);
case 'vw':
return scalar.value * (container.width / 100);
case 'px':
return Math.round(scalar.value * (outputDpi / inputDpi));
default:
return scalar.value;
}
};
const processNumberValue = (key, value) => ({
[key]: parseFloat$1(value),
});
const processUnitValue = (key, value, container) => ({
[key]: transformUnit(container, value),
});
const processColorValue = (key, value) => {
const result = { [key]: transformColor(value) };
return result;
};
const processNoopValue = (key, value) => ({
[key]: value,
});
const BORDER_SHORTHAND_REGEX = /(-?\d+(\.\d+)?(in|mm|cm|pt|vw|vh|px|rem)?)\s(\S+)\s(.+)/;
const matchBorderShorthand = (value) => value.match(BORDER_SHORTHAND_REGEX) || [];
const resolveBorderShorthand = (key, value, container) => {
const match = matchBorderShorthand(`${value}`);
if (match) {
const widthMatch = match[1] || value;
const styleMatch = match[4] || value;
const colorMatch = match[5] || value;
const style = styleMatch;
const color = colorMatch ? transformColor(colorMatch) : undefined;
const width = widthMatch ? transformUnit(container, widthMatch) : undefined;
if (key.match(/(Top|Right|Bottom|Left)$/)) {
return {
[`${key}Color`]: color,
[`${key}Style`]: style,
[`${key}Width`]: width,
};
}
if (key.match(/Color$/)) {
return {
borderTopColor: color,
borderRightColor: color,
borderBottomColor: color,
borderLeftColor: color,
};
}
if (key.match(/Style$/)) {
if (typeof style === 'number')
throw new Error(`Invalid border style: ${style}`);
return {
borderTopStyle: style,
borderRightStyle: style,
borderBottomStyle: style,
borderLeftStyle: style,
};
}
if (key.match(/Width$/)) {
if (typeof width !== 'number')
throw new Error(`Invalid border width: ${width}`);
return {
borderTopWidth: width,
borderRightWidth: width,
borderBottomWidth: width,
borderLeftWidth: width,
};
}
if (key.match(/Radius$/)) {
const radius = value ? transformUnit(container, value) : undefined;
if (typeof radius !== 'number')
throw new Error(`Invalid border radius: ${radius}`);
return {
borderTopLeftRadius: radius,
borderTopRightRadius: radius,
borderBottomRightRadius: radius,
borderBottomLeftRadius: radius,
};
}
if (typeof width !== 'number')
throw new Error(`Invalid border width: ${width}`);
if (typeof style === 'number')
throw new Error(`Invalid border style: ${style}`);
return {
borderTopColor: color,
borderTopStyle: style,
borderTopWidth: width,
borderRightColor: color,
borderRightStyle: style,
borderRightWidth: width,
borderBottomColor: color,
borderBottomStyle: style,
borderBottomWidth: width,
borderLeftColor: color,
borderLeftStyle: style,
borderLeftWidth: width,
};
}
return { [key]: value };
};
const handlers$b = {
border: (resolveBorderShorthand),
borderBottom: (resolveBorderShorthand),
borderBottomColor: (processColorValue),
borderBottomLeftRadius: (processUnitValue),
borderBottomRightRadius: (processUnitValue),
borderBottomStyle: (processNoopValue),
borderBottomWidth: (processUnitValue),
borderColor: (resolveBorderShorthand),
borderLeft: (resolveBorderShorthand),
borderLeftColor: (processColorValue),
borderLeftStyle: (processNoopValue),
borderLeftWidth: (processUnitValue),
borderRadius: (resolveBorderShorthand),
borderRight: (resolveBorderShorthand),
borderRightColor: (processColorValue),
borderRightStyle: (processNoopValue),
borderRightWidth: (processUnitValue),
borderStyle: (resolveBorderShorthand),
borderTop: (resolveBorderShorthand),
borderTopColor: (processColorValue),
borderTopLeftRadius: (processUnitValue),
borderTopRightRadius: (processUnitValue),
borderTopStyle: (processNoopValue),
borderTopWidth: (processUnitValue),
borderWidth: (resolveBorderShorthand),
};
const handlers$a = {
backgroundColor: (processColorValue),
color: (processColorValue),
opacity: (processNumberValue),
};
const handlers$9 = {
height: (processUnitValue),
maxHeight: (processUnitValue),
maxWidth: (processUnitValue),
minHeight: (processUnitValue),
minWidth: (processUnitValue),
width: (processUnitValue),
};
// https://developer.mozilla.org/en-US/docs/Web/CSS/flex#values
// TODO: change flex defaults to [0, 1, 'auto'] as in spec in next major release
const flexDefaults = [1, 1, 0];
const flexAuto = [1, 1, 'auto'];
const processFlexShorthand = (key, value, container) => {
let defaults = flexDefaults;
let matches = [];
if (value === 'auto') {
defaults = flexAuto;
}
else {
matches = `${value}`.split(' ');
}
const flexGrow = parseFloat$1(matches[0] || defaults[0]);
const flexShrink = parseFloat$1(matches[1] || defaults[1]);
const flexBasis = transformUnit(container, matches[2] || defaults[2]);
return { flexGrow, flexShrink, flexBasis };
};
const handlers$8 = {
alignContent: (processNoopValue),
alignItems: (processNoopValue),
alignSelf: (processNoopValue),
flex: (processFlexShorthand),
flexBasis: (processUnitValue),
flexDirection: (processNoopValue),
flexFlow: (processNoopValue),
flexGrow: (processNumberValue),
flexShrink: (processNumberValue),
flexWrap: (processNoopValue),
justifyContent: (processNoopValue),
justifySelf: (processNoopValue),
};
const processGapShorthand = (key, value, container) => {
const match = `${value}`.split(' ');
const rowGap = transformUnit(container, match?.[0] || value);
const columnGap = transformUnit(container, match?.[1] || value);
return { rowGap, columnGap };
};
const handlers$7 = {
gap: (processGapShorthand),
columnGap: (processUnitValue),
rowGap: (processUnitValue),
};
const handlers$6 = {
aspectRatio: (processNumberValue),
bottom: (processUnitValue),
display: (processNoopValue),
left: (processUnitValue),
position: (processNoopValue),
right: (processUnitValue),
top: (processUnitValue),
overflow: (processNoopValue),
zIndex: (processNumberValue),
};
const BOX_MODEL_UNITS = 'px,in,mm,cm,pt,%,vw,vh';
const logError = (style, value) => {
const name = style.toString();
// eslint-disable-next-line no-console
console.error(`
@react-pdf/stylesheet parsing error:
${name}: ${value},
${' '.repeat(name.length + 2)}^
Unsupported ${name} value format
`);
};
/**
* @param options
* @param [options.expandsTo]
* @param [options.maxValues]
* @param [options.autoSupported]
*/
const expandBoxModel = ({ expandsTo, maxValues = 1, autoSupported = false, } = {}) => (model, value, container) => {
const nodes = parse$1(`${value}`);
const parts = [];
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
// value contains `calc`, `url` or other css function
// `,`, `/` or strings that unsupported by margin and padding
if (node.type === 'function' ||
node.type === 'string' ||
node.type === 'div') {
logError(model, value);
return {};
}
if (node.type === 'word') {
if (node.value === 'auto' && autoSupported) {
parts.push(node.value);
}
else {
const result = parseUnit(node.value);
// when unit isn't specified this condition is true
if (result && BOX_MODEL_UNITS.includes(result.unit)) {
parts.push(node.value);
}
else {
logError(model, value);
return {};
}
}
}
}
// checks that we have enough parsed values
if (parts.length > maxValues) {
logError(model, value);
return {};
}
const first = transformUnit(container, parts[0]);
if (expandsTo) {
const second = transformUnit(container, parts[1] || parts[0]);
const third = transformUnit(container, parts[2] || parts[0]);
const fourth = transformUnit(container, parts[3] || parts[1] || parts[0]);
return expandsTo({ first, second, third, fourth });
}
return {
[model]: first,
};
};
const processMargin = expandBoxModel({
expandsTo: ({ first, second, third, fourth }) => ({
marginTop: first,
marginRight: second,
marginBottom: third,
marginLeft: fourth,
}),
maxValues: 4,
autoSupported: true,
});
const processMarginVertical = expandBoxModel({
expandsTo: ({ first, second }) => ({
marginTop: first,
marginBottom: second,
}),
maxValues: 2,
autoSupported: true,
});
const processMarginHorizontal = expandBoxModel({
expandsTo: ({ first, second }) => ({
marginRight: first,
marginLeft: second,
}),
maxValues: 2,
autoSupported: true,
});
const processMarginSingle = expandBoxModel({
autoSupported: true,
});
const handlers$5 = {
margin: (processMargin),
marginBottom: (processMarginSingle),
marginHorizontal: (processMarginHorizontal),
marginLeft: (processMarginSingle),
marginRight: (processMarginSingle),
marginTop: (processMarginSingle),
marginVertical: (processMarginVertical),
};
const processPadding = expandBoxModel({
expandsTo: ({ first, second, third, fourth }) => ({
paddingTop: first,
paddingRight: second,
paddingBottom: third,
paddingLeft: fourth,
}),
maxValues: 4,
});
const processPaddingVertical = expandBoxModel({
expandsTo: ({ first, second }) => ({
paddingTop: first,
paddingBottom: second,
}),
maxValues: 2,
});
const processPaddingHorizontal = expandBoxModel({
expandsTo: ({ first, second }) => ({
paddingRight: first,
paddingLeft: second,
}),
maxValues: 2,
});
const processPaddingSingle = expandBoxModel();
const handlers$4 = {
padding: (processPadding),
paddingBottom: (processPaddingSingle),
paddingHorizontal: (processPaddingHorizontal),
paddingLeft: (processPaddingSingle),
paddingRight: (processPaddingSingle),
paddingTop: (processPaddingSingle),
paddingVertical: (processPaddingVertical),
};
const offsetKeyword = (value) => {
switch (value) {
case 'top':
case 'left':
return '0%';
case 'right':
case 'bottom':
return '100%';
case 'center':
return '50%';
default:
return value;
}
};
const processObjectPosition = (key, value, container) => {
const match = `${value}`.split(' ');
const objectPositionX = offsetKeyword(transformUnit(container, match?.[0] || value));
const objectPositionY = offsetKeyword(transformUnit(container, match?.[1] || value));
return { objectPositionX, objectPositionY };
};
const processObjectPositionValue = (key, value, container) => ({
[key]: offsetKeyword(transformUnit(container, value)),
});
const handlers$3 = {
objectPosition: (processObjectPosition),
objectPositionX: (processObjectPositionValue),
objectPositionY: (processObjectPositionValue),
objectFit: (processNoopValue),
};
const castInt = (value) => {
if (typeof value === 'number')
return value;
return parseInt(value, 10);
};
const FONT_WEIGHTS = {
thin: 100,
hairline: 100,
ultralight: 200,
extralight: 200,
light: 300,
normal: 400,
medium: 500,
semibold: 600,
demibold: 600,
bold: 700,
ultrabold: 800,
extrabold: 800,
heavy: 900,
black: 900,
};
const transformFontWeight = (value) => {
if (!value)
return FONT_WEIGHTS.normal;
if (typeof value === 'number')
return value;
const lv = value.toLowerCase();
if (FONT_WEIGHTS[lv])
return FONT_WEIGHTS[lv];
return castInt(value);
};
const processFontWeight = (key, value) => {
return { [key]: transformFontWeight(value) };
};
const transformLineHeight = (value, styles, container) => {
if (value === '')
return value;
const fontSize = transformUnit(container, styles.fontSize || 18);
const lineHeight = transformUnit(container, value);
// Percent values: use this number multiplied by the element's font size
const { percent } = matchPercent(lineHeight) || {};
if (percent)
return percent * fontSize;
// Unitless values: use this number multiplied by the element's font size
return isNaN(value) ? lineHeight : lineHeight * fontSize;
};
const processLineHeight = (key, value, container, styles) => {
return {
[key]: transformLineHeight(value, styles, container),
};
};
const handlers$2 = {
direction: (processNoopValue),
fontFamily: (processNoopValue),
fontSize: (processUnitValue),
fontStyle: (processNoopValue),
fontWeight: (processFontWeight),
letterSpacing: (processUnitValue),
lineHeight: (processLineHeight),
maxLines: (processNumberValue),
textAlign: (processNoopValue),
textDecoration: (processNoopValue),
textDecorationColor: (processColorValue),
textDecorationStyle: (processNoopValue),
textIndent: (processNoopValue),
textOverflow: (processNoopValue),
textTransform: (processNoopValue),
verticalAlign: (processNoopValue),
};
const matchNumber = (value) => typeof value === 'string' && /^-?\d*\.?\d*$/.test(value);
const castFloat = (value) => {
if (typeof value !== 'string')
return value;
if (matchNumber(value))
return parseFloat(value);
return value;
};
const parse = (transformString) => {
const transforms = transformString.trim().split(/\)[ ,]|\)/);
// Handle "initial", "inherit", "unset".
if (transforms.length === 1) {
return [[transforms[0], true]];
}
const parsed = [];
for (let i = 0; i < transforms.length; i += 1) {
const transform = transforms[i];
if (transform) {
const [name, rawValue] = transform.split('(');
const splitChar = rawValue.indexOf(',') >= 0 ? ',' : ' ';
const value = rawValue.split(splitChar).map((val) => val.trim());
parsed.push({ operation: name.trim(), value });
}
}
return parsed;
};
const parseAngle = (value) => {
const unitsRegexp = /(-?\d*\.?\d*)(\w*)?/i;
const [, angle, unit] = unitsRegexp.exec(value);
const number = Number.parseFloat(angle);
return unit === 'rad' ? (number * 180) / Math.PI : number;
};
const normalizeTransformOperation = ({ operation, value }) => {
switch (operation) {
case 'scale': {
const [scaleX, scaleY = scaleX] = value.map((num) => Number.parseFloat(num));
return { operation: 'scale', value: [scaleX, scaleY] };
}
case 'scaleX': {
return { operation: 'scale', value: [Number.parseFloat(value), 1] };
}
case 'scaleY': {
return { operation: 'scale', value: [1, Number.parseFloat(value)] };
}
case 'rotate': {
return { operation: 'rotate', value: [parseAngle(value)] };
}
case 'translate': {
return {
operation: 'translate',
value: value.map((num) => Number.parseFloat(num)),
};
}
case 'translateX': {
return {
operation: 'translate',
value: [Number.parseFloat(value), 0],
};
}
case 'translateY': {
return { operation: 'translate', value: [0, Number.parseFloat(value)] };
}
case 'skew': {
return { operation: 'skew', value: value.map(parseAngle) };
}
case 'skewX': {
return { operation: 'skew', value: [parseAngle(value), 0] };
}
case 'skewY': {
return { operation: 'skew', value: [0, parseAngle(value)] };
}
default: {
return { operation, value: value.map((num) => Number.parseFloat(num)) };
}
}
};
const normalize = (operations) => {
return operations.map((operation) => normalizeTransformOperation(operation));
};
const processTransform = (key, value) => {
if (typeof value !== 'string')
return { [key]: value };
return { [key]: normalize(parse(value)) };
};
const Y_AXIS_SHORTHANDS = { top: true, bottom: true };
const sortTransformOriginPair = (a, b) => {
if (Y_AXIS_SHORTHANDS[a])
return 1;
if (Y_AXIS_SHORTHANDS[b])
return -1;
return 0;
};
const getTransformOriginPair = (values) => {
if (!values || values.length === 0)
return ['center', 'center'];
const pair = values.length === 1 ? [values[0], 'center'] : values;
return pair.sort(sortTransformOriginPair);
};
// Transforms shorthand transformOrigin values
const processTransformOriginShorthand = (key, value, container) => {
const match = `${value}`.split(' ');
const pair = getTransformOriginPair(match);
const transformOriginX = transformUnit(container, pair[0]);
const transformOriginY = transformUnit(container, pair[1]);
return {
transformOriginX: offsetKeyword(transformOriginX) || castFloat(transformOriginX),
transformOriginY: offsetKeyword(transformOriginY) || castFloat(transformOriginY),
};
};
const processTransformOriginValue = (key, value, container) => {
const v = transformUnit(container, value);
return { [key]: offsetKeyword(v) || castFloat(v) };
};
const handlers$1 = {
transform: processTransform,
gradientTransform: processTransform,
transformOrigin: (processTransformOriginShorthand),
transformOriginX: (processTransformOriginValue),
transformOriginY: (processTransformOriginValue),
};
const handlers = {
fill: (processColorValue),
stroke: (processColorValue),
strokeDasharray: (processNoopValue),
strokeWidth: (processUnitValue),
fillOpacity: (processNumberValue),
strokeOpacity: (processNumberValue),
fillRule: (processNoopValue),
textAnchor: (processNoopValue),
strokeLinecap: (processNoopValue),
strokeLinejoin: (processNoopValue),
visibility: (processNoopValue),
clipPath: (processNoopValue),
dominantBaseline: (processNoopValue),
};
const shorthands = {
...handlers$b,
...handlers$a,
...handlers$9,
...handlers$8,
...handlers$7,
...handlers$6,
...handlers$5,
...handlers$4,
...handlers$3,
...handlers$2,
...handlers$1,
...handlers,
};
/**
* Expand the shorthand properties.
*
* @param style - Style object
* @returns Expanded style object
*/
const resolve = (container) => (style) => {
const propsArray = Object.keys(style);
const resolvedStyle = {};
for (let i = 0; i < propsArray.length; i += 1) {
const key = propsArray[i];
const value = style[key];
if (!shorthands[key]) {
resolvedStyle[key] = value;
continue;
}
const resolved = shorthands[key](key, value, container, style);
const keys = Object.keys(resolved);
for (let j = 0; j < keys.length; j += 1) {
const propName = keys[j];
const propValue = resolved[propName];
resolvedStyle[propName] = propValue;
}
}
return resolvedStyle;
};
/**
* Resolves styles
*
* @param container
* @param style - Style
* @returns Resolved style
*/
const resolveStyles = (container, style) => {
const computeMediaQueries = (value) => resolveMediaQueries(container, value);
return compose(resolve(container), computeMediaQueries, flatten)(style);
};
export { resolveStyles as default, flatten, transformColor };
+33
View File
@@ -0,0 +1,33 @@
{
"name": "@react-pdf/stylesheet",
"version": "6.1.0",
"license": "MIT",
"description": "A styles engine for Node and the browser",
"author": "Diego Muracciole <diegomuracciole@gmail.com>",
"homepage": "https://github.com/diegomura/react-pdf#readme",
"type": "module",
"main": "./lib/index.js",
"types": "./lib/index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/diegomura/react-pdf.git",
"directory": "packages/stylesheet"
},
"scripts": {
"test": "vitest",
"build": "rimraf ./lib && rollup -c",
"watch": "rimraf ./lib && rollup -c -w",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@react-pdf/fns": "3.1.2",
"@react-pdf/types": "^2.9.0",
"color-string": "^1.9.1",
"hsl-to-hex": "^1.0.0",
"media-engine": "^1.0.3",
"postcss-value-parser": "^4.1.0"
},
"files": [
"lib"
]
}
+25
View File
@@ -0,0 +1,25 @@
<p align="center">
<img src="https://user-images.githubusercontent.com/5600341/27505816-c8bc37aa-587f-11e7-9a86-08a2d081a8b9.png" height="280px">
</p>
# @react-pdf/textkit
## Acknowledges
This project is a fork of [textkit](https://github.com/foliojs/textkit) by @devongovett and continued under the scope of this project since it has react-pdf specific features. Any recongnition should go to him and the original project mantainers.
## Layout process
1. split into paragraphs
2. get bidi runs and paragraph direction
3. font substitution - map to resolved font runs
4. script itemization
5. font shaping - text to glyphs
6. line breaking
7. bidi reordering
8. justification
9. get a list of rectangles by intersecting path, line, and exclusion paths
10. perform line breaking to get acceptable break points for each fragment
11. ellipsize line if necessary
12. bidi reordering
13. justification
+192
View File
@@ -0,0 +1,192 @@
/// <reference types="node" />
import { Glyph as Glyph$1 } from 'fontkit';
import { Font } from '@react-pdf/font';
export { Font } from '@react-pdf/font';
type Factor = {
before: number;
after: number;
priority?: number;
unconstrained?: boolean;
};
type Coordinate = {
x: number;
y: number;
};
type Rect = {
x: number;
y: number;
width: number;
height: number;
};
type Container = Rect & {
truncateMode?: 'ellipsis';
maxLines?: number;
excludeRects?: Rect[];
};
type Glyph = Glyph$1;
type Position = {
xAdvance: number;
yAdvance: number;
xOffset: number;
yOffset: number;
advanceWidth?: number;
};
type Attachment = {
x?: number;
y?: number;
width: number;
height: number;
xOffset?: number;
yOffset?: number;
image: Buffer;
};
type Attributes = {
align?: string;
alignLastLine?: string;
attachment?: Attachment;
backgroundColor?: string;
bidiLevel?: number;
bullet?: unknown;
characterSpacing?: number;
color?: string;
direction?: 'rtl' | 'ltr';
features?: unknown[];
fill?: boolean;
font?: Font[];
fontSize?: number;
hangingPunctuation?: boolean;
hyphenationFactor?: number;
indent?: number;
justificationFactor?: number;
lineHeight?: number;
lineSpacing?: number;
link?: string;
margin?: number;
marginLeft?: number;
marginRight?: number;
opacity?: number;
padding?: number;
paddingTop?: number;
paragraphSpacing?: number;
scale?: number;
script?: unknown;
shrinkFactor?: number;
strike?: boolean;
strikeColor?: string;
strikeStyle?: string;
stroke?: boolean;
underline?: boolean;
underlineColor?: string;
underlineStyle?: string;
verticalAlign?: string;
wordSpacing?: number;
yOffset?: number;
};
type Run = {
start: number;
end: number;
attributes: Attributes;
glyphIndices?: number[];
glyphs?: Glyph[];
positions?: Position[];
xAdvance?: number;
height?: number;
descent?: number;
};
type DecorationLine = {
rect: Rect;
opacity: number;
color: string;
style: string;
};
type AttributedString = {
string: string;
syllables?: string[];
runs: Run[];
box?: Rect;
decorationLines?: DecorationLine[];
overflowLeft?: number;
overflowRight?: number;
xAdvance?: number;
ascent?: number;
};
type Fragment = {
string: string;
attributes?: Attributes;
};
type Paragraph = AttributedString[];
type LayoutOptions = {
hyphenationCallback?: (word: string) => string[];
tolerance?: number;
hyphenationPenalty?: number;
expandCharFactor?: Factor;
shrinkCharFactor?: Factor;
expandWhitespaceFactor?: Factor;
shrinkWhitespaceFactor?: Factor;
};
declare const bidiEngine: () => (attributedString: AttributedString) => AttributedString;
/**
* Performs Knuth & Plass line breaking algorithm
* Fallbacks to best fit algorithm if latter not successful
*
* @param options - Layout options
*/
declare const linebreaker: (options: LayoutOptions) => (attributedString: AttributedString, availableWidths: number[]) => AttributedString[];
/**
* A JustificationEngine is used by a Typesetter to perform line fragment
* justification. This implementation is based on a description of Apple's
* justification algorithm from a PDF in the Apple Font Tools package.
*
* @param options - Layout options
*/
declare const justification: (options: LayoutOptions) => (line: AttributedString) => AttributedString;
declare const fontSubstitution: () => ({ string, runs }: AttributedString) => AttributedString;
/**
* A TextDecorationEngine is used by a Typesetter to generate
* DecorationLines for a line fragment, including underlines
* and strikes.
*/
declare const textDecoration: () => (line: AttributedString) => AttributedString;
/**
* Resolves unicode script in runs, grouping equal runs together
*/
declare const scriptItemizer: () => (attributedString: AttributedString) => AttributedString;
declare const wordHyphenation: () => (word: string | null) => string[];
type Engines = {
bidi: typeof bidiEngine;
linebreaker: typeof linebreaker;
justification: typeof justification;
fontSubstitution: typeof fontSubstitution;
scriptItemizer: typeof scriptItemizer;
textDecoration: typeof textDecoration;
wordHyphenation?: typeof wordHyphenation;
};
/**
* A LayoutEngine is the main object that performs text layout.
* It accepts an AttributedString and a Container object
* to layout text into, and uses several helper objects to perform
* various layout tasks. These objects can be overridden to customize
* layout behavior.
*/
declare const layoutEngine: (engines: Engines) => (attributedString: AttributedString, container: Container, options?: LayoutOptions) => Paragraph[];
/**
* Create attributed string from text fragments
*
* @param fragments - Fragments
* @returns Attributed string
*/
declare const fromFragments: (fragments: Fragment[]) => AttributedString;
export { type Attachment, type AttributedString, type Attributes, type Container, type Coordinate, type DecorationLine, type Fragment, type Glyph, type LayoutOptions, type Paragraph, type Position, type Rect, type Run, bidiEngine as bidi, layoutEngine as default, fontSubstitution, fromFragments, justification, linebreaker, scriptItemizer, textDecoration, wordHyphenation };
+2848
View File
File diff suppressed because it is too large Load Diff
+36
View File
@@ -0,0 +1,36 @@
{
"name": "@react-pdf/textkit",
"license": "MIT",
"version": "6.0.0",
"description": "An advanced text layout framework",
"type": "module",
"main": "./lib/textkit.js",
"types": "./lib/index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/diegomura/react-pdf.git",
"directory": "packages/textkit"
},
"contributors": [
"Devon Govett <devongovett@gmail.com>",
"Diego Muracciole <diegomuracciole@gmail.com>"
],
"scripts": {
"test": "vitest",
"build": "rimraf ./lib && rollup -c",
"watch": "rimraf ./lib && rollup -c -w",
"typecheck": "tsc --noEmit"
},
"files": [
"lib"
],
"dependencies": {
"@react-pdf/fns": "3.1.2",
"bidi-js": "^1.0.2",
"hyphen": "^1.6.4",
"unicode-properties": "^1.4.1"
},
"devDependencies": {
"@types/fontkit": "^2.0.7"
}
}
+174
View File
@@ -0,0 +1,174 @@
# @react-pdf/types
## 2.9.0
### Minor Changes
- [#3112](https://github.com/diegomura/react-pdf/pull/3112) [`f89f75c1`](https://github.com/diegomura/react-pdf/commit/f89f75c1f132ba19b54847c3ac23efec675f8d0a) Thanks [@diegomura](https://github.com/diegomura)! - feat: add xLinkHref, gradientTransform and gradientUnits support
### Patch Changes
- Updated dependencies [[`f89f75c1`](https://github.com/diegomura/react-pdf/commit/f89f75c1f132ba19b54847c3ac23efec675f8d0a)]:
- @react-pdf/stylesheet@6.1.0
- @react-pdf/font@4.0.2
## 2.8.2
### Patch Changes
- Updated dependencies [[`e257f7ee`](https://github.com/diegomura/react-pdf/commit/e257f7ee18ff09f4895cd16c0b21b824678384c8)]:
- @react-pdf/font@4.0.1
- @react-pdf/stylesheet@6.0.2
## 2.8.1
### Patch Changes
- [#3087](https://github.com/diegomura/react-pdf/pull/3087) [`7cd66e4f`](https://github.com/diegomura/react-pdf/commit/7cd66e4fc37cd1393adc6250a919fe2629812082) Thanks [@diegomura](https://github.com/diegomura)! - fix: font exported types
- Updated dependencies [[`2a4f1bfc`](https://github.com/diegomura/react-pdf/commit/2a4f1bfca6b84e6c6bbde683447ce8079a1febbe), [`7cd66e4f`](https://github.com/diegomura/react-pdf/commit/7cd66e4fc37cd1393adc6250a919fe2629812082), [`bfb51ec0`](https://github.com/diegomura/react-pdf/commit/bfb51ec09b851c52659ce16fed1286173e9516a9), [`a2de2685`](https://github.com/diegomura/react-pdf/commit/a2de2685b25c797f266775c2e35a6535090393b7), [`24690f52`](https://github.com/diegomura/react-pdf/commit/24690f5238e4eacf28351cf9996856a7d196d29e), [`481b536f`](https://github.com/diegomura/react-pdf/commit/481b536f4ad145fb227829399b85a35838a506f8)]:
- @react-pdf/stylesheet@6.0.1
- @react-pdf/font@4.0.0
## 2.8.0
### Minor Changes
- [#3082](https://github.com/diegomura/react-pdf/pull/3082) [`24fe4bf8`](https://github.com/diegomura/react-pdf/commit/24fe4bf894fff055121926488b30d0bf212a9c45) Thanks [@diegomura](https://github.com/diegomura)! - feat: rework and type stylesheet package
- [#3079](https://github.com/diegomura/react-pdf/pull/3079) [`700535c5`](https://github.com/diegomura/react-pdf/commit/700535c57ff1b105d923be70f4fc4bfdf4479f91) Thanks [@diegomura](https://github.com/diegomura)! - refactor: convert font package to TS
### Patch Changes
- [#3067](https://github.com/diegomura/react-pdf/pull/3067) [`96c2464d`](https://github.com/diegomura/react-pdf/commit/96c2464dfaa7294e0d79b7ed64743bfd7b1a8c72) Thanks [@diegomura](https://github.com/diegomura)! - refactor: convert primitives package to TS
- Updated dependencies [[`96c2464d`](https://github.com/diegomura/react-pdf/commit/96c2464dfaa7294e0d79b7ed64743bfd7b1a8c72), [`24fe4bf8`](https://github.com/diegomura/react-pdf/commit/24fe4bf894fff055121926488b30d0bf212a9c45), [`700535c5`](https://github.com/diegomura/react-pdf/commit/700535c57ff1b105d923be70f4fc4bfdf4479f91)]:
- @react-pdf/primitives@4.1.1
- @react-pdf/stylesheet@6.0.0
- @react-pdf/font@3.1.0
## 2.7.1
### Patch Changes
- [#3019](https://github.com/diegomura/react-pdf/pull/3019) [`01944231`](https://github.com/diegomura/react-pdf/commit/01944231a342d502b832aeecb4c313020b8360c8) Thanks [@wojtekmaj](https://github.com/wojtekmaj)! - Fixed HyphenationCallback type (confusing argument name, removed extra argument)
## 2.7.0
### Minor Changes
- [#2875](https://github.com/diegomura/react-pdf/pull/2875) [`46c3047d`](https://github.com/diegomura/react-pdf/commit/46c3047de56ae82f062b72c4910a4e6096eee99f) Thanks [@diegomura](https://github.com/diegomura)! - feat: add position: static support
- [#2874](https://github.com/diegomura/react-pdf/pull/2874) [`55973278`](https://github.com/diegomura/react-pdf/commit/55973278ac8bc8f703b63844f57d6f155ae8d86f) Thanks [@diegomura](https://github.com/diegomura)! - feat: add align-content: space-evenly support
## 2.6.0
### Minor Changes
- [#2771](https://github.com/diegomura/react-pdf/pull/2771) [`8e6a832`](https://github.com/diegomura/react-pdf/commit/8e6a8320f86354aff950c296a96bc41a33e9dab2) Thanks [@nikischin](https://github.com/nikischin)! - fix: fix dpi
### Patch Changes
- [#2727](https://github.com/diegomura/react-pdf/pull/2727) [`4bafab8`](https://github.com/diegomura/react-pdf/commit/4bafab8455c9003759f48bad20a720baf4ed189b) Thanks [@hendrikmolder](https://github.com/hendrikmolder)! - accept string array for `fontFamily` in stylesheets
## 2.5.0
### Minor Changes
- [#2723](https://github.com/diegomura/react-pdf/pull/2723) [`22a34a9`](https://github.com/diegomura/react-pdf/commit/22a34a91b16a201cd8288e0dbea9368b12ca73f5) Thanks [@hendrikmolder](https://github.com/hendrikmolder)! - Allow passing a string array to fontFamily
## 2.4.1
### Patch Changes
- [#2573](https://github.com/diegomura/react-pdf/pull/2573) [`9af07fe`](https://github.com/diegomura/react-pdf/commit/9af07feb59c2fe9c1d8960ac95f6fa6e03d16235) Thanks [@davbrito](https://github.com/davbrito)! - feat: add support for resolving blob images
## 2.4.0
### Minor Changes
- [#2539](https://github.com/diegomura/react-pdf/pull/2539) [`fb5273d`](https://github.com/diegomura/react-pdf/commit/fb5273d8d80d919f7b9c214e02d67b79ce23fa19) Thanks [@diegomura](https://github.com/diegomura)! - feat: add creation and modification dates
## 2.3.6
### Patch Changes
- [#2525](https://github.com/diegomura/react-pdf/pull/2525) [`9e5842b`](https://github.com/diegomura/react-pdf/commit/9e5842bbecca6e249af2c5fc50078bb7ddd5420f) Thanks [@wojtekmaj](https://github.com/wojtekmaj)! - Fix rowGap and columnGap style properties not accepting strings
## 2.3.5
### Patch Changes
- [#2453](https://github.com/diegomura/react-pdf/pull/2453) [`e5c8fde`](https://github.com/diegomura/react-pdf/commit/e5c8fde9379a9a85ecac7e3d6273953e39d65f8d) Thanks [@chuckspencer-aiq](https://github.com/chuckspencer-aiq)! - fix: add clipPath to typing for SVGPresentationAttributes
* [#2467](https://github.com/diegomura/react-pdf/pull/2467) [`1f987cc`](https://github.com/diegomura/react-pdf/commit/1f987cc27c3fd1ef1b6748ebe58a289a78b538d2) Thanks [@JaeSeoKim](https://github.com/JaeSeoKim)! - feat: add withVariationSelectors option to registerEmojiSource [#2466](https://github.com/diegomura/react-pdf/issues/2466)
- [#2416](https://github.com/diegomura/react-pdf/pull/2416) [`4c40b14`](https://github.com/diegomura/react-pdf/commit/4c40b149cfed42f2513e1dd330a92ccc3363c04f) Thanks [@TheMikeyRoss](https://github.com/TheMikeyRoss)! - Updated svg.d.ts to include strokeLinejoin
## 2.3.4
### Patch Changes
- [#2130](https://github.com/diegomura/react-pdf/pull/2130) [`4a55c1b`](https://github.com/diegomura/react-pdf/commit/4a55c1b2ed19e460ccae6e749ed94c16729a23c4) Thanks [@PoornakumarRasiraju](https://github.com/PoornakumarRasiraju)! - fix: allow credentials option in Image
## 2.3.3
### Patch Changes
- [#2276](https://github.com/diegomura/react-pdf/pull/2276) [`1e1fbdc`](https://github.com/diegomura/react-pdf/commit/1e1fbdc3c33ced46d8c7ebba7a196733cb789d59) Thanks [@renchap](https://github.com/renchap)! - add `aspectRatio` style property
* [#2293](https://github.com/diegomura/react-pdf/pull/2293) [`8636812`](https://github.com/diegomura/react-pdf/commit/86368122ed87621d19ae3bc248080e17703d9fcb) Thanks [@BryanAbate](https://github.com/BryanAbate)! - fix type for `getRegisteredFonts` method
## 2.3.2
### Patch Changes
- [#2310](https://github.com/diegomura/react-pdf/pull/2310) [`a25dbcb`](https://github.com/diegomura/react-pdf/commit/a25dbcb32b65c300f5b088e8b210bb0c1abca5c2) Thanks [@wojtekmaj](https://github.com/wojtekmaj)! - Fixed all strings allowed in `fontWeight` in `Font.register`
## 2.3.1
### Patch Changes
- [#2252](https://github.com/diegomura/react-pdf/pull/2252) [`47e91cb`](https://github.com/diegomura/react-pdf/commit/47e91cbd8016046bb4e8389ba0d1c7ede9edce59) Thanks [@jeetiss](https://github.com/jeetiss)! - implement function as emoji source to build more complex urls
## 2.3.0
### Minor Changes
- [#2214](https://github.com/diegomura/react-pdf/pull/2214) [`2db67a3`](https://github.com/diegomura/react-pdf/commit/2db67a38b9be98b7816a2b5aa4733446b95e3724) Thanks [@KODIKAS-NL](https://github.com/KODIKAS-NL)! - added base support for verticalAlign "super" and "sub"
## 2.2.0
### Minor Changes
- [#2160](https://github.com/diegomura/react-pdf/pull/2160) [`a743c90`](https://github.com/diegomura/react-pdf/commit/a743c905fb5d201d2382bc9175fa36b83cc47284) Thanks [@jeetiss](https://github.com/jeetiss)! - implement flex gap
## 2.1.1
### Patch Changes
- [#2106](https://github.com/diegomura/react-pdf/pull/2106) [`24bb5de`](https://github.com/diegomura/react-pdf/commit/24bb5de969a854cc0226438985b34ef8ae2d7581) Thanks [@RDO34](https://github.com/RDO34)! - Add `dpi` and `bookmark` page prop types
## 2.1.0
### Minor Changes
- [#1862](https://github.com/diegomura/react-pdf/pull/1862) [`1411d16`](https://github.com/diegomura/react-pdf/commit/1411d162e04ca237bad93729695c363fdf4bdbeb) Thanks [@diegomura](https://github.com/diegomura)! - feat: bookmarks support
* [#1867](https://github.com/diegomura/react-pdf/pull/1867) [`4fadb48`](https://github.com/diegomura/react-pdf/commit/4fadb48983d7269452f89f80c7e341ece859aaee) Thanks [@diegomura](https://github.com/diegomura)! - feat: add page layout support
- [#1868](https://github.com/diegomura/react-pdf/pull/1868) [`ce8762f`](https://github.com/diegomura/react-pdf/commit/ce8762f6de5c796e69ec5a225c7f3ff9c619a960) Thanks [@diegomura](https://github.com/diegomura)! - feat: add page mode support
* [#1869](https://github.com/diegomura/react-pdf/pull/1869) [`5d2c308`](https://github.com/diegomura/react-pdf/commit/5d2c3088cf438a8abf1038b14a21117fecf59d57) Thanks [@diegomura](https://github.com/diegomura)! - feat: variable dpi
## 2.0.9
### Patch Changes
- [#1843](https://github.com/diegomura/react-pdf/pull/1843) [`fe0f214`](https://github.com/diegomura/react-pdf/commit/fe0f214dbbf2f632b852ebfe65f886ecc4dd6953) Thanks [@diegomura](https://github.com/diegomura)! - fix: add ID1 type
## 2.0.8
### Patch Changes
- [#1581](https://github.com/diegomura/react-pdf/pull/1581) [`04449ab`](https://github.com/diegomura/react-pdf/commit/04449ab352db0cca2155024dd3e8c690e42193ca) Thanks [@jeetiss](https://github.com/jeetiss)! - added changelog with changesets
+17
View File
@@ -0,0 +1,17 @@
<p align="center">
<img src="https://user-images.githubusercontent.com/5600341/27505816-c8bc37aa-587f-11e7-9a86-08a2d081a8b9.png" height="280px">
</p>
# @react-pdf/types
> React-pdf TypeScript definitions
## How to install
```sh
yarn add @react-pdf/types
```
## License
MIT © [Diego Muracciole](http://github.com/diegomura)
+10
View File
@@ -0,0 +1,10 @@
interface ExpandedBookmark {
title: string;
top?: number;
left?: number;
zoom?: number;
fit?: true | false;
expanded?: true | false;
}
export type Bookmark = string | ExpandedBookmark;
+76
View File
@@ -0,0 +1,76 @@
// instance.registerFont = vi.fn().mockReturnValue(instance);
// instance.note = vi.fn().mockReturnValue(instance);
// instance.rotate = vi.fn().mockReturnValue(instance);
// instance.scale = vi.fn().mockReturnValue(instance);
// instance.translate = vi.fn().mockReturnValue(instance);
// instance.link = vi.fn().mockReturnValue(instance);
// instance.goTo = vi.fn().mockReturnValue(instance);
// instance.addNamedDestination = vi.fn().mockReturnValue(instance);
// instance.clip = vi.fn().mockReturnValue(instance);
// instance.closePath = vi.fn().mockReturnValue(instance);
// instance.path = vi.fn().mockReturnValue(instance);
// instance.radialGradient = vi.fn().mockReturnValue(instance);
// instance.linearGradient = vi.fn().mockReturnValue(instance);
// instance.fontSize = vi.fn().mockReturnValue(instance);
// instance.text = vi.fn().mockReturnValue(instance);
// instance.font = vi.fn().mockReturnValue(instance);
interface DocumentInfo {
Producer?: string;
Creator?: string;
CreationDate?: Date;
Title?: string;
Author?: string;
Keywords?: string;
ModDate?: Date;
}
interface PageOption {
margin?: number;
size?: number[] | string;
}
interface ImageOption {
width?: number;
height?: number;
}
type ColorValue = string;
export interface Context {
info: DocumentInfo;
undash(): this;
end: () => void;
save: () => this;
restore: () => this;
lineCap(c: string): this;
miterLimit(m: any): this;
lineJoin(j: string): this;
lineWidth(w: number): this;
fill(color?: ColorValue): this;
stroke(color?: ColorValue): this;
moveTo(x: number, y: number): this;
lineTo(x: number, y: number): this;
opacity(opacity: number): this;
fillOpacity(opacity: number): this;
addPage(options?: PageOption): this;
polygon(...points: number[][]): this;
strokeOpacity(opacity: number): this;
dash(length: number, option: any): this;
circle(x: number, y: number, raduis: number): this;
fillColor(color: ColorValue, opacity?: number): this;
rect(x: number, y: number, w: number, h: number): this;
strokeColor(color: ColorValue, opacity?: number): this;
ellipse(x: number, y: number, r1: number, r2?: number): this;
quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): this;
image(src: any, x?: number, y?: number, options?: ImageOption): Context;
roundedRect(x: number, y: number, w: number, h: number, r?: number): this;
bezierCurveTo(
cp1x: number,
cp1y: number,
cp2x: number,
cp2y: number,
x: number,
y: number,
): this;
}
+8
View File
@@ -0,0 +1,8 @@
export {
FontStyle,
FontWeight,
EmojiSource,
FontDescriptor,
HyphenationCallback,
FontStoreType as FontStore,
} from '@react-pdf/font';
+37
View File
@@ -0,0 +1,37 @@
type HTTPMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
type SourceURL = string;
type SourceBuffer = Buffer;
type SourceBlob = Blob;
type SourceDataBuffer = { data: Buffer; format: 'png' | 'jpg' };
type SourceURLObject = {
uri: string;
method?: HTTPMethod;
body?: any;
headers?: any;
credentials?: 'omit' | 'same-origin' | 'include';
};
type Source =
| SourceURL
| SourceBuffer
| SourceBlob
| SourceDataBuffer
| SourceURLObject
| undefined;
type SourceFactory = () => Source;
type SourceAsync = Promise<Source>;
type SourceAsyncFactory = () => Promise<Source>;
export type SourceObject =
| Source
| SourceFactory
| SourceAsync
| SourceAsyncFactory;
+10
View File
@@ -0,0 +1,10 @@
export * from './pdf';
export * from './svg';
export * from './node';
export * from './page';
export * from './font';
export * from './style';
export * from './image';
export * from './context';
export * from './primitive';
export * from './bookmark';
+103
View File
@@ -0,0 +1,103 @@
import { Style } from './style';
import { Primitive } from './primitive';
import { HyphenationCallback } from './font';
import { PageSize, Orientation } from './page';
import { Bookmark } from './bookmark';
interface BaseProps {
id?: string;
fixed?: boolean;
break?: boolean;
debug?: boolean;
bookmark?: Bookmark;
minPresenceAhead?: number;
}
type DynamicRenderCallback = (props: {
pageNumber: number;
totalPages: number;
}) => any;
interface TextProps extends BaseProps {
wrap?: boolean;
widows?: number;
orphans?: number;
render?: DynamicRenderCallback;
hyphenationCallback?: HyphenationCallback;
}
interface ViewProps extends BaseProps {
wrap?: boolean;
render?: (props: { pageNumber: number }) => any;
}
interface PageProps extends BaseProps {
wrap?: boolean;
size?: PageSize;
orientation?: Orientation;
dpi?: number;
}
type PageLayout =
| 'singlePage'
| 'oneColumn'
| 'twoColumnLeft'
| 'twoColumnRight'
| 'twoPageLeft'
| 'twoPageRight';
type PageMode =
| 'useNone'
| 'useOutlines'
| 'useThumbs'
| 'fullScreen'
| 'useOC'
| 'useAttachments';
interface DocumentProps {
title?: string;
author?: string;
subject?: string;
keywords?: string;
creator?: string;
producer?: string;
creationDate?: Date;
modificationDate?: Date;
pageLayout?: PageLayout;
pageMode?: PageMode;
}
interface TextInstanceNode {
type: Primitive.TextInstance;
value: string;
}
interface TextNode {
type: Primitive.Text;
lines?: any[];
style?: Style;
props?: TextProps;
children?: TextInstanceNode[];
}
interface ViewNode {
type: Primitive.View;
style?: Style;
props?: ViewProps;
children?: (ViewNode | TextNode)[];
}
interface PageNode {
type: Primitive.Page;
style?: Style;
props?: PageProps;
children?: (ViewNode | TextNode)[];
}
export interface DocumentNode {
type: Primitive.Document;
props?: DocumentProps;
children: PageNode[];
}
export type Node = DocumentNode | PageNode | ViewNode;
+19
View File
@@ -0,0 +1,19 @@
{
"name": "@react-pdf/types",
"version": "2.9.0",
"license": "MIT",
"description": "React-pdf TypeScript definitions",
"author": "Diego Muracciole <diegomuracciole@gmail.com>",
"homepage": "https://github.com/diegomura/react-pdf#readme",
"main": "index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/diegomura/react-pdf.git",
"directory": "packages/types"
},
"dependencies": {
"@react-pdf/font": "^4.0.2",
"@react-pdf/primitives": "^4.1.1",
"@react-pdf/stylesheet": "^6.1.0"
}
}
+62
View File
@@ -0,0 +1,62 @@
export type Orientation = 'portrait' | 'landscape';
type StandardPageSize =
| '4A0'
| '2A0'
| 'A0'
| 'A1'
| 'A2'
| 'A3'
| 'A4'
| 'A5'
| 'A6'
| 'A7'
| 'A8'
| 'A9'
| 'A10'
| 'B0'
| 'B1'
| 'B2'
| 'B3'
| 'B4'
| 'B5'
| 'B6'
| 'B7'
| 'B8'
| 'B9'
| 'B10'
| 'C0'
| 'C1'
| 'C2'
| 'C3'
| 'C4'
| 'C5'
| 'C6'
| 'C7'
| 'C8'
| 'C9'
| 'C10'
| 'RA0'
| 'RA1'
| 'RA2'
| 'RA3'
| 'RA4'
| 'SRA0'
| 'SRA1'
| 'SRA2'
| 'SRA3'
| 'SRA4'
| 'EXECUTIVE'
| 'FOLIO'
| 'LEGAL'
| 'LETTER'
| 'TABLOID'
| 'ID1';
type StaticSize = number | string;
export type PageSize =
| StandardPageSize
| [StaticSize]
| [StaticSize, StaticSize]
| { width: StaticSize; height?: StaticSize };
+1
View File
@@ -0,0 +1 @@
export type PDFVersion = '1.3' | '1.4' | '1.5' | '1.6' | '1.7' | '1.7ext3';
+28
View File
@@ -0,0 +1,28 @@
import * as P from '@react-pdf/primitives';
export enum Primitive {
G = P.G,
Svg = P.Svg,
View = P.View,
Text = P.Text,
Link = P.Link,
Page = P.Page,
Note = P.Note,
Path = P.Path,
Rect = P.Rect,
Line = P.Line,
Stop = P.Stop,
Defs = P.Defs,
Image = P.Image,
Tspan = P.Tspan,
Canvas = P.Canvas,
Circle = P.Circle,
Ellipse = P.Ellipse,
Polygon = P.Polygon,
Document = P.Document,
Polyline = P.Polyline,
ClipPath = P.ClipPath,
TextInstance = P.TextInstance,
LinearGradient = P.LinearGradient,
RadialGradient = P.RadialGradient,
}

Some files were not shown because too many files have changed in this diff Show More