{"id":23338229,"url":"https://github.com/aymkdn/html-to-pdfmake","last_synced_at":"2025-05-14T05:10:25.555Z","repository":{"id":37430873,"uuid":"180160996","full_name":"Aymkdn/html-to-pdfmake","owner":"Aymkdn","description":"This module permits to convert HTML to the PDFMake format","archived":false,"fork":false,"pushed_at":"2025-05-03T13:18:52.000Z","size":813,"stargazers_count":595,"open_issues_count":1,"forks_count":90,"subscribers_count":7,"default_branch":"master","last_synced_at":"2025-05-07T17:05:37.527Z","etag":null,"topics":["javascript","pdf"],"latest_commit_sha":null,"homepage":"https://aymkdn.github.io/html-to-pdfmake/index.html","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Aymkdn.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":"aymkdn"}},"created_at":"2019-04-08T13:59:14.000Z","updated_at":"2025-05-05T07:49:25.000Z","dependencies_parsed_at":"2024-04-17T09:45:21.369Z","dependency_job_id":"ba72106b-dff4-49db-9256-572aa7905733","html_url":"https://github.com/Aymkdn/html-to-pdfmake","commit_stats":{"total_commits":176,"total_committers":13,"mean_commits":"13.538461538461538","dds":0.1477272727272727,"last_synced_commit":"950b6c8eb7f53814989363240361e4e8dbcc8a51"},"previous_names":[],"tags_count":114,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Aymkdn%2Fhtml-to-pdfmake","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Aymkdn%2Fhtml-to-pdfmake/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Aymkdn%2Fhtml-to-pdfmake/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Aymkdn%2Fhtml-to-pdfmake/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Aymkdn","download_url":"https://codeload.github.com/Aymkdn/html-to-pdfmake/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254076850,"owners_count":22010611,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["javascript","pdf"],"created_at":"2024-12-21T03:12:48.090Z","updated_at":"2025-05-14T05:10:25.530Z","avatar_url":"https://github.com/Aymkdn.png","language":"JavaScript","funding_links":["https://github.com/sponsors/aymkdn","https://www.paypal.me/aymkdn","https://github.com/sponsors/Aymkdn"],"categories":[],"sub_categories":[],"readme":"# html-to-pdfmake\n\nConvert HTML to PDFMake format with ease. This library bridges the gap between HTML content and [PDFMake](https://pdfmake.github.io/docs/) document definitions, allowing you to generate PDFs from basic HTML while maintaining based styling and structure.\n\n**Note**: if you need to convert a complex HTML, check some online solutions, like [Doppio](https://doppio.sh/), or you could try to convert [your HTML to canvas](https://github.com/chearon/dropflow) and then to [export it to PDF](https://github.com/parallax/jsPDF).\n\n## Features\n\n- Convert HTML to PDFMake-compatible format\n- Preserve basic styling and structure\n- Support for tables, lists, images, and more\n- Customizable styling options\n- Works in both browser and Node.js environments\n- Handle nested elements\n- Custom tag support\n- Image handling with reference support\n\n## Online Demo\n\nTry it live with the [online demo](https://aymkdn.github.io/html-to-pdfmake/index.html).\n\n## Quick Start\n\n### Browser Usage\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml\u003e\n\u003chead\u003e\n  \u003c!-- Include required libraries --\u003e\n  \u003cscript src=\"https://cdn.jsdelivr.net/npm/pdfmake@latest/build/pdfmake.min.js\"\u003e\u003c/script\u003e\n  \u003cscript src=\"https://cdn.jsdelivr.net/npm/pdfmake@latest/build/vfs_fonts.min.js\"\u003e\u003c/script\u003e\n  \u003cscript src=\"https://cdn.jsdelivr.net/npm/html-to-pdfmake/browser.js\"\u003e\u003c/script\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n  \u003cscript\u003e\n    // Convert HTML to PDFMake format\n    const html = `\n      \u003cdiv\u003e\n        \u003ch1\u003eSample Document\u003c/h1\u003e\n        \u003cp\u003eThis is a \u003cstrong\u003esimple\u003c/strong\u003e example with \u003cem\u003eformatted\u003c/em\u003e text.\u003c/p\u003e\n      \u003c/div\u003e\n    `;\n    \n    const converted = htmlToPdfmake(html);\n    const docDefinition = { content: converted };\n    \n    // Generate PDF\n    pdfMake.createPdf(docDefinition).download('document.pdf');\n  \u003c/script\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\n### Node.js Usage\n\n```bash\nnpm install html-to-pdfmake jsdom\n```\n\n```javascript\nconst pdfMake = require('pdfmake/build/pdfmake');\nconst pdfFonts = require('pdfmake/build/vfs_fonts');\nconst htmlToPdfmake = require('html-to-pdfmake');\nconst jsdom = require('jsdom');\nconst { JSDOM } = jsdom;\n\n// the below line may vary depending on your version of PDFMake\n// please, check https://github.com/bpampuch/pdfmake to know how to initialize this library\npdfMake.vfs = pdfFonts;\n\n// initiate the \"window\" object in Node\nconst { window } = new JSDOM('');\n\n// Convert HTML to PDFMake format\nconst html = `\n  \u003cdiv\u003e\n    \u003ch1\u003eSample Document\u003c/h1\u003e\n    \u003cp\u003eThis is a \u003cstrong\u003esimple\u003c/strong\u003e example with \u003cem\u003eformatted\u003c/em\u003e text.\u003c/p\u003e\n  \u003c/div\u003e\n`;\n\nconst converted = htmlToPdfmake(html, { window });\nconst docDefinition = { content: converted };\n\n// Generate PDF\npdfMake.createPdf(docDefinition).getBuffer((buffer) =\u003e {\n  require('fs').writeFileSync('output.pdf', buffer);\n});\n```\n\n## Supported HTML Elements\n\n### Block Elements\n- `\u003cdiv\u003e`, `\u003cp\u003e`, `\u003ch1\u003e` to `\u003ch6\u003e`\n- `\u003ctable\u003e`, `\u003cthead\u003e`, `\u003ctbody\u003e`, `\u003ctfoot\u003e`, `\u003ctr\u003e`, `\u003cth\u003e`, `\u003ctd\u003e`\n- `\u003cul\u003e`, `\u003col\u003e`, `\u003cli\u003e`\n- `\u003cpre\u003e`\n\n### Inline Elements\n- `\u003cspan\u003e`, `\u003cstrong\u003e`, `\u003cb\u003e`, `\u003cem\u003e`, `\u003ci\u003e`, `\u003cs\u003e`\n- `\u003ca\u003e` (with support for external and internal links)\n- `\u003csub\u003e`, `\u003csup\u003e`\n- `\u003cimg\u003e`, `\u003csvg\u003e`\n- `\u003cbr\u003e`, `\u003chr\u003e`\n\n### CSS Properties Support\n\nThe library handles these CSS properties:\n\n| Property | Support Details |\n|----------|----------------|\n| `background-color` | Good support |\n| `border` | Including individual borders |\n| `color` | Good support, including opacity |\n| `font-family` | Basic support |\n| `font-style` | Support for `italic` |\n| `font-weight` | Support for `bold` |\n| `height` | For tables and images |\n| `width` | For tables and images |\n| `margin` | Including individual margins |\n| `text-align` | Good support |\n| `text-decoration` | Support for `underline`, `line-through` |\n| `text-indent` | Basic support |\n| `white-space` | Support for `nowrap`, `pre`, `break-spaces` |\n| `line-height` | Basic support |\n| `list-style-type` | Good support |\n\n## Configuration Options\n\nThe `htmlToPdfmake` function accepts an options object as its second parameter:\n\n```javascript\nconst options = {\n  defaultStyles: {\n    // Override default element styles that are defined below\n    b: {bold:true},\n    strong: {bold:true},\n    u: {decoration:'underline'},\n    del: {decoration:'lineThrough'},\n    s: {decoration: 'lineThrough'},\n    em: {italics:true},\n    i: {italics:true},\n    h1: {fontSize:24, bold:true, marginBottom:5},\n    h2: {fontSize:22, bold:true, marginBottom:5},\n    h3: {fontSize:20, bold:true, marginBottom:5},\n    h4: {fontSize:18, bold:true, marginBottom:5},\n    h5: {fontSize:16, bold:true, marginBottom:5},\n    h6: {fontSize:14, bold:true, marginBottom:5},\n    a: {color:'blue', decoration:'underline'},\n    strike: {decoration: 'lineThrough'},\n    p: {margin:[0, 5, 0, 10]},\n    ul: {marginBottom:5,marginLeft:5},\n    table: {marginBottom:5},\n    th: {bold:true, fillColor:'#EEEEEE'}\n  },\n  tableAutoSize: false,  // Enable automatic table sizing\n  imagesByReference: false,  // Handle images by reference\n  removeExtraBlanks: false,  // Remove extra whitespace\n  removeTagClasses: false,  // Keep HTML tag classes\n  window: window,  // Required for Node.js usage\n  ignoreStyles: [],  // Style properties to ignore\n  fontSizes: [10, 14, 16, 18, 20, 24, 28], // Font sizes for legacy \u003cfont\u003e tag\n  customTag: function(params) { /* Custom tag handler */ }\n};\n\nconst converted = htmlToPdfmake(html, options);\n```\n\n### Options Explained\n\n#### defaultStyles\n\nObject to override the default element styling. Useful for consistent document appearance:\n\n```javascript\nconst options = {\n  defaultStyles: {\n    h1: { fontSize: 24, bold: true, marginBottom: 10 },\n    p: { margin: [0, 5, 0, 10] },\n    a: { color: 'purple', decoration: null }\n  }\n};\n```\n\n#### tableAutoSize\n\nBoolean that enables automatic table sizing based on content and CSS properties\n\nExample:\n```html\nconst result = htmlToPdfmake(`\u003ctable\u003e\n  \u003ctr style=\"height:100px\"\u003e\n    \u003ctd style=\"width:250px\"\u003eheight:100px / width:250px\u003c/td\u003e\n    \u003ctd\u003eheight:100px / width:'auto'\u003c/td\u003e\n  \u003c/tr\u003e\n  \u003ctr\u003e\n    \u003ctd style=\"width:100px\"\u003eHere it will use 250px for the width because we have to use the largest col's width\u003c/td\u003e\n    \u003ctd style=\"height:200px\"\u003eheight:200px / width:'auto'\u003c/td\u003e\n  \u003c/tr\u003e\n\u003c/table\u003e`, { tableAutoSize:true });\n```\n\n#### imagesByReference\n\n*For Web browser only, not for Node*\n\nBoolean that enables the images handling by reference instead of embedding. It will automatically load your images in your PDF using the [`{images}` option of PDFMake](https://pdfmake.github.io/docs/document-definition-object/images/).\n\nUsing this option will change the output that will return an object with `{content, images}`.\n\n```javascript\nconst html = `\u003cimg src=\"https://picsum.photos/seed/picsum/200\"\u003e`;\nconst result = htmlToPdfmake(html, { imagesByReference:true });\n// 'result' contains:\n//  {\n//    \"content\":[\n//      [\n//        {\n//          \"nodeName\":\"IMG\",\n//          \"image\":\"img_ref_0\",\n//          \"style\":[\"html-img\"]\n//        }\n//      ]\n//    ],\n//    \"images\":{\n//      \"img_ref_0\":\"https://picsum.photos/seed/picsum/200\"\n//    }\n//  }\n\npdfMake.createPdf(result).download();\n```\n\n#### customTag\n\nFunction to handle custom HTML tags or modify existing tag behavior:\n\n```javascript\nconst options = {\n  customTag: function({ element, ret, parents }) {\n    if (element.nodeName === 'CUSTOM-TAG') {\n      // Handle custom tag\n      ret.text = 'Custom content';\n      ret.style = ['custom-style'];\n    }\n    return ret;\n  }\n};\n```\n\nExample with a QR code generator:\n\n```javascript\nconst html = htmlToPdfMake(`\u003ccode typecode=\"QR\" style=\"foreground:black;background:yellow;fit:300px\"\u003etexto in code\u003c/code\u003e`, {\n  customTag:function(params) {\n    let ret = params.ret;\n    let element = params.element;\n    let parents = params.parents;\n    switch(ret.nodeName) {\n      case \"CODE\": {\n        ret = this.applyStyle({ret:ret, parents:parents.concat([element])});\n        ret.qr = ret.text[0].text;\n        switch(element.getAttribute(\"typecode\")){\n          case 'QR':\n            delete ret.text;\n            ret.nodeName='QR';\n            if(!ret.style || !Array.isArray(ret.style)){\n              ret.style = [];\n            }\n            ret.style.push('html-qr');\n            break;\n        }\n        break;\n      }\n    }\n    return ret;\n  }\n});\n```\n\n#### removeExtraBlanks\n\nBoolean that will remove extra unwanted blank spaces from the PDF.\n\nIn [some cases](https://github.com/Aymkdn/html-to-pdfmake/issues/145) these blank spaces could appear. Using this option could be quite resource consuming.\n\n#### showHidden\n\nBoolean to display the hidden elements (`display:none`) in the PDF.\n\n#### removeTagClasses\n\nBoolean that permits to remove the `html-TAG` classes added for each node.\n\n#### ignoreStyles\n\nArray of string to define a list of style properties that should not be parsed.\n\nFor example, to ignore `font-family`:\n```javascript\nhtmlToPdfmake(\"[the html code here]\", { ignoreStyles:['font-family'] })\n```\n\n#### fontSizes\n\nArray of 7 integers to overwrite the default sizes for the old HTML4 tag `\u003cfont\u003e`.\n  \n#### replaceText\n\nFunction with two parameters (`text` and `nodes`) to modify the text of all the nodes in your HTML document.\n\nExample:\n```javascript\nconst result = htmlToPdfmake(`\u003cp style='text-align: justify;'\u003eLorem Ipsum is simply d-ummy text of th-e printing and typese-tting industry. Lorem Ipsum has b-een the industry's standard dummy text ever since the 1500s\u003c/p\u003e`, {\n  replaceText:function(text, nodes) {\n    // 'nodes' contains all the parent nodes for the text\n    return text.replace(/-/g, \"\\\\u2011\"); // it will replace any occurrence of '-' with '\\\\u2011' in \"Lorem Ipsum is simply d-ummy text […] dummy text ever since the 1500s\"\n  }\n});\n```\n\n## Advanced Features\n\n### Custom Styling with data-pdfmake\n\nApply PDFMake-specific properties using the `data-pdfmake` attribute:\n\n```html\n\u003c!-- Custom table properties --\u003e\n\u003ctable data-pdfmake='{\"widths\": [100, \"*\", \"auto\"], \"heights\": 40}'\u003e\n  \u003ctr\u003e\n    \u003ctd\u003eFixed Width\u003c/td\u003e\n    \u003ctd\u003eFill Space\u003c/td\u003e\n    \u003ctd\u003eAuto Width\u003c/td\u003e\n  \u003c/tr\u003e\n\u003c/table\u003e\n\n\u003c!-- Custom HR styling --\u003e\n\u003chr data-pdfmake='{\"color\": \"red\", \"thickness\": 2}'\u003e\n```\n\n### Page Breaks\n\nControl page breaks using CSS classes and PDFMake's [`pageBreakBefore`](https://pdfmake.github.io/docs/document-definition-object/page/):\n\n```javascript\nconst html = `\n  \u003cdiv\u003e\n    \u003ch1\u003eFirst Page\u003c/h1\u003e\n    \u003ch1 class=\"page-break\"\u003eSecond Page\u003c/h1\u003e\n  \u003c/div\u003e\n`;\n\nconst docDefinition = {\n  content: htmlToPdfmake(html),\n  pageBreakBefore: function(node) {\n    return node.style \u0026\u0026 node.style.includes('page-break');\n  }\n};\n```\n\n### Image Handling\n\nSupport for various image formats and references:\n\n```html\n\u003c!-- Best option: Base64 encoded image --\u003e\n\u003c!-- Required for Node environment --\u003e\n\u003cimg src=\"data:image/jpeg;base64,/9j/4AAQ...\"\u003e\n\n\u003c!-- Image by URL (with imagesByReference option) --\u003e\n\u003c!-- Only works with Web Browser --\u003e\n\u003cimg src=\"https://example.com/image.jpg\"\u003e\n\n\u003c!-- Image with custom headers --\u003e\n\u003cimg data-src='{\"url\": \"https://example.com/image.jpg\", \"headers\": {\"Authorization\": \"Bearer token\"}}'\u003e\n```\n\nFor Base64 encoded image, please refer to the [PDFMake documentation](https://pdfmake.github.io/docs/document-definition-object/images/) and [here](https://github.com/Aymkdn/html-to-pdfmake/issues/109#issue-932953144). And you can check [this Stackoverflow question](https://stackoverflow.com/questions/934012/get-image-data-in-javascript/42916772#42916772) to know the different ways to get a base64 encoded content from an image.\n\n## Common Use Cases\n\n### Tables with Complex Layouts\n\n```html\n\u003ctable\u003e\n  \u003cthead\u003e\n    \u003ctr\u003e\n      \u003cth colspan=\"2\"\u003eHeader\u003c/th\u003e\n    \u003c/tr\u003e\n  \u003c/thead\u003e\n  \u003ctbody\u003e\n    \u003ctr\u003e\n      \u003ctd rowspan=\"2\"\u003eCell 1\u003c/td\u003e\n      \u003ctd\u003eCell 2\u003c/td\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n      \u003ctd\u003eCell 3\u003c/td\u003e\n    \u003c/tr\u003e\n  \u003c/tbody\u003e\n\u003c/table\u003e\n```\n\n### Styled Lists\n\n```html\n\u003cul style=\"margin-left: 20px\"\u003e\n  \u003cli\u003eFirst item\u003c/li\u003e\n  \u003cli style=\"color: red\"\u003eSecond item\u003c/li\u003e\n  \u003cli\u003e\n    Nested list:\n    \u003col style=\"list-style-type: lower-alpha\"\u003e\n      \u003cli\u003eSub-item a\u003c/li\u003e\n      \u003cli\u003eSub-item b\u003c/li\u003e\n    \u003c/ol\u003e\n  \u003c/li\u003e\n\u003c/ul\u003e\n```\n\n### Links and Anchors\n\n```html\n\u003c!-- External link --\u003e\n\u003ca href=\"https://example.com\"\u003eVisit Website\u003c/a\u003e\n\n\u003c!-- Internal link --\u003e\n\u003ca href=\"#section1\"\u003eJump to Section\u003c/a\u003e\n\u003ch2 id=\"section1\"\u003eSection 1\u003c/h2\u003e\n```\n\n### Columns\n\nPDFMake has a concept of [`columns`](https://pdfmake.github.io/docs/0.1/document-definition-object/columns/). We use `\u003cdiv data-pdfmake-type=\"columns\"\u003e\u003c/div\u003e` to identify it.\n  \nExample to center a table in the page:\n```html\n\u003cdiv data-pdfmake-type=\"columns\"\u003e\n  \u003cdiv data-pdfmake='{\"width\":\"*\"}'\u003e\u003c/div\u003e\n  \u003cdiv style=\"width:auto\"\u003e\n    \u003ctable\u003e\u003ctr\u003e\u003cth\u003eTable\u003c/th\u003e\u003ctr\u003e\u003ctr\u003e\u003ctd\u003eCentered\u003c/td\u003e\u003c/tr\u003e\u003c/table\u003e\n  \u003c/div\u003e\n  \u003cdiv data-pdfmake='{\"width\":\"*\"}'\u003e\u003c/div\u003e\n\u003c/div\u003e\n```\n\n## Examples\n\nYou can find more examples in [example.js](example.js) which will create [example.pdf](example.pdf):\n\n```bash\nnpm install\nnode example.js\n```\n\n## Donate\n\nYou can support my work by [making a donation](https://www.paypal.me/aymkdn), or by visiting my [Github Sponsors page](https://github.com/sponsors/Aymkdn). Thank you!\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faymkdn%2Fhtml-to-pdfmake","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faymkdn%2Fhtml-to-pdfmake","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faymkdn%2Fhtml-to-pdfmake/lists"}