Lesson 1, Topic 1
In Progress

5.1 Formatting A DOCX file using python-docx library

python-docx ‘is a Python library for creating and manipulating Microsoft Word (.docx) files. It provides a simple and intuitive API for generating documents, making it a valuable tool for tasks like report generation, document automation, and content extraction. With ‘python-docx‘, users can easily add paragraphstablesimages, and formatting to their documents. It also allows for the extraction of content from existing Word documents, enabling a wide range of document processing applications. This library is widely used in data science, automation, and business applications where programmatic document creation and manipulation are required.
https://python-docx.readthedocs.io/en/latest/genindex.html

Let’s start with the formatting:

def resume_formatter(content, filename, th):

  Heading_fonts, Heading_size, Text_fonts, Text_size, maxlength, api_key = config_extractor()
  # General formatter for heading
  def add_formatted_paragraph(doc, text, bold = False, color = None, alignment = None, under_line = None, Type = 'Default'):
    if Type == 'Heading':
      fontsize = Heading_size
      fontstyle = Heading_fonts
    elif Type == 'Text':
      fontsize = Text_size
      fontstyle = Text_fonts
    elif Type == 'Default':
      fontsize = 16
      fontstyle = 'Calibri'
    paragraph = doc.add_paragraph()
    run = paragraph.add_run(text)
    if bold:
        run.bold = True
    if color:
        run.font.color.rgb = RGBColor(*color)
    if alignment:
        paragraph.alignment = alignment
    if fontsize:
        run.font.size = Pt(fontsize)
    if fontstyle:
        run.font.name = fontstyle
    if under_line:
        run.font.underline = under_line
    return paragraph

Let’s look at the explaination of the above snippet:

  1. def resume_formatter(content, filename, dictionary):
    • This line defines a function named resume_formatter that takes three arguments: contentfilename, and dictionary.
  2. Heading_fonts, Heading_size, Text_fonts, Text_size, maxlength = config_extractor()
    • This line calls a function config_extractor() to retrieve values for heading fonts, heading size, text fonts, text size, and maximum length. These values are then assigned to the respective variables.
  3. def add_formatted_paragraph(doc, text, bold=False, color=None, alignment=None, under_line=None, Type='Default'):
    • Within the resume_formatter function, there is an inner function named add_formatted_paragraph. This function is used to create formatted paragraphs in the document.
    • It takes several optional parameters like boldcoloralignmentunder_line, and Type to customize the appearance of the paragraph.
  4. Inside the add_formatted_paragraph function:
    • It first determines the fontsize and fontstyle based on the value of the Type parameter.
    • It then creates a new paragraph in the document.
    • It adds a run (a sequence of characters with the same style) containing the specified text.
    • If bold is True, it sets the text to be bold.
    • If color is provided, it sets the font color.
    • If alignment is provided, it sets the paragraph alignment.
    • If fontsize is provided, it sets the font size.
    • If fontstyle is provided, it sets the font style (e.g., ‘Calibri’).
    • If under_line is provided, it underlines the text.
    • Finally, it returns the formatted paragraph.

This code snippet is a part of a main program for generating formatted documents, possibly using the Python library ‘python-docx’ for working with Microsoft Word files. The resume_formatter function is responsible for adding formatted paragraphs to the document based on the provided parameters.

def add_margin_to_page(doc, leftmargin = 1.0, topmargin = 0.3, rightmargin = 1.0, bottommargin = 0.3):
    for section in doc.sections:
      section.left_margin = Inches(leftmargin)
      section.top_margin = Inches(topmargin)
      section.right_margin = Inches(rightmargin)
      section.bottom_margin = Inches(bottommargin)
  # line generator
  def generate_line_separator(document, color):
    paragraph = document.add_paragraph()
    run = paragraph.add_run()
    run.bold = True
    run.font.name = 'Roboto'
    run.font.color.rgb = RGBColor(*color)
    run.font.size = Pt(10)
    run.text = '_' * 93
    return paragraph

  # image setter
  def add_image_to_header(doc):
    image_path = 'give your image path'
    section = doc.sections[0]
    section.left_margin = Inches(1)
    head = section.header
    p = head.paragraphs[0]

    p.add_run().add_picture(image_path, width = Inches(1), height = Inches(1))
    p.alignment = 1
    p.paragraph_format.space_after = Inches(0.2)
    return p
  1. add_margin_to_page:
    This function takes a doc object (which is assumed to be a document opened using the docx library) along with optional arguments for left, top, right, and bottom margins. It iterates through the sections of the document and adjusts the margins according to the provided values.For example, calling add_margin_to_page(my_doc, leftmargin=1.5, topmargin=0.5) would set the left margin to 1.5 inches, the top margin to 0.5 inches, and leave the other margins at their default values.
  2. generate_line_separator:
    This function creates a line separator (a series of underscores) with a specified color. It adds this separator to the document and returns the paragraph containing it. The color is specified as an RGB tuple.For example, calling generate_line_separator(my_document, (102,142,70)) would create a red line separator.
  3. add_image_to_header:
    This function adds an image to the header of the document. It assumes that the doc object has sections, and it fetches the first section to work with. It then sets the left margin of the section to 1 inch.The function expects an image file path (image_path) and adds it to the header with a specified width and height (8.5 inches by 0.3 inches in this case).The alignment of the paragraph is set to left-aligned (0), and some space is added after the paragraph.The function returns the paragraph containing the added image.

Overall, these functions provide a way to format and customize a document, including adjusting margins, adding line separators, and incorporating images into the document’s header. The code assumes that a doc object is being used, likely from the python-docx library.

# create empty document
  doc = docx.Document()

  add_image_to_header(doc)

  # Add margin to the page
  add_margin_to_page(doc, leftmargin = 1.0, topmargin = 0.3, rightmargin = 1.0, bottommargin = 0.3)

  # Step 0.0: Print the name
  name = th['name']
  if not name:
    add_formatted_paragraph(doc, '', bold = True, color = (67, 67, 67), alignment = WD_PARAGRAPH_ALIGNMENT.CENTER, Type = 'Text')
  else:
    add_formatted_paragraph(doc, name, bold = True, color = (102,142,70), alignment = WD_PARAGRAPH_ALIGNMENT.CENTER)

  # Step 0.1: Generating the line seperator
  line = generate_line_separator(doc, (102,142,70))
  line.paragraph_format.space_before = Inches(0.015)
  line.paragraph_format.space_after = Inches(0.3)
  1. doc = docx.Document()This line initializes an empty Word document using the Document class from the python-docx library. doc is now an empty document that you can add content to.
  2. add_margin_to_page(doc, leftmargin=1.0, topmargin=0.3, rightmargin=1.0, bottommargin=0.3): This line calls a function called add_margin_to_page and passes the doc object along with specific margin values. This function is likely designed to add margins to the Word document’s pages.
  3. name = th['name']It appears that th is some data source (possibly a dictionary or object), and this line is attempting to retrieve a value associated with the key ‘name’ and assigns it to the variable name.
  4. The next part of the code is conditional based on whether name has a value or not:
    • If name is empty or evaluates to False (if not name), it calls the add_formatted_paragraph function to add an empty paragraph with specific formatting attributes like bold, color, and alignment. The paragraph will be centered.
    • If name has a value, it calls the add_formatted_paragraph function to add a paragraph with the value of name, and it specifies formatting attributes such as bold, color, and center alignment.
  5. line = generate_line_separator(doc, (102,142,70))This line seems to call a function named generate_line_separator and assigns the result to the variable line. It appears that this function is used to create a line separator (possibly a horizontal line) within the document. The (237, 149, 0) argument likely specifies the color of the line.
  6. line.paragraph_format.space_before and line.paragraph_format.space_afterThese lines adjust the spacing before and after the line separator paragraph. space_before sets the space before the paragraph, and space_after sets the space after the paragraph. In this case, Inches(0.015) is used for spacing before and Inches(0.3) for spacing after.

The code snippet appears to be part of a larger document generation process. It initializes a Word document, sets margins, adds a name to the document (with or without formatting), generates a line separator, and adjusts spacing around the separator. To fully understand the code’s purpose, you would need to examine the definitions of the functions like add_margin_to_pageadd_formatted_paragraph, and generate_line_separator, which are not provided in this snippet.

# Step 1.0: Print the heading
  profile = th['PP']

  if not profile:
    add_formatted_paragraph(doc, '', bold = True, color = (67, 67, 67), alignment = WD_PARAGRAPH_ALIGNMENT.CENTER, Type = 'Text')
  else:
    p = add_formatted_paragraph(doc, "Professional Profile", bold = True, color = (102,142,70), alignment = WD_PARAGRAPH_ALIGNMENT.LEFT, Type = 'Heading')
    p.paragraph_format.space_before = Inches(0.015)
    p.paragraph_format.space_after = Inches(0.02)

  # Step 1.1: formatting the professional profile
  if not profile:
      add_formatted_paragraph(doc, '', bold = True, color = (67, 67, 67), alignment = WD_PARAGRAPH_ALIGNMENT.CENTER, Type = 'Text')
  else:
      professional_profile = re.sub(r'  ', ' ', profile)
      professional_profile = re.sub(r'•','', profile)
      profile = add_formatted_paragraph(doc, profile, bold = False, color = (67, 67, 67), alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY, Type = 'Text')
      profile.paragraph_format.space_before = Inches(0.015)
      profile.paragraph_format.space_after = Inches(0.3)
  1. Step 1.0 – Print the heading:
    • profile = th['PP']: This line seems to be extracting a value labeled as ‘PP'[Professional Profile] from some data structure represented by th. It’s likely that th is some kind of data container, like a dictionary or an object, and ‘PP’ is a key or attribute. The extracted value is stored in the variable profile.
    • if not profile:: This is a conditional statement checking if profile is empty or evaluates to False. If it is, it implies that there is no professional profile information available.
    • add_formatted_paragraph(...): This is likely a function call that adds a formatted paragraph to a document (doc). Depending on the condition, it either adds an empty formatted paragraph (if there’s no professional profile information) or adds a paragraph with the text “Professional Profile”. The parameters control various formatting options such as bold, color, alignment, and type.
  2. Step 1.1 – Formatting the professional profile:
    • if not profile:: Similar to the previous conditional statement, this checks if profile is empty or evaluates to False. This condition may be checking if there is any professional profile information available.
    • professional_profile = re.sub(r' ', ' ', profile): If there is professional profile information, this line seems to perform a regular expression substitution operation. It’s replacing occurrences of double spaces with single spaces in the profile text.
    • professional_profile = re.sub(r'•', '', profile): This line is performing another regular expression substitution. It appears to be removing bullet points (‘•’) from the profile.
    • profile = add_formatted_paragraph(...): This line is replacing the original profile content with the modified professional_profile. It seems to be adding a formatted paragraph to the document, likely containing the modified professional profile text.
    • profile.paragraph_format.space_before = Inches(0.015): This line sets the space before the paragraph to 0.015 inches.
    • profile.paragraph_format.space_after = Inches(0.3): This line sets the space after the paragraph to 0.3 inches.

Without additional context, it’s a bit challenging to provide a more detailed explanation or suggest improvements. If you have specific questions or need further clarification.

# Step 2.0: Formatting the Education
  edu = th['Education']
  if not edu:
      add_formatted_paragraph(doc, '', bold = True, color = (67, 67, 67), alignment = WD_PARAGRAPH_ALIGNMENT.CENTER, Type = 'Text')
  else:
    ed = add_formatted_paragraph(doc, "Education", bold = True, color = (102,142,70), alignment = WD_PARAGRAPH_ALIGNMENT.LEFT, Type = 'Heading')
    ed.paragraph_format.space_before = Inches(0.015)
    ed.paragraph_format.space_after = Inches(0.02)

  # Step 2.1: Formatting the education details
  if not edu:
    add_formatted_paragraph(doc, '', bold = True, color = (67, 67, 67), alignment = WD_PARAGRAPH_ALIGNMENT.CENTER, Type = 'Text')
  else:
    for k1, v1 in edu.items():
      key1 = add_formatted_paragraph(doc, k1, bold = True, color = (67, 67, 67), alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY, Type = 'Text')
      key1.paragraph_format.space_before = Inches(0.015)
      key1.paragraph_format.space_after = Inches(0.02)
      if isinstance(v1, list):
        for value in v1:
            paragraph = doc.add_paragraph()
            paragraph.paragraph_format.left_indent = Inches(0.5)
            run = paragraph.add_run(value)
            words = value.split()
            for i in range(len(words)):
              if i > 0 and words[i].startswith(":"):
                words[i] = words[i][:1] + words[i][1:].ljust(len(words[i-1]))
            # formating the list elements
            run.text = " ".join(words)
            style = doc.styles['Normal']
            run = style.font
            run.name = Text_fonts
            run.size = Pt(Text_size)
            run.color.rgb = RGBColor(67, 67, 67)
            paragraph.style = "ListBullet"
            paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY
            paragraph.paragraph_format.space_before = Inches(0.015)
            paragraph.paragraph_format.space_after = Inches(0.02)
      else:
        for k2, v2 in v1.items():
          key2 = add_formatted_paragraph(doc, k2, bold = False, color = (0, 0, 0), alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY, Type = 'Text')
          key2.paragraph_format.space_before = Inches(0.015)
          key2.paragraph_format.space_after = Inches(0.02)
          if isinstance(v2, list):
            for value in v2:
              paragraph = doc.add_paragraph()
              paragraph.paragraph_format.left_indent = Inches(0.5)
              run = paragraph.add_run(value)
              words = value.split()
              for i in range(len(words)):
                if i > 0 and words[i].startswith(":"):
                  words[i] = words[i][:1] + words[i][1:].ljust(len(words[i-1]))
                  words[i] = re.sub(r'\n[o]', r'\n•  ', words[i])
              # formating the list elements
              run.text = " ".join(words)
              style = doc.styles['Normal']
              run = style.font
              run.name = Text_fonts
              run.size = Pt(Text_size)
              run.color.rgb = RGBColor(67, 67, 67)
              paragraph.style = "ListBullet"
              paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY
              paragraph.paragraph_format.space_before = Inches(0.015)
              paragraph.paragraph_format.space_after = Inches(0.3)
          else:
            for k3, v3 in v2.items():
              key3 = add_formatted_paragraph(doc, k3, bold = False, color = (0, 0, 0), alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY, Type = 'Text')
              key3.paragraph_format.space_before = Inches(0.015)
              key3.paragraph_format.space_after = Inches(0.2)
              # values formatting
              for value in v3:
                paragraph = doc.add_paragraph()
                paragraph.paragraph_format.left_indent = Inches(0.5)
                run = paragraph.add_run(value)
                words = value.split()
                for i in range(len(words)):
                  if i > 0 and words[i].startswith(":"):
                    words[i] = words[i][:1] + words[i][1:].ljust(len(words[i-1]))
                # formating the list elements
                run.text = " ".join(words)
                style = doc.styles['Normal']
                run = style.font
                run.name = Text_fonts
                run.size = Pt(Text_size)
                run.color.rgb = RGBColor(67, 67, 67)
                paragraph.style = "ListBullet"
                paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY
                paragraph.paragraph_format.space_before = Inches(0.015)
                paragraph.paragraph_format.space_after = Inches(0.3)
  1. Step 2.0: Formatting the Education
    • edu = th['Education']: This line assigns the value of the ‘Education’ key from the variable th to the variable edu.
    • if not edu:: This condition checks if edu is empty or does not contain any data.
    • add_formatted_paragraph(...) is a function call for adding a formatted paragraph to the document. It is assumed to be a custom function.
    • If edu is empty, it adds an empty formatted paragraph with specific attributes like being bold, centered alignment, and black color.
  2. Step 2.1: Formatting
    • This section handles the details within the edu variable.
    • The code first checks if edu is empty and adds an empty formatted paragraph if it is.
    • If edu is not empty, it proceeds to iterate through its content using nested loops and conditions.
    • Inside the loops, the code is performing the following actions:
      • Creating paragraphs and runs to add content to the document.
      • Applying formatting such as indentation, font size, color, and style.
      • Manipulating text elements for better presentation, like adjusting line breaks and bullet points.
    • The overall structure seems to be processing education details, potentially in a hierarchical manner (k1 -> v1 -> k2 -> v2 -> k3 -> v3), where k represents keys and v represents values.
    • It’s important to note that some functions (add_formatted_paragraphInchesPtRGBColor) and variables (thText_fontsText_size) are referenced but not defined within this code snippet. These might be defined elsewhere in the script.
    • Additionally, regular expressions (re.sub) are used to perform substitutions on text elements.

Please note that to fully understand the code, additional context about the functions and variables being used, as well as the overall structure of the script, would be needed.

# Step 3.0: Print the employement History
  work_ex = th['Work Experience']
  if not work_ex:
    add_formatted_paragraph(doc, '', bold = True, color = (67, 67, 67), alignment = WD_PARAGRAPH_ALIGNMENT.CENTER, Type = 'Text')
  else:
    work_exp = add_formatted_paragraph(doc, 'Employment History', bold = True, color = (102,142,70), alignment = WD_PARAGRAPH_ALIGNMENT.LEFT, Type = 'Heading')
    work_exp.paragraph_format.space_before = Inches(0.015)
    work_exp.paragraph_format.space_after = Inches(0.02)

  # Step 3.1: Formatting the data in emloyment history
  if not work_ex:
    add_formatted_paragraph(doc, '', bold = True, color = (67, 67, 67), alignment = WD_PARAGRAPH_ALIGNMENT.CENTER, Type = 'Text')
  else:
    for k1, v1 in work_ex.items():
      key1 = add_formatted_paragraph(doc, k1, bold = True, color = (67, 67, 67), alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY, Type = 'Text')
      key1.paragraph_format.space_before = Inches(0.015)
      key1.paragraph_format.space_after = Inches(0.02)
      if isinstance(v1, list):
        for value in v1:
            paragraph = doc.add_paragraph()
            paragraph.paragraph_format.left_indent = Inches(0.5)
            run = paragraph.add_run(value)
            words = value.split()
            for i in range(len(words)):
              if i > 0 and words[i].startswith(":"):
                words[i] = words[i][:1] + words[i][1:].ljust(len(words[i-1]))
            # formating the list elements
            run.text = " ".join(words)
            style = doc.styles['Normal']
            run = style.font
            run.name = Text_fonts
            run.size = Pt(Text_size)
            run.color.rgb = RGBColor(67, 67, 67)
            paragraph.style = "ListBullet"
            paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY
            paragraph.paragraph_format.space_before = Inches(0.015)
            paragraph.paragraph_format.space_after = Inches(0.02)
      else:
        for k2, v2 in v1.items():
          key2 = add_formatted_paragraph(doc, k2, bold = False, color = (67, 67, 67), alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY, Type = 'Text')
          key2.paragraph_format.space_before = Inches(0.015)
          key2.paragraph_format.space_after = Inches(0.02)
          if isinstance(v2, list):
            for value in v2:
              paragraph = doc.add_paragraph()
              paragraph.paragraph_format.left_indent = Inches(0.5)
              run = paragraph.add_run(value)
              words = value.split()
              for i in range(len(words)):
                if i > 0 and words[i].startswith(":"):
                  words[i] = words[i][:1] + words[i][1:].ljust(len(words[i-1]))
                  words[i] = re.sub(r'\n[o]', r'\n•  ', words[i])
              # formating the list elements
              run.text = " ".join(words)
              style = doc.styles['Normal']
              run = style.font
              run.name = Text_fonts
              run.size = Pt(Text_size)
              run.color.rgb = RGBColor(67, 67, 67)
              paragraph.style = "ListBullet"
              paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY
              paragraph.paragraph_format.space_before = Inches(0.015)
              paragraph.paragraph_format.space_after = Inches(0.3)
          else:
            for k3, v3 in v2.items():
              key3 = add_formatted_paragraph(doc, k3, bold = False, color = (67, 67, 67), alignment = WD_PARAGRAPH_ALIGNMENT.LEFT, Type = 'Text')
              key3.paragraph_format.space_before = Inches(0.015)
              key3.paragraph_format.space_after = Inches(0.2)
              # values formatting
              for value in v3:
                paragraph = doc.add_paragraph()
                paragraph.paragraph_format.left_indent = Inches(0.5)
                run = paragraph.add_run(value)
                words = value.split()
                for i in range(len(words)):
                  if i > 0 and words[i].startswith(":"):
                    words[i] = words[i][:1] + words[i][1:].ljust(len(words[i-1]))
                # formating the list elements
                run.text = " ".join(words)
                style = doc.styles['Normal']
                run = style.font
                run.name = Text_fonts
                run.size = Pt(Text_size)
                run.color.rgb = RGBColor(67, 67, 67)
                paragraph.style = "ListBullet"
                paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY
                paragraph.paragraph_format.space_before = Inches(0.015)
                paragraph.paragraph_format.space_after = Inches(0.3)

Step 3.0: Print the Employment History

  1. work_ex = th['Work Experience']: This line retrieves the ‘Work Experience’ data from a dictionary th.
  2. if not work_ex:: Checks if there is any work experience data available. If not, it adds an empty paragraph with specified formatting.
  3. else:: If there is work experience data available, it proceeds to add the content.
  4. work_exp = add_formatted_paragraph(doc, 'Employment History', bold=True, color=(102,142,70), alignment=WD_PARAGRAPH_ALIGNMENT.LEFT, Type='Heading'): This line adds a formatted paragraph titled ‘Employment History’ to the Word document. The paragraph is set to be bold, colored with an RGB value of (102,142,70) which represents a shade of orange, left-aligned, and treated as a heading.
  5. work_exp.paragraph_format.space_before = Inches(0.015): Adjusts the space before the paragraph.
  6. work_exp.paragraph_format.space_after = Inches(0.02): Adjusts the space after the paragraph.

Step 3.1: Formatting the Data in Employment History

This section handles the detailed formatting of employment history data:

  1. for k1, v1 in work_ex.items(): Iterates over the items in the ‘Work Experience’.
  2. Inside this loop, it distinguishes between different types of data:a. If v1 is a list, it means there are multiple items under a single heading. It iterates over the list and adds them as bullet points.b. If v1 is a dictionary, it means there are sub-headings under a main heading. It iterates through the sub-headings and adds their content.c. If v1 is neither a list nor a dictionary, it means it’s a simple paragraph of text.

The code snippet is essentially responsible for efficiently structuring and presenting employment history information within a Word document, applying various styles and formatting options to enhance readability.

# Step 4.0: Print the Additional
  add = th['Additional']
  if not add:
    add_formatted_paragraph(doc, '', bold = True, color = (67, 67, 67), alignment = WD_PARAGRAPH_ALIGNMENT.LEFT, Type = 'Text')
  else:
    addi = add_formatted_paragraph(doc, 'Additional', bold = True, color = (102,142,70), alignment = WD_PARAGRAPH_ALIGNMENT.LEFT, Type = 'Heading')
    addi.paragraph_format.space_before = Inches(0.015)
    addi.paragraph_format.space_after = Inches(0.2)

  # Step 4.1: format the content in it
  if not add:
      add_formatted_paragraph(doc, '', bold = True, color = (67, 67, 67), alignment = WD_PARAGRAPH_ALIGNMENT.CENTER, Type = 'Text')
  else:
    if not isinstance(add, dict):
      add_formatted_paragraph(doc, add, bold = False, color = (67, 67, 67), alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY, Type = 'Text')
    else:
      for k, v in add.items():
        key = add_formatted_paragraph(doc, k, bold = True, color = (67, 67, 67), alignment = WD_PARAGRAPH_ALIGNMENT.LEFT, Type = 'Text')
        key.paragraph_format.space_after = Inches(0.015)
        key.paragraph_format.space_before = Inches(0.02)
        for value in v:
          paragraph = doc.add_paragraph()
          paragraph.paragraph_format.left_indent = Inches(0.5)
          run = paragraph.add_run(value)
          style = doc.styles['Normal']
          run = style.font
          run.name = Text_fonts
          run.size = Pt(Text_size)
          run.color.rgb = RGBColor(67, 67, 67)
          paragraph.style = "ListBullet"
          paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT
          paragraph.paragraph_format.space_before = Inches(0.015)
          paragraph.paragraph_format.space_after = Inches(0.3)

Step 4.0: Printing the Additional

This section of the code is responsible for handling the ‘Additional’ section in a document.

  1. add = th['Additional']: This line retrieves the value associated with the key ‘Additional’ from the dictionary th. This suggests that th is a dictionary containing various sections of a document.
  2. if not add:: This checks if add is empty or evaluates to False. If it is, it means there is no content for the ‘Additional’ section.
    • If add is empty, it calls the function add_formatted_paragraph with specific parameters to insert an empty paragraph with certain formatting characteristics like bold text, black color, left alignment, and a type of ‘Text’.
    • If add is not empty, it proceeds to the else block.
  3. In the else block, it creates a formatted paragraph for the ‘Additional’ section with specific formatting attributes: bold text, a color in RGB format (102,142,70), left alignment, and a type of ‘Heading’. It then adjusts the space before and after the paragraph.

Step 4.1: Formatting the Additional

This section of the code handles the content within the ‘Additional’ section.

  1. if not add:: This checks if add is empty or evaluates to False. If it is, it means there is no content for the ‘Additional’ section.
    • If add is empty, it calls the function add_formatted_paragraph with specific parameters to insert an empty paragraph with certain formatting characteristics like bold text, black color, center alignment, and a type of ‘Text’.
    • If add is not empty, it proceeds to the next else block.
  2. In the next else block, it checks if add is not a dictionary.
    • If add is not a dictionary, it means it’s a string (or some non-dictionary type). It creates a formatted paragraph with specific attributes like no bold, black color, justified alignment, and a type of ‘Text’.
    • If add is indeed a dictionary, it iterates through its key-value pairs. For each key-value pair, it creates a bold formatted paragraph for the key, adjusting space before and after. It then creates a paragraph with an indent for the value, applying specific font and formatting attributes.
    • Finally, it applies a ‘ListBullet’ style to the paragraph, sets left alignment, and adjusts space before and after.

This code is likely a part of a larger script responsible for generating a formatted document, possibly using the Python library python-docx for handling Word documents. It deals specifically with the ‘Additional’ section, formatting it appropriately based on the content provided.

# Step 5.0 print the contact details
  cdetails = th['Contact Details']

  if not cdetails:
    add_formatted_paragraph(doc, '', bold = True, color = (67, 67, 67), alignment = WD_PARAGRAPH_ALIGNMENT.LEFT, Type = 'Text')
  else:
    cd = add_formatted_paragraph(doc, 'Contact Details', bold = True, color = (102,142,70), alignment = WD_PARAGRAPH_ALIGNMENT.LEFT, Type = 'Heading')
    cd.paragraph_format.space_before = Inches(0.015)
    cd.paragraph_format.space_after = Inches(0.2)

  # Step 5.1: creating a formatting for the information under contact details
  if not cdetails:
    add_formatted_paragraph(doc, '', bold = True, color = (67, 67, 67), alignment = WD_PARAGRAPH_ALIGNMENT.CENTER, fontsize = 13)
  else:
    for key, value in cdetails.items():
      paragraph = doc.add_paragraph()
      paragraph.add_run(f"•  {key} :").bold=True
      paragraph.add_run(f"\n          -    {value}")
      paragraph.paragraph_format.space_before = Inches(0.015)
      paragraph.paragraph_format.space_after = Inches(0.03)
    doc.add_paragraph()
  return doc

Step 5.0: Print the Contact details

  • cdetails = th['Contact Details']: This line appears to fetch the ‘Contact Details’ from some kind of data structure or dictionary th.
  • if not cdetails:: This checks if cdetails is empty or evaluates to False.
    • If cdetails is empty:
      • add_formatted_paragraph(...): This function is called with specific formatting parameters. It’s likely responsible for adding a formatted paragraph to the document.
      • This paragraph seems to be empty (since there is an empty string as the first argument).
    • If cdetails is not empty:
      • cd = add_formatted_paragraph(...): This seems to create a formatted paragraph titled ‘Contact Details’ with specified formatting attributes.
      • cd.paragraph_format.space_before and cd.paragraph_format.space_after adjust the spacing before and after the paragraph.

Step 5.1: Creating a formatting for the information under contact details

  • if not cdetails:: This checks if cdetails is empty or evaluates to False.
    • If cdetails is empty:
      • Another formatted paragraph is added, but this one is centered and with a different font size.
    • If cdetails is not empty:
      • A loop iterates over the key-value pairs in cdetails.For each key-value pair, a new paragraph is added to the document.The key is displayed as a bullet point followed by the value.
      For example:markdownCopy code
      • Key1 : - Value1
      • Key2 : - Value2
      • Spacing before and after the paragraph is adjusted.
  • doc.add_paragraph(): This adds an empty paragraph to the document, creating a separation between sections.
  • Finally, return doc indicates that the modified document is being returned by this function.

Overall, this code seems to be part of a larger process that involves creating a document and populating it with contact details, with specific formatting applied based on whether there are contact details available or not.

docs = resume_formatter(content, filename, dictionary)
docs.save("result.docx")
Get In Touch