render.py 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: MIT
  3. """
  4. A Python script to generate a single PDF document with all the `tldr` pages. It works by generating
  5. intermediate HTML files from existing md files using Python-markdown, applying desired formatting
  6. through CSS, and finally rendering them as PDF. There is no LaTeX dependency for generating the PDF.
  7. """
  8. import os
  9. import sys
  10. import glob
  11. import markdown
  12. import argparse
  13. from datetime import datetime
  14. from weasyprint import HTML
  15. def main(loc, colorscheme):
  16. # Checking correctness of path
  17. if not os.path.isdir(loc):
  18. print("Invalid directory. Please try again!", file=sys.stderr)
  19. sys.exit(1)
  20. # Set up css style sheets
  21. csslist = ["basic.css"]
  22. if colorscheme != "basic":
  23. csslist.append(f"{colorscheme}.css")
  24. # A string that stores all pages in HTML format
  25. html = (
  26. '<!doctype html><html><head><meta charset="utf-8"></head>'
  27. + "<body><h1 class=title-main>tldr pages</h1>"
  28. + "<div class=title-sub>Simplified and community-driven man pages</div>"
  29. + "<div class=title-sub><em><small>Generated on "
  30. + datetime.now().strftime("%c")
  31. + "</small></em></div>"
  32. + '<p style="page-break-before: always" ></p>'
  33. )
  34. # Writing names of all directories inside 'pages' to a list
  35. for operating_sys in sorted(os.listdir(loc)):
  36. # Required string to create directory title pages
  37. html += (
  38. "<h1 class=title-dir>"
  39. + operating_sys.capitalize()
  40. + "</h1>"
  41. + '<p style="page-break-before: always" ></p>'
  42. )
  43. # Conversion of Markdown to HTML string
  44. for page_number, md in enumerate(
  45. sorted(glob.glob(os.path.join(loc, operating_sys, "*.md"))), start=1
  46. ):
  47. with open(md, "r") as inp:
  48. text = inp.readlines()
  49. # modify our page to have an H2 header, so that it is grouped under
  50. # the H1 header for the directory
  51. text[0] = "<h2 class='title-page'>" + text[0][2:] + "</h2>"
  52. for line in text:
  53. if line.startswith(">"):
  54. line = "####" + line[1:]
  55. html += markdown.markdown(line)
  56. html += '<p style="page-break-before: always" ></p>'
  57. print(f"Rendered page {page_number} of the directory {operating_sys}")
  58. html += "</body></html>"
  59. # Writing the PDF to disk
  60. print("\nConverting all pages to PDF...")
  61. HTML(string=html).write_pdf("tldr-pages.pdf", stylesheets=csslist)
  62. if os.path.exists("tldr-pages.pdf"):
  63. print("\nCreated tldr-pages.pdf in the current directory!\n")
  64. if __name__ == "__main__":
  65. # Parsing the arguments
  66. parser = argparse.ArgumentParser(
  67. prog="tldr-pages-to-pdf",
  68. description="A Python script to generate a single PDF document with all the `tldr` pages.",
  69. )
  70. parser.add_argument("dir_path", help="Path to the 'pages' directory")
  71. parser.add_argument(
  72. "-c",
  73. "--color",
  74. choices=["solarized-light", "solarized-dark", "basic"],
  75. default="basic",
  76. help="Color scheme of the PDF",
  77. )
  78. args = parser.parse_args()
  79. main(args.dir_path, args.color)