Search code examples
pythongoogle-drive-apigoogle-docsgoogle-docs-apigoogle-api-python-client

how to add image in header and keep first page header and footer different from other pages using google docs API in python


Thanks to Tanaike's solution, I'm able to add header and footer in my document. The only problem is I want to keep the first page's header and footer different from rest of the pages.

Also I want to add multiple small images in my header but using insertInlineImage in the header to add an image throws error.

My working code:

file_id = ##
def insert_data(file_id):
    requests = []
    header_footer_req = []

    index = 0
    header_footer_req.append(add_header(index))
    header_footer_req.append(add_footer())
    header_footer_res = docs.documents().batchUpdate(documentId=file_id, body={'requests': header_footer_req}).execute()
    header_id = header_footer_res['replies'][0]['createHeader']['headerId']
    footer_id = header_footer_res['replies'][1]['createFooter']['footerId']
    requests.append(add_header_content(index, header_id))
    requests.append(add_footer_content(footer_id))
    
    docs.documents().batchUpdate(documentId=file_id, body={'requests': requests}).execute()    

def add_header(index):
    header = {
        "createHeader": {
            "sectionBreakLocation": {
                "index": index
            },
            "type": "DEFAULT"
        }
    }
    return header


def add_header_content(index, headerId):
    headerText = {
        "insertText": {
            "location": {
                "segmentId": headerId,
                "index": index,
            },
            "text": "sample text"
        }
    }
    return headerText


def add_footer():
    footer = {
        "createFooter": {
            "type": "DEFAULT"
        }
    }
    return footer


def add_footer_content(footer_id):
    footer_data = {
        "insertText": {
            "location": {
                "segmentId": footer_id,
                "index": 0
            },
            "text": "This is my footer"
        }
    }
    return footer_data

Expected sample output: Page 1: page 1

Rest other pages: other pages

Please note that the footer of both the pages are different and they are right aligned and are colored. It also has page number on the left.


Solution

  • I believe your goal is as follows.

    • You want to create a header and footer to Google Document.
      • From I'll keep the header and footer in my document same for all the pages., you want to use the same header and footer for the 1st and other pages.
    • For the header, you want to insert an image to the right side.
    • For the footer, you want to insert 2 texts to the right side.
    • You want to achieve this using googleapis for python.

    In this case, how about the following modified script?

    Modified script:

    In this modification, please modify your function of insert_data as follows.

    def insert_data(file_id):
        requests = []
        header_footer_req = []
    
        index = 0
        header_footer_req.append(add_header(index))
        header_footer_req.append(add_footer())
        header_footer_res = docs.documents().batchUpdate(documentId=file_id, body={'requests': header_footer_req}).execute()
        header_id = header_footer_res['replies'][0]['createHeader']['headerId']
        footer_id = header_footer_res['replies'][1]['createFooter']['footerId']
    
        # Add header content
        requests += [
            {
                "insertInlineImage": {
                    "location": {
                        "segmentId": header_id,
                        "index": 0
                    },
                    "uri": "https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.png", # This is a sample image.
                    "objectSize": {
                        "width": {
                            "magnitude": 100,
                            "unit": "PT"
                        }
                    }
                }
            },
            {
                "updateParagraphStyle": {
                    "paragraphStyle": {
                        "alignment": "END"
                    },
                    "range": {
                        "segmentId": header_id,
                        "startIndex": 0,
                        "endIndex": 1
                    },
                    "fields": "alignment"
                }
            }
        ]
    
        # Add footer content.
        text = "This is my footer\nsample text"
        requests += [
            {
                "insertText": {
                    "location": {
                        "segmentId": footer_id,
                        "index": 0
                    },
                    "text": text
                }
            },
            {
                "updateParagraphStyle": {
                    "paragraphStyle": {
                        "alignment": "END"
                    },
                    "range": {
                        "segmentId": footer_id,
                        "startIndex": 0,
                        "endIndex": len(text)
                    },
                    "fields": "alignment"
                }
            }
        ]
    
        docs.documents().batchUpdate(documentId=file_id, body={'requests': requests}).execute()
    
    • If you want to align the content to the left side, please modify END to START.

    Note:

    • In this sample script, when the header and footer have already been created, an error like Default header already exists. occurs. Because the header and footer cannot be added to the Document which has the header and footer. Please be careful about this.

    References: