0

I have a doc file with a header. I would like to add more pages to this file and copy and paste the header from the first page into all the new pages.

from docx.parts.hdrftr import HeaderPart
document = Document("Template.docx")
document.add_page_break

h = document.sections[0].first_page_header
p = h.part

copyHdr = None
for k in p.package.parts:
  if isinstance(k, HeaderPart):
    copyHdr = copy.deepcopy(k)
    print(k)

newHeader = document.add_heading()

I can get the header, but what part or parts I should copy? Where I'll add it? Thanks

Here is a screenshot showing what I am trying to have. enter image description here

  • A header automatically appears on every page until you set a new header (including possibly a blank one). So no need to copy paste. – scanny Dec 01 '21 at 20:15
  • Hi @scanny thanks for the message, I generate a new page but the I don't have a header. Do you have an example that I can try? – Mirco Bianchini Dec 02 '21 at 03:21
  • Check and see whether it is a first-page only header. That one only shows on the first page. There can be up to three headers in each section, default, first-page, and even pages. The default header appears on all pages where it is not overridden. A first-page header appears on the first page only (overriding the default). An even-page header appears on verso pages (left page in book bind, back of page on two-sided print). So if you only have a first-page header and no default header, you'll see the behavior you describe. https://python-docx.readthedocs.io/en/latest/api/section.html#id1 – scanny Dec 02 '21 at 03:48
  • yep is a first-page only header, so it is not possible to loop the parts inside the header (image and text) and copy them into a new default header? – Mirco Bianchini Dec 02 '21 at 05:36
  • It would be the same approach as when copying a document. There is no direct API support for that, but others have been able to do it, at least partially: https://stackoverflow.com/questions/48869423/how-do-i-copy-the-contents-of-a-word-document – scanny Dec 02 '21 at 18:49
  • Yep I saw that example. So the steps should be: getting the Header object by the sections getting the paragraph, accessing the run and check for pictures or texts and copy them. is this correct? – Mirco Bianchini Dec 02 '21 at 23:07
  • I think that's the way I would approach it. It depends a little bit on the diversity of the documents your code is going to run on. If you have a pretty good idea what you're going to encounter it's going to be a lot easier to come up with something that works. If it has to work in the absolute general case then that's a much tougher job, which is why it's not in the library yet :) – scanny Dec 03 '21 at 05:21

0 Answers0