Package: mkdocs-with-pdf
PDF Generate Plugin for MkDocsThis plugin will generate a single PDF file from your MkDocs repository.
This plugin is inspired byMkDocs PDF Export Plugin.FeaturesCover and Table of Contents integrated in the PDFAutomatically numbers on heading(h1-h3).Shift down sub-page headings level.usingWeasyPrint.SamplesPDF of'MkDocs' docsPDF of'Material for MkDocs' docsRequirementsThis package requires MkDocs version 1.0 or higher (0.17 works as well)Python 3.6 or higherWeasyPrint depends on cairo, Pango and GDK-PixBuf which need to be installed separately. Please follow the installation instructions for your platform carefully:LinuxMacOSWindowsHow to useInstallationInstall the package with pip:pipinstallmkdocs-with-pdfEnable the plugin in yourmkdocs.yml:plugins:-with-pdfMore information about plugins in theMkDocs documentation.TestingWhen building your repository withmkdocs build, you should now see the following message at the end of your build output:Converting 10 articles to PDF took 7.1sConfigurationYou may customize the plugin by passing options inmkdocs.yml:plugins:-with-pdf:#author: WHO#copyright: ANY TEXT##cover: false#back_cover: true#cover_title: TITLE TEXT#cover_subtitle: SUBTITLE TEXT#custom_template_path: TEMPLATES PATH##toc_title: TOC TITLE TEXT#heading_shift: false#toc_level: 3#ordered_chapter_level: 2#excludes_children:#    - 'release-notes/:upgrading'#    - 'release-notes/:changelog'##exclude_pages:#    - 'bugs/'#    - 'appendix/contribute/'#convert_iframe:#    - src: IFRAME SRC#      img: POSTER IMAGE URL#      text: ALTERNATE TEXT#    - src: ...#two_columns_level: 3##render_js: true#headless_chrome_path: headless-chromium##output_path: any-place/document.pdf#enabled_if_env: ENABLE_PDF_EXPORT##debug_html: true#show_anchors: true#verbose: trueOptionsfor PropertiesauthorSet the author text.default: usesite_authorin your projectmkdocs.ymlcopyrightSet the author text.default: usecopyrightin your projectmkdocs.ymlauthorandcopyrightvalues are drawn in Cover, and you can use '@page' content.@page{@bottom-left{content:string(author)!important;}@bottom-right{content:string(copyright)!important;}}for CovercoverSet the value tofalseif you don't need a cover page.default:trueback_coverSet the value totrueif you need a back cover page.default:falsesince:v0.8.0You would be better to install theqrcodepackage:pipinstallqrcodecover_titleSet the title text in cover page.default: usesite_namein your projectmkdocs.ymlcover_subtitleSet the subtitle text in cover page.default:Nonecover_logoSet the logo image in cover page. This value is URL or simply specify the relative path to the docs directory.default:Nonesince:v0.8.0for Heading and TOCtoc_titleSet the title text ofTable of Content.default:Table of Contentsince:v0.4.0heading_shiftSet this value tofalse, disable shift heading in child page.default:trueIn this flags enable, heading move down one level in child page.toc_levelSet the level ofTable of Content. This value is enabled in the range of from1to3.default:3ordered_chapter_levelSet the level of heading number addition. This value is enabled in the range of from1to3.default:3excludes_childrenSet the pageidofnavurl. If theidmatches in this list, it will be excluded from the heading number addition and table of contents.default:[]for Pageexclude_pagesSet the pageidofnavurl. If theidmatches in this list, it will be excluded page contents.default:[]since:v0.3.0convert_iframeList ofiframetoaconversions. Everyiframethat matches asrcin this list will be replace toacontains eachimgand/ortext. it's using for such as embedded VIDEO.default:[]since:v0.6.0@seeSample ofMkDocs Materialtwo_columns_level(Experimental)Set the heading level ofTwo Column Layout. Currently only0(disable) or3is valid for this value. So slow processing, but a little nice.default:0since:v0.7.0@seeSample ofMkDocs MaterialRenderer for JavaScriptrender_jsSet the value totrueif you're using 'MathJax', 'Twemoji' or any more.Require "Chrome" which has "headless" mode.default:falsesince:v0.7.0headless_chrome_pathSet the "Headless Chrome" program path.Ifrender_jsisfalse, this value will be ignored.default:chromium-browserCheck on your system:$ <PROGRAM_PATH> --headless \
   --disable-gpu \
   --dump-dom \
   <ANY_SITE_URL(eg. 'https://google.com')>... and moreoutput_pathThis option allows you to use a different destination for the PDF file.default:pdf/document.pdfcustom_template_pathThe path where your customcover.htmland/orstyles.scssare located.default:templatessince:v0.8.0enabled_if_envSetting this option will enable the build only if there is an environment variable set to 1. This is useful to disable building the PDF files during development, since it can take a long time to export all files.default:NonePDF generation can take significantly longer than HTML generation which can slow down mkdocs's built-in dev-server.Addingenabled_if_env: ENABLE_PDF_EXPORTunder- with-pdf:disables PDF generation during development.  Run the dev-server normally:$mkdocsserve
INFO-BrowserConnected:http://127.0.0.1:8000/
INFO-Runningtask:builder(delay:None)INFO-Buildingdocumentation...
WARNING-withoutgeneratePDF(setenvironmentvariableENABLE_PDF_EXPORTto1toenable)...2secondslater...
INFO-Reload1waiters:/.../index.mdand to build files to deploy specifyENABLE_PDF_EXPORT=1at the command line:$ENABLE_PDF_EXPORT=1mkdocsbuild
...
INFO-Converting10articlestoPDFtook7.1s
INFO-Documentationbuiltin8.29secondsdebug_htmlSetting this totruewill out HTML tostdouton build time.default:falseYou can try this:mkdocsbuild>for_pdf_print.html...and browse output with Google Chrome.Chrome DevTools Into Print Preview Modewill you help.Note: WeasyPrint and Google Chrome are not fully compatible.show_anchorsSetting this totruewill list out of anchor points provided during the build as info message.default:falsesince:v0.7.4verboseSetting this totruewill show all WeasyPrint debug messages during the build.default:falseCustom cover page and document styleIt is possible to create a custom cover page for the document.
You can also add a custom style sheet to modify the whole document.To do so, add atemplatesfolder at the root level of yourmkdocsproject and place acover.htmland/or astyles.scssinside.
Alternatively, you can specify a different location with thecustom_template_pathoption.Custom cover pageUsingjinja2syntax, you can access all data from yourmkdocs.yml.
To make template creation easier, you can useplugin_some_pluginto access variables from plugins.
E.g. use{{ author }}to get the author from yourmkdocs.ymlthat looks like:plugins:-with-pdf:author:WHOYou can use custom variablesextra:in yourmkdocs.ymlAnd, you can check it in the log if run withverboseordebug_htmloptions.Custom stylesheetSince your stylesheet is appended to the default ones, you can override every setting from them.Tip: setting thedebug_htmloption totrueto get the generated html that is passed toweasyprintcan help you determine the html tags, classes or identifiers you want to modify in your stylesheet.Advanced Rendering Hooks (Experimental)You can hook the PDF rendering process by creating apdf_event_hook.py(orpdf_event_hook/__init__.py) in your working directory(usually the same directory asmkdocs.yml).since:v0.8.2Samplepdf_event_hook.py(orpdf_event_hook/__init__.py)importloggingfrombs4importBeautifulSoupfrommkdocs.structure.pagesimportPagedefinject_link(html:str,href:str,page:Page,logger:logging)->str:"""Adding PDF View button on navigation bar(using material theme)"""def_pdf_icon():_ICON='''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M128,0c-17.6,0-32,14.4-32,32v448c0,17.6,14.4,32,32,32h320c17.6,0,32-14.4,32-32V128L352,0H128z" fill="#E2E5E7"/><path d="m384 128h96l-128-128v96c0 17.6 14.4 32 32 32z" fill="#B0B7BD"/><polygon points="480 224 384 128 480 128" fill="#CAD1D8"/><path d="M416,416c0,8.8-7.2,16-16,16H48c-8.8,0-16-7.2-16-16V256c0-8.8,7.2-16,16-16h352c8.8,0,16,7.2,16,16  V416z" fill="#F15642"/><g fill="#fff"><path d="m101.74 303.15c0-4.224 3.328-8.832 8.688-8.832h29.552c16.64 0 31.616 11.136 31.616 32.48 0 20.224-14.976 31.488-31.616 31.488h-21.36v16.896c0 5.632-3.584 8.816-8.192 8.816-4.224 0-8.688-3.184-8.688-8.816v-72.032zm16.88 7.28v31.872h21.36c8.576 0 15.36-7.568 15.36-15.504 0-8.944-6.784-16.368-15.36-16.368h-21.36z"/><path d="m196.66 384c-4.224 0-8.832-2.304-8.832-7.92v-72.672c0-4.592 4.608-7.936 8.832-7.936h29.296c58.464 0 57.184 88.528 1.152 88.528h-30.448zm8.064-72.912v57.312h21.232c34.544 0 36.08-57.312 0-57.312h-21.232z"/><path d="m303.87 312.11v20.336h32.624c4.608 0 9.216 4.608 9.216 9.072 0 4.224-4.608 7.68-9.216 7.68h-32.624v26.864c0 4.48-3.184 7.92-7.664 7.92-5.632 0-9.072-3.44-9.072-7.92v-72.672c0-4.592 3.456-7.936 9.072-7.936h44.912c5.632 0 8.96 3.344 8.96 7.936 0 4.096-3.328 8.704-8.96 8.704h-37.248v0.016z"/></g><path d="m400 432h-304v16h304c8.8 0 16-7.2 16-16v-16c0 8.8-7.2 16-16 16z" fill="#CAD1D8"/></svg>'''# noqa: E501returnBeautifulSoup(_ICON,'html.parser')logger.info(f'(hook on inject_link:{page.title})')soup=BeautifulSoup(html,'html.parser')nav=soup.find(class_='md-header-nav')ifnotnav:# after 7.xnav=soup.find('nav',class_='md-header__inner')ifnav:a=soup.new_tag('a',href=href,title='PDF',**{'class':'md-header__button md-header-nav__button md-icon'})a.append(_pdf_icon())nav.append(a)returnstr(soup)returnhtml# def pre_js_render(soup: BeautifulSoup, logger: logging) -> BeautifulSoup:#     logger.info('(hook on pre_js_render)')#     return soup# def pre_pdf_render(soup: BeautifulSoup, logger: logging) -> BeautifulSoup:#     logger.info('(hook on pre_pdf_render)')#     tag = soup.find(lambda tag: tag.name ==#                     'body' and 'data-md-color-scheme' in tag.attrs)#     if tag:#         tag['data-md-color-scheme'] = 'print'#     return soup... and check log:$mkdocsbuild
INFO-FoundPDFrenderingeventhookmodule.
INFO-Cleaningsitedirectory
INFO-Buildingdocumentationtodirectory:/tmp/sample/site
INFO-(hookoninject_link:Home)...ContributingFrom reporting a bug to submitting a pull request: every contribution is appreciated and welcome. Report bugs, ask questions and request features usingGithub issues.
If you want to contribute to the code of this project, please read theContribution Guidelines.Special thanks toTerry Zhaothe author of theMkDocs PDF Export Pluginthe source of our inspiration. We've used some of his code in this project.