Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Appending one document to another #558

Open
MorganSP opened this issue Oct 12, 2018 · 2 comments
Open

Appending one document to another #558

MorganSP opened this issue Oct 12, 2018 · 2 comments

Comments

@MorganSP
Copy link

I'm using docx to open a template and add some content as a first page. I then want to use a different template for subsequent pages (different watermarks). I then want to save all pages in one document. Is this possible in python-docx?

this is how I'm creating my document

page_1.render(context)            
out = StringIO()
page_1.save(out)
payload = out.getvalue()
filename = "proposal-%s-%s.docx" % (order.code, datetime.date.today())
response = HttpResponse(payload, 
    content_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document")
response['Content-Disposition'] = 'attachment;filename="%s"' % filename

I'm wondering if I can add
other_pages.render(context)
out_2 = StringIO()
other_pages.save(out_2)

and then something like
payload = out.getvalue() + out_2.getvalue()

This creates a file but when I try to open it I get the message "this file is corrupt and cannot be opened"

@plutext
Copy link

plutext commented Oct 14, 2018

This is not so easy in the general case. For more info, see my old blog post https://www.docx4java.org/blog/2010/11/merging-word-documents/

@nuarhu
Copy link

nuarhu commented Aug 19, 2019

Inspired by this comment #182 (comment) the following code works for me:

document = Document('MainTemplate.docx')
# add content

last_part_file = os.path.join('LastPart.docx')
last_part_doc = Document(last_part_file)
for para in last_part_doc.paragraphs:
    document._body._body._insert_p(para._p)

The content from LastPart.docx gets appended at the end of the new Document. The formatting looks like in the original LastPart.docx. (There are no bullet point lists but numbered lists, and they come out fine.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants