render.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  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 re
  12. import markdown
  13. import argparse
  14. from datetime import datetime
  15. from weasyprint import HTML
  16. def main(loc, colorscheme):
  17. oslist = []
  18. allmd = []
  19. group = []
  20. ap = []
  21. # Checking correctness of path
  22. if not os.path.isdir(loc):
  23. print("Invalid directory. Please try again!", file=sys.stderr)
  24. sys.exit(1)
  25. # Writing names of all directories inside 'pages' to a list
  26. for os_dir in os.listdir(loc):
  27. oslist.append(os_dir)
  28. oslist.sort()
  29. # Required strings to create intermediate HTML files
  30. header = '<!doctype html><html><head><meta charset="utf-8"><link rel="stylesheet" href="basic.css">'
  31. if colorscheme != "basic":
  32. header += '<link rel="stylesheet" href="' + colorscheme + '.css"></head><body>\n'
  33. header += "</head><body>\n"
  34. footer = "</body></html>"
  35. title_content = "<h1 class=title-main>tldr pages</h1>" \
  36. + "<h4 class=title-sub>Simplified and community-driven man pages</h4>" \
  37. + "<h6 class=title-sub><em><small>Generated on " + datetime.now().strftime("%c") + "</small></em></h6>" \
  38. + "</body></html>"
  39. # Creating title page
  40. with open("title.html", "w") as f:
  41. f.write(header + title_content)
  42. group.append(HTML("title.html").render())
  43. for operating_sys in oslist:
  44. # Required string to create directory title pages
  45. dir_title = "<h2 class=title-dir>" + \
  46. operating_sys.capitalize() + "</h2></body></html>"
  47. # Creating directory title page for current directory
  48. with open("dir_title.html", "w") as os_html:
  49. os_html.write(header + dir_title)
  50. group.append(HTML("dir_title.html").render())
  51. # Creating a list of all md files in the current directory
  52. for temp in glob.glob(os.path.join(loc, operating_sys, "*.md")):
  53. allmd.append(temp)
  54. # Sorting all filenames in the directory, to maintain the order of the PDF
  55. allmd.sort()
  56. # Conversion of Markdown to HTML
  57. for page_number, md in enumerate(allmd, start=1):
  58. with open(md, "r") as inp:
  59. text = inp.readlines()
  60. with open("htmlout.html", "w") as out:
  61. out.write(header)
  62. for line in text:
  63. if re.match(r'^>', line):
  64. line = line[:0] + '####' + line[1:]
  65. html = markdown.markdown(line)
  66. out.write(html)
  67. out.write(footer)
  68. group.append(HTML("htmlout.html").render())
  69. print("Rendered page {} of the directory {}".format(
  70. str(page_number), operating_sys))
  71. allmd.clear()
  72. # Merging all the documents into a single PDF
  73. for doc in group:
  74. for p in doc.pages:
  75. ap.append(p)
  76. # Writing the PDF to disk, preserving metadata of first `tldr` page
  77. group[2].copy(ap).write_pdf('tldr-pages.pdf')
  78. if os.path.exists("tldr-pages.pdf"):
  79. print("\nCreated tldr-pages.pdf in the current directory!\n")
  80. # Removing unnecessary intermediate files
  81. try:
  82. os.remove("htmlout.html")
  83. os.remove("title.html")
  84. os.remove("dir_title.html")
  85. except OSError:
  86. print("Error removing temporary file(s)")
  87. if __name__ == "__main__":
  88. # Parsing the arguments
  89. parser = argparse.ArgumentParser(prog="tldr-pages-to-pdf", description="A Python script to generate a single PDF document with all the `tldr` pages.")
  90. parser.add_argument("dir_path", help = "Path to the 'pages' directory")
  91. parser.add_argument("-c", "--color", choices=["solarized-light", "solarized-dark", "basic"], default="basic", help="Color scheme of the PDF")
  92. args = parser.parse_args()
  93. main(args.dir_path, args.color)