0.5.0 • Published 4 years ago

markdown4documentation v0.5.0

Weekly downloads
3
License
MIT
Repository
-
Last release
4 years ago

markdown4documentation

markdown4documentation is a tool that can either convert a single markdown file, a complete directory or a complex structure to HTML or PDF. You can choose between several build-in themes (called templates) or define a custom theme.

Complex structures mean that you can combine multiple markdown files into a single HTML or PDF file. You can insert prebuild HTML structures in the result also as well as whole pdf files.

markdown4documentation can either be used from the CLI or from inside a Node.js script.

Use the CLI

First, install from NPM:

npm install --global markdown4documentation

That's all, markdown4documentation is ready for use. NPM now has registered the command markdown4documentation, or shorter m4d.

Simple example

This example generates an HTML file from your Markdown file.

markdown4documentation --file README.md --output README.html

To generate a pdf, simply add --type:

m4d --file README.md --output README.pdf --type pdf

These commands use the default theme. markdown4documentation provides a material design theme also. Just add the --template parameter:

m4d --file README.md --output README.pdf --type pdf --template material

How to create your templates is explained further below.

For more features use a configuration file:

m4d --configuration configuration.json

CLI Parameters

ParameterShortcutDescription
--file-fRequired. Markdown file
--output-oRequired. Path to save the new file
--type-tOptional, default html. Output format, either html or pdf
--templateOptional. A template; can be a build-in template or a custom template.
--configuration-cA configuration file. If set, all other parameters are forbidden.

Create a custom template

A template is a JavaScript file, which defines, how markdown4documentation renders HTML elements. To create an own template file, you can copy one of the built-in templates and modify them. You can find the build-in templates in the templates folder.

To set a custom template, just provide the relative or absolute path to the file to the --template parameter.

Create a configuration file

A configuration file is a JSON file. It has one property jobs. Each job describes a conversion.

Sample:

{
    'jobs': []
}
ParameterTypeDefaultDescription
jobsArray\[]Jobs to process

Jobs

markdown4documentation supports three different modes of jobs: file, directory and merge.

  • file: Convert a single file, like with the CLI parameters
  • directory: Convert all Markdown files in a directory
  • merge: Merge multiple Markdown files to one output file

Sample:

{
    'jobs': [
        {
            'mode': 'file',
            'type': 'html',
            'template': 'default',
            'input': 'myFile.md',
            'output': 'myFile.html',
            'suppressLeadingH1': false,
            'indentHeadlines': 0,
            'headingNumbering': false,
            'pdfOptions': {...}
        }
    ]
}

A Job has this parameters:

ParameterTypeDefaultDescription
modestring'file'The mode of the job.
typestring'html'The output format. Either html or pdf.
templatestring'default'The template to use.
inputstring | Array\-Mode file: input fileMode directory: input directoryMode merge: Merge object
outputstring-Mode file: output fileMode directory: output directoryMode merge: output file
suppressLeadingH1booleanfalseNot allowed in merge mode.If true and the first element in the md file is a level 1 heading, it's skipped.
indentHeadlinesnumber0Not allowed in merge mode.Indent every heading in the markdown file.
headingNumberingbooleanfalseAutomatically add numbers to all headings
pdfOptionsObject\Some options to customize pdf generation. Ignored, if type is different then pdf.

PdfOptions

PdfOptions has these parameters:

ParameterTypeDefaultDescription
formatstring'A4'The format of the pages. If explicitly set, width and height are ignored.
widthstring-The width of each page. It is ignored if format is explicitly set. The format of the string is described below this table.
heightstring-The height of each page. It is ignored if format is explicitly set. The format of the string is described below this table.
landscapebooleanbooleanSets if the page format should be rotated.
marginObject-The object has the properties top, right, bottom and left, the values are units (see below the table). This sets a margin for the content of the pdf. top and bottom default to ' '1.5cm' and right and left to '1cm'.
displayHeaderFooterbooleanfalseDisplays a custom header and footer on each page.
headerTemplatestring-A HTML template for a header on each page. It is ignored if displayHeaderFooter is not set to true. See remarks below the table.
footerTemplateboolean-A HTML template for a footer on each page. It is ignored if displayHeaderFooter is not set to true. See remarks below the table.

Size Units

Size can be measured in centimeter, millimeter or inch. For centimeter set for example '2cm', for millimeter '20mm' and inch '0.78in'.

Header and footer templates

There are some things you should note on the header and footer template:

  • Your templates should be included in a surrounding div.
  • The default font-size is very small, so you have to set the font-size manually.
  • To remove the default space above and under the header and footer, add this style at the very beginning of the header or footer template: <style>#header, #footer { padding: 0 !important; }</style>.
  • The default width of a surrounding div is not 100% as usual. You have to set the width manually to 100% if needed.
  • You can inject some predefined values: date, pageNumber and totalPages. Add it as a CSS class: <span class='totalPages'></span>.
  • You cannot add images by URL, you have to include images as base64 encoded string.

A possible header could be this:

<style>#header, #footer { padding: 0 !important; }</style><div style='font-size: 10px'>Hello world, Page <span class='pageNumber'></span></div>

Tasks

A task is one file of a merge job.

Sample:

{
    'jobs': [
        {
            'mode': 'merge',
            ...
            'input': [
                {
                    'type': 'file',
                    'file': 'myFile.md',
                    'suppressLeadingH1': false,
                    'indentHeadlines': 0,
                    'sub': []
                }
            ]
        }
    ]
}

A Task has these parameters:

ParameterTypeDefaultDescription
typestring'file'Either file to read content from a file or heading to insert a single heading. Not to be confused with type of a Job.
filestring-Only with type file. A Markdown file or HTML file or PDF file. If it is a .html or .htm file, all other parameters are ignored and the content of the file is copied to the output without any interpretation. If it is a .pdf file, this pdf file is included in the output pdf. .pdf files are only allowed with output type pdf.
contentstring-Only with type heading. The heading to be insert.
suppressLeadingH1booleanfalseIf true and the first element in the md file is a level 1 heading, it's skipped.
indentHeadlinesnumber0Indent every heading in the markdown file.
subArray\[]A list of Task objects, which headlines are indented one level (including indentHeadlines).

Use with Node.js script

markdown4documentation can be used manually to convert Markdown files to HTML or PDF files.

Install with NPM:

npm install --save markdown4documentation

Require in a script:

const m4d = require('markdown4documentation');

markdown4documentation consists of four main classes.

ClassDescription
m4d.ConfigurationA configuration object, similar to a configuration file.
m4d.ProcessorUses a configuration object to create HTML and PDF files.
m4d.HtmlBuilderA class to create HTML based on a template.
m4d.HtmlParserThe main parser to convert Markdown to HTML.

markdown4documentation has two more classes, which can't be created manually.

ClassDescription
JobA job, equivalent to a job in a configuration file.
TaskA task of a job, equivalent to a task in a configuration file.

Parse a single markdown file

This sample parses markdown to HTML.

const m4d = require('markdown4documentation');

// For a build in template:
const template = m4d.Templates.default;

// For a custom template:
const template = require('path/to/template');

const htmlBuilder = new m4d.HtmlBuilder(template);

const markdown = '...';

const htmlParser = new m4d.HtmlParser(markdown, htmlBuilder);
let html = htmlParser.Parse();

html = htmlBuilder.BuildPage(html);

To create a PDF file you either have to use a configuration or create it manually. markdown4documentation uses Puppeteer for PDF creation.

Classes

Class 'Configuration'

MethodDescription
constructor()Creates a new configuration.
CreateJob(): JobCreates a new job an returns it so that you can fill it with information.
PropertyTypeDescription
get JobsArray\Get all Jobs of this configuration.

Class 'Job'

MethodDescription
CreateTask(): TaskCreates a new task an returns it so that you can fill it with information.
PropertyTypeDescription
get/set TypestringSets the type of the job, can be html or pdf.
get InputArray\Get all Tasks of this job.
get/set OutputstringThe file to output.
TemplateNode ModuleA Template-Module (see the example above).
PdfOptionsPdfOptionsOptions for pdf generation.
HeadingNumberingbooleanAutomatically add numbers to all headings

Class 'PdfOptions'

PropertyTypeDescription
get/set FormatstringThe format of the pages. Defaults to 'A4'.
get/set WidthstringThe width of each page. Is ignored, if format is not set to undefined. The format of this string is explained here.
get/set heightstringThe width of each page. Is ignored, if format is not set to undefined. The format of this string is explained here.
get/set LandscapebooleanSets if the page format should be rotated.
MarginObjectThe object has the properties Top, Right, Bottom and Left, the values are units (see below the table). This sets a margin for the content of the pdf. Top and Bottom default to ' '1.5cm' and Right and Left to '1cm'.
get/set DisplayHeaderFooterbooleanDisplays a custom header and footer on each page.
get/set HeaderTemplatestringA HTML template for a header on each page. It is ignored if DisplayHeaderFooter is not set to true. A description of how to write a header can be found here.
get/set FooterTemplatestringA HTML template for a footer on each page. It is ignored if displayHeaderFooter is not set to true. A description of how to write a header can be found here.

Class 'Task'

MethodDescription
CreateSubTask(): TaskCreates a new subtask and returns it, so that you can fill it with information.
PropertyTypeDescription
get/set TypestringEither file to read content from a file or heading to insert a single heading.
get/set FilestringOnly with type file. The markdown file to use. It can be an md file, an HTML file or a pdf file. A pdf file is only allowed if Type of the corresponding Job is pdf.
get/set ContentstringOnly with type heading. The heading to be insert.
get/set SuppressLeadingH1booleanIf true and the first element in the md file is a level 1 heading, it's skipped. Defaults to false.
IndentHeadlinesnumberIndent every heading in the markdown file. Defaults to 0.
get SubArray\A list of Task, which headlines are indented one level (including indentHeadlines).

Class 'Processor'

MethodDescription
constructor(configuration: Configuration)Creates a new processor based on a configuration.
async Process()Processes the configuration.

Class 'HtmlBuilder'

MethodDescription
constructor(template)Creates a new HtmlBuilder with a specific template.
BuildTag(tag: string, attributes: object, content: string)Creates a Html Tag. Note that the build-in templates considers 'attributes' currently only at a, img and headline tags.
BuildPage(content: string)Wraps the content in HTML.
ResetHNumbers()Disables automatic numbering of headings and set counters to zero.
EnableHNumbering(enable: boolean)Enable or disable automatic numbering of headings.

Class 'HtmlParser'

MethodDescription
constructor(markdown: string, builder: HtmlBuilder)Creates a new Parser.
Parse(): stringParses the markdown into HTML and returns it.
PropertyTypeDescription
set BaseHeadlineLevelnumberThe minimum headline level. Defaults to 1.
set SuppressLeadingH1booleanIf true, ignore the top heading if it is the first in the file. Defaults to false.

Disclaimer

markdown4documentation may have some other Methods and Properties that can be accessed. But all classes, methods, properties, variables and so on that are not mentioned here are not considered as stable and may not be determined for public use.

Contributing

Do you want to contribute to this project? Great! Please consider reading the contributions guideline in the CONTRIBUTING.md.