This commit is contained in:
Libor M. 2024-12-24 13:05:20 +01:00
parent a2ee174ebb
commit 94166696b3
5 changed files with 0 additions and 629 deletions

10
.gitignore vendored
View File

@ -1,12 +1,2 @@
lib/font/tables/.DS_Store
.DS_Store
/node_modules/
node-zlib/
src/
playground/
build/
js/
.vscode
coverage
tests/integration/__pdfs__
tests/integration/pdfmake/__pdfs__

View File

@ -1,348 +0,0 @@
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS103: Rewrite code to no longer use __guard__
* DS205: Consider reworking code to avoid use of IIFEs
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const fs = require('fs');
const vm = require('vm');
const md = require('markdown').markdown;
const CodeMirror = require('codemirror/addon/runmode/runmode.node');
const PDFDocument = require('../');
process.chdir(__dirname);
// setup code mirror javascript mode
const filename = require.resolve('codemirror/mode/javascript/javascript');
const jsMode = fs.readFileSync(filename, 'utf8');
vm.runInNewContext(jsMode, { CodeMirror });
// style definitions for markdown
const styles = {
h1: {
font: 'fonts/Alegreya-Bold.ttf',
fontSize: 25,
padding: 15
},
h2: {
font: 'fonts/Alegreya-Bold.ttf',
fontSize: 18,
padding: 10
},
h3: {
font: 'fonts/Alegreya-Bold.ttf',
fontSize: 18,
padding: 10
},
para: {
font: 'fonts/Merriweather-Regular.ttf',
fontSize: 10,
padding: 10
},
code: {
font: 'fonts/SourceCodePro-Regular.ttf',
fontSize: 9
},
code_block: {
padding: 10,
background: '#2c2c2c'
},
inlinecode: {
font: 'fonts/SourceCodePro-Bold.ttf',
fontSize: 10
},
listitem: {
font: 'fonts/Merriweather-Regular.ttf',
fontSize: 10,
padding: 6
},
link: {
font: 'fonts/Merriweather-Regular.ttf',
fontSize: 10,
color: 'blue',
underline: true
},
example: {
font: 'Helvetica',
fontSize: 9,
color: 'black',
padding: 10
}
};
// syntax highlighting colors
// based on Github's theme
const colors = {
keyword: '#cb4b16',
atom: '#d33682',
number: '#009999',
def: '#2aa198',
variable: '#108888',
'variable-2': '#b58900',
'variable-3': '#6c71c4',
property: '#2aa198',
operator: '#6c71c4',
comment: '#999988',
string: '#dd1144',
'string-2': '#009926',
meta: '#768E04',
qualifier: '#b58900',
builtin: '#d33682',
bracket: '#cb4b16',
tag: '#93a1a1',
attribute: '#2aa198',
header: '#586e75',
quote: '#93a1a1',
link: '#93a1a1',
special: '#6c71c4',
default: '#002b36'
};
// shared lorem ipsum text so we don't need to copy it into every example
const lorem =
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in suscipit purus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus nec hendrerit felis. Morbi aliquam facilisis risus eu lacinia. Sed eu leo in turpis fringilla hendrerit. Ut nec accumsan nisl. Suspendisse rhoncus nisl posuere tortor tempus et dapibus elit porta. Cras leo neque, elementum a rhoncus ut, vestibulum non nibh. Phasellus pretium justo turpis. Etiam vulputate, odio vitae tincidunt ultricies, eros odio dapibus nisi, ut tincidunt lacus arcu eu elit. Aenean velit erat, vehicula eget lacinia ut, dignissim non tellus. Aliquam nec lacus mi, sed vestibulum nunc. Suspendisse potenti. Curabitur vitae sem turpis. Vestibulum sed neque eget dolor dapibus porttitor at sit amet sem. Fusce a turpis lorem. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;';
let codeBlocks = [];
let lastType = null;
// This class represents a node in the markdown tree, and can render it to pdf
class Node {
constructor(tree) {
// special case for text nodes
if (typeof tree === 'string') {
this.type = 'text';
this.text = tree;
return;
}
this.type = tree.shift();
this.attrs = {};
if (typeof tree[0] === 'object' && !Array.isArray(tree[0])) {
this.attrs = tree.shift();
}
// parse sub nodes
this.content = (() => {
const result = [];
while (tree.length) {
result.push(new Node(tree.shift()));
}
return result;
})();
switch (this.type) {
case 'header':
this.type = `h${this.attrs.level}`;
break;
case 'code_block':
// use code mirror to syntax highlight the code block
var code = this.content[0].text;
this.content = [];
CodeMirror.runMode(code, 'javascript', (text, style) => {
const color = colors[style] || colors.default;
const opts = {
color,
continued: text !== '\n'
};
return this.content.push(new Node(['code', opts, text]));
});
__guard__(
this.content[this.content.length - 1],
x => (x.attrs.continued = false)
);
codeBlocks.push(code);
break;
case 'img':
// images are used to generate inline example output
// stores the JS so it can be run
// in the render method
this.type = 'example';
code = codeBlocks[this.attrs.alt];
if (code) {
this.code = code;
}
this.height = +this.attrs.title || 0;
break;
}
this.style = styles[this.type] || styles.para;
}
// sets the styles on the document for this node
setStyle(doc) {
if (this.style.font) {
doc.font(this.style.font);
}
if (this.style.fontSize) {
doc.fontSize(this.style.fontSize);
}
if (this.style.color || this.attrs.color) {
doc.fillColor(this.style.color || this.attrs.color);
} else {
doc.fillColor('black');
}
const options = {};
options.align = this.style.align;
options.link = this.attrs.href || false; // override continued link
if (this.attrs.continued != null) {
options.continued = this.attrs.continued;
}
return options;
}
// renders this node and its subnodes to the document
render(doc, continued) {
let y;
if (continued == null) {
continued = false;
}
switch (this.type) {
case 'example':
this.setStyle(doc);
// translate all points in the example code to
// the current point in the document
doc.moveDown();
doc.save();
doc.translate(doc.x, doc.y);
var { x } = doc;
({ y } = doc);
doc.x = doc.y = 0;
// run the example code with the document
vm.runInNewContext(this.code, {
doc,
lorem
});
// restore points and styles
y += doc.y;
doc.restore();
doc.x = x;
doc.y = y + this.height;
break;
case 'hr':
doc.addPage();
break;
default:
// loop through subnodes and render them
for (let index = 0; index < this.content.length; index++) {
const fragment = this.content[index];
if (fragment.type === 'text') {
// add a new page for each heading, unless it follows another heading
if (
['h1', 'h2'].includes(this.type) &&
lastType != null &&
lastType !== 'h1'
) {
doc.addPage();
}
if (this.type === 'h1') {
doc.h1Outline = doc.outline.addItem(fragment.text);
} else if (this.type === 'h2' && doc.h1Outline !== null) {
doc.h1Outline.addItem(fragment.text);
}
// set styles and whether this fragment is continued (for rich text wrapping)
const options = this.setStyle(doc);
if (options.continued == null) {
options.continued = continued || index < this.content.length - 1;
}
// remove newlines unless this is code
if (this.type !== 'code') {
fragment.text = fragment.text.replace(/[\r\n]\s*/g, ' ');
}
doc.text(fragment.text, options);
} else {
fragment.render(
doc,
index < this.content.length - 1 && this.type !== 'bulletlist'
);
}
lastType = this.type;
}
}
if (this.style.padding) {
return (doc.y += this.style.padding);
}
}
}
// reads and renders a markdown/literate javascript file to the document
const render = function(doc, filename) {
codeBlocks = [];
const tree = md.parse(fs.readFileSync(filename, 'utf8'));
tree.shift();
return (() => {
const result = [];
while (tree.length) {
const node = new Node(tree.shift());
result.push(node.render(doc));
}
return result;
})();
};
// renders the title page of the guide
const renderTitlePage = function(doc) {
const title = 'PDFKit Guide';
const author = 'By Devon Govett';
const version = `Version ${require('../package.json').version}`;
doc.font('fonts/AlegreyaSans-Light.ttf', 60);
doc.y = doc.page.height / 2 - doc.currentLineHeight();
doc.text(title, { align: 'center' });
const w = doc.widthOfString(title);
doc.h1Outline = doc.outline.addItem(title);
doc.fontSize(20);
doc.y -= 10;
doc.text(author, {
align: 'center',
indent: w - doc.widthOfString(author)
});
doc.font(styles.para.font, 10);
doc.text(version, {
align: 'center',
indent: w - doc.widthOfString(version)
});
return doc.addPage();
};
// render all sections of the guide and write the pdf file
(function() {
const doc = new PDFDocument();
doc.pipe(fs.createWriteStream('guide.pdf'));
renderTitlePage(doc);
render(doc, 'getting_started.md');
render(doc, 'vector.md');
render(doc, 'text.md');
render(doc, 'images.md');
render(doc, 'outline.md');
render(doc, 'annotations.md');
return doc.end();
})();
function __guard__(value, transform) {
return typeof value !== 'undefined' && value !== null
? transform(value)
: undefined;
}

View File

@ -1,128 +0,0 @@
const jade = require('jade');
const { markdown } = require('markdown');
const fs = require('fs');
const vm = require('vm');
const { exec } = require('child_process');
const PDFDocument = require('../');
process.chdir(__dirname);
if (!fs.existsSync('img')) {
fs.mkdirSync('img');
}
const files = [
'../README.md',
'getting_started.md',
'vector.md',
'text.md',
'images.md',
'annotations.md'
];
// shared lorem ipsum text so we don't need to copy it into every example
const lorem =
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in suscipit purus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus nec hendrerit felis. Morbi aliquam facilisis risus eu lacinia. Sed eu leo in turpis fringilla hendrerit. Ut nec accumsan nisl. Suspendisse rhoncus nisl posuere tortor tempus et dapibus elit porta. Cras leo neque, elementum a rhoncus ut, vestibulum non nibh. Phasellus pretium justo turpis. Etiam vulputate, odio vitae tincidunt ultricies, eros odio dapibus nisi, ut tincidunt lacus arcu eu elit. Aenean velit erat, vehicula eget lacinia ut, dignissim non tellus. Aliquam nec lacus mi, sed vestibulum nunc. Suspendisse potenti. Curabitur vitae sem turpis. Vestibulum sed neque eget dolor dapibus porttitor at sit amet sem. Fusce a turpis lorem. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;';
const extractHeaders = function(tree) {
const headers = [];
for (let index = 0; index < tree.length; index++) {
const node = tree[index];
if (node[0] === 'header' && (headers.length === 0 || node[1].level > 1)) {
if (node[1].level > 2) {
node[1].level = 2;
}
const hash = node[2].toLowerCase().replace(/\s+/g, '_');
node[1].id = hash;
headers.push({
hash,
title: node[2]
});
}
}
return headers;
};
let imageIndex = 0;
const generateImages = function(tree) {
// find code blocks
const codeBlocks = [];
for (var node of tree) {
if (node[0] === 'code_block') {
codeBlocks.push(node[1]);
}
}
for (node of tree) {
if (node[0] === 'para' && Array.isArray(node[1]) && node[1][0] === 'img') {
// compile the code
const attrs = node[1][1];
let code = codeBlocks[attrs.alt];
delete attrs.height; // used for pdf generation
// create a PDF and run the example
const doc = new PDFDocument();
const f = `img/${imageIndex++}`;
var file = fs.createWriteStream(`${f}.pdf`);
doc.pipe(file);
doc.translate(doc.x, doc.y);
doc.scale(0.8);
doc.x = doc.y = 0;
vm.runInNewContext(code, {
doc,
lorem
});
delete attrs.title;
delete attrs.alt;
attrs.href = `${f}.png`;
// write the PDF, convert to PNG using the mac `sips`
// command line tool, and trim with graphicsmagick
file.on('finish', () =>
exec(`sips -s format png ${f}.pdf --out ${f}.png`, function() {
fs.unlink(`${f}.pdf`);
exec(`gm convert ${f}.png -trim ${f}.png`);
})
);
}
}
};
const pages = [];
for (let file of Array.from(files)) {
let content = fs.readFileSync(file, 'utf8');
// turn github highlighted code blocks into normal markdown code blocks
content = content.replace(
/^```javascript\n((:?.|\n)*?)\n```/gm,
(m, $1) => ` ${$1.split('\n').join('\n ')}`
);
const tree = markdown.parse(content);
const headers = extractHeaders(tree);
generateImages(tree);
file = file.replace(/README\.md/, 'index').replace(/\.md$/, '');
pages.push({
file,
url: `/docs/${file}.html`,
title: headers[0].title,
headers: headers.slice(1),
content: markdown.toHTML(tree)
});
}
for (let index = 0; index < pages.length; index++) {
const page = pages[index];
page.pages = pages;
page.index = index;
const html = jade.renderFile('template.jade', page);
fs.writeFileSync(page.file + '.html', html, 'utf8');
}

View File

@ -1,88 +0,0 @@
# Paper Sizes
When creating a new document or adding a new page to your current document, PDFKit allows you to set the page dimensions. To improve convenience, PDFKit has a number of predefined page sizes. These sizes are based on the most commonly used stndard page sizes.
### Predefined Page Sizes
The following predefined sizes are based on the ISO (International) standards. All the dimensions in brackets are in PostScript points.
#### A-series
* A0 (2383.94 x 3370.39)
* A1 (1683.78 x 2383.94)
* A2 (1190.55 x 1683.78)
* A3 (841.89 x 1190.55)
* A4 (595.28 x 841.89)
* A5 (419.53 x 595.28)
* A6 (297.64 x 419.53)
* A7 (209.76 x 297.64)
* A8 (147.40 x 209.76)
* A9 (104.88 x 147.40)
* A10 (73.70 x 104.88)
#### B-series
* B0 (2834.65 x 4008.19)
* B1 (2004.09 x 2834.65)
* B2 (1417.32 x 2004.09)
* B3 (1000.63 x 1417.32)
* B4 (708.66 x 1000.63)
* B5 (498.90 x 708.66)
* B6 (354.33 x 498.90)
* B7 (249.45 x 354.33)
* B8 (175.75 x 249.45)
* B9 (124.72 x 175.75)
* B10 (87.87 x 124.72)
#### C-series
* C0 (2599.37 x 3676.54)
* C1 (1836.85 x 2599.37)
* C2 (1298.27 x 1836.85)
* C3 (918.43 x 1298.27)
* C4 (649.13 x 918.43)
* C5 (459.21 x 649.13)
* C6 (323.15 x 459.21)
* C7 (229.61 x 323.15)
* C8 (161.57 x 229.61)
* C9 (113.39 x 161.57)
* C10 (79.37 x 113.39)
#### RA-series
* RA0 (2437.80 x 3458.27)
* RA1 (1729.13 x 2437.80)
* RA2 (1218.90 x 1729.13)
* RA3 (864.57 x 1218.90)
* RA4 (609.45 x 864.57)
#### SRA-series
* SRA0 (2551.18 x 3628.35)
* SRA1 (1814.17 x 2551.18)
* SRA2 (1275.59 x 1814.17)
* SRA3 (907.09 x 1275.59)
* SRA4 (637.80 x 907.09)
The following predefined sizes are based on the common paper sizes used mainly in the United States of America and Canada. The dimensions in brackets are in PostScript points.
* EXECUTIVE (521.86 x 756.00)
* LEGAL (612.00 x 1008.00)
* LETTER (612.00 X 792.00)
* TABLOID (792.00 X 1224.00)
PDFKit supports also the following paper sizes. The dimensions in brackets are in PostScript points.
* 4A0 (4767.89 x 6740.79)
* 2A0 (3370.39 x 4767.87)
* FOLIO (612.00 X 936.00)
### Setting the page size
In order to use the predefined sizes, the name of the size (as named in the lists above) should be passed to either the `PDFDocument` constructor or the `addPage()` function in the `size` property of the `options` object, as shown in the example below, using `A7` as the preferred size.
// Passing size to the constructor
const doc = new PDFDocument({size: 'A7'});
// Passing size to the addPage function
doc.addPage({size: 'A7'});

View File

@ -1,55 +0,0 @@
doctype html
html
head
meta(charset='utf-8')
title= title
link(rel='stylesheet', href='http://fonts.googleapis.com/css?family=Source+Code+Pro:400,700|Alegreya:700|Merriweather')
link(rel='stylesheet', href='/docs/css/index.css')
link(rel='stylesheet', href='/docs/css/github.css')
body
nav(class='sidebar')
ul
li
a(href='/', class=(/index/.test(url) ? 'selected' : '')) Home
li
a(href=pages[0].url) Documentation
ul
each page in pages.slice(1)
li
a(href=page.url, class=page.title == title ? 'selected' : '')
= page.title.replace(/(with|in) PDFKit/, '')
- if (page.title == title && headers.length)
ul
each header in headers
li
a(href='#' + header.hash)= header.title
li
a(href='/docs/guide.pdf') PDF Guide
li
a(href='/demo/out.pdf') Example PDF
li
a(href='/demo/browser.html') Interactive Browser Demo
li
a(href='http://github.com/devongovett/pdfkit') Source Code
.main
!= content
nav
- if (index > 0)
a(href=pages[index - 1].url, class='previous') Previous
- if (index < pages.length - 1)
a(href=pages[index + 1].url, class='next') Next
script(src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js')
script(src='/docs/js/scroll.js')
script(src='/docs/js/highlight.pack.js')
script.
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-48340245-1', 'pdfkit.org');
ga('send', 'pageview');