Salman.S
Salman.S

Reputation: 96

python-docx add title in a 2 column layout document

I've been going through the python-docx docs and couldn't find a way to insert a title in a 2 column layout document.

I've tried several methods to get a workaround and none of them worked. Whenever I create a 2 column layout using python-docx and try to add a title for the document, the title is not added to the top center of the document, it actually gets added to the first column on the left.

Below is the code that I am using to generate the document.

from docx import Document
from docx.shared import Inches
from docx.shared import Pt
from docx.enum.section import WD_SECTION
from docx.oxml.ns import qn

doc = Document()

# Title
title = doc.add_heading('THIS IS THE TITLE')

section = doc.sections[0]

sectPr = section._sectPr
cols = sectPr.xpath('./w:cols')[0]
cols.set(qn('w:num'),'2')

# Left column
par1 = doc.add_paragraph('FIRST PAR IN THE LEFT COLUMN(testingtestingtestingtestingtestingtestingtestingtestingtestingtesting)')

# Right column
current_section = doc.sections[-1]  
current_section.start_type
new_section = doc.add_section(WD_SECTION.NEW_COLUMN)
new_section.start_type

par2 = doc.add_paragraph('FIRST PAR IN THE RIGHT COLUMN(testingtestingtestingtestingtestingtestingtestingtestingtestingtesting)')

# Save Doc
doc.save('demo.docx')

The below image shows the result of the code.

result

Is there any way I could insert the title on the top center of the document, or do I need to use templates in order to do so?

EDIT (solution):

Scanny pointed out that I should isolate each element in its own section. please find the code below generating 2 column document with a title.

from docx import Document
from docx.shared import Inches
from docx.shared import Pt
from docx.enum.section import WD_SECTION
from docx.oxml.ns import qn
import pdf2docx

doc = Document()
# First Section
new_section = doc.add_section(WD_SECTION.CONTINUOUS)
new_section.start_type

p1 = doc.add_heading('This is the title!!!!!!!!!!!!!')
p1.alignment = 1

# Second Section
new_section = doc.add_section(WD_SECTION.CONTINUOUS)
new_section.start_type
section = doc.sections[2]

# Set to 2 column layout
sectPr = section._sectPr
cols = sectPr.xpath('./w:cols')[0]
cols.set(qn('w:num'),'2')

p1 = doc.add_paragraph('This is the 1st para')
p1.alignment = 1

# Third Section
new_section = doc.add_section(WD_SECTION.NEW_COLUMN)          
new_section.start_type


p1 = doc.add_paragraph('This is the 2nd para')
p1.alignment = 1


# Save
doc.save('demo.docx')

Thanks to Scanny!

Upvotes: 1

Views: 1188

Answers (1)

scanny
scanny

Reputation: 28903

You'll need separate sections for the (1-col) title and the (2-col) body. There is a setting on a section to specify the kind of break that precedes it, something like section.start_type = WD_SECTION.CONTINUOUS. I believe that will need to go on the second section

Upvotes: 2

Related Questions