Skip to main content
Glama
ZatesloFL

Google Workspace MCP Server

by ZatesloFL

export_doc_to_pdf

Convert a Google Doc into a PDF format and save it to Google Drive. Specify the document ID, email address, optional filename, and folder ID for storage. Retrieve confirmation with file details and links.

Instructions

Exports a Google Doc to PDF format and saves it to Google Drive.

Args: user_google_email: User's Google email address document_id: ID of the Google Doc to export pdf_filename: Name for the PDF file (optional - if not provided, uses original name + "_PDF") folder_id: Drive folder ID to save PDF in (optional - if not provided, saves in root)

Returns: str: Confirmation message with PDF file details and links

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
document_idYes
folder_idNo
pdf_filenameNo
user_google_emailYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The core handler function for the 'export_doc_to_pdf' tool. It exports a Google Document to PDF using the Google Drive API's export_media method, then uploads the resulting PDF file back to Google Drive, optionally into a specified folder. Includes validation that the document is a native Google Doc, generates filename if not provided, and returns success message with links.
    @server.tool()
    @handle_http_errors("export_doc_to_pdf", service_type="drive")
    @require_google_service("drive", "drive_file")
    async def export_doc_to_pdf(
        service,
        user_google_email: str,
        document_id: str,
        pdf_filename: str = None,
        folder_id: str = None,
    ) -> str:
        """
        Exports a Google Doc to PDF format and saves it to Google Drive.
    
        Args:
            user_google_email: User's Google email address
            document_id: ID of the Google Doc to export
            pdf_filename: Name for the PDF file (optional - if not provided, uses original name + "_PDF")
            folder_id: Drive folder ID to save PDF in (optional - if not provided, saves in root)
    
        Returns:
            str: Confirmation message with PDF file details and links
        """
        logger.info(f"[export_doc_to_pdf] Email={user_google_email}, Doc={document_id}, pdf_filename={pdf_filename}, folder_id={folder_id}")
    
        # Get file metadata first to validate it's a Google Doc
        try:
            file_metadata = await asyncio.to_thread(
                service.files().get(
                    fileId=document_id, 
                    fields="id, name, mimeType, webViewLink"
                ).execute
            )
        except Exception as e:
            return f"Error: Could not access document {document_id}: {str(e)}"
    
        mime_type = file_metadata.get("mimeType", "")
        original_name = file_metadata.get("name", "Unknown Document")
        web_view_link = file_metadata.get("webViewLink", "#")
    
        # Verify it's a Google Doc
        if mime_type != "application/vnd.google-apps.document":
            return f"Error: File '{original_name}' is not a Google Doc (MIME type: {mime_type}). Only native Google Docs can be exported to PDF."
    
        logger.info(f"[export_doc_to_pdf] Exporting '{original_name}' to PDF")
    
        # Export the document as PDF
        try:
            request_obj = service.files().export_media(
                fileId=document_id,
                mimeType='application/pdf'
            )
            
            fh = io.BytesIO()
            downloader = MediaIoBaseDownload(fh, request_obj)
            
            done = False
            while not done:
                _, done = await asyncio.to_thread(downloader.next_chunk)
                
            pdf_content = fh.getvalue()
            pdf_size = len(pdf_content)
            
        except Exception as e:
            return f"Error: Failed to export document to PDF: {str(e)}"
    
        # Determine PDF filename
        if not pdf_filename:
            pdf_filename = f"{original_name}_PDF.pdf"
        elif not pdf_filename.endswith('.pdf'):
            pdf_filename += '.pdf'
    
        # Upload PDF to Drive
        try:
            # Reuse the existing BytesIO object by resetting to the beginning
            fh.seek(0)
            # Create media upload object
            media = MediaIoBaseUpload(
                fh,
                mimetype='application/pdf',
                resumable=True
            )
            
            # Prepare file metadata for upload
            file_metadata = {
                'name': pdf_filename,
                'mimeType': 'application/pdf'
            }
            
            # Add parent folder if specified
            if folder_id:
                file_metadata['parents'] = [folder_id]
            
            # Upload the file
            uploaded_file = await asyncio.to_thread(
                service.files().create(
                    body=file_metadata,
                    media_body=media,
                    fields='id, name, webViewLink, parents',
                    supportsAllDrives=True
                ).execute
            )
            
            pdf_file_id = uploaded_file.get('id')
            pdf_web_link = uploaded_file.get('webViewLink', '#')
            pdf_parents = uploaded_file.get('parents', [])
            
            logger.info(f"[export_doc_to_pdf] Successfully uploaded PDF to Drive: {pdf_file_id}")
            
            folder_info = ""
            if folder_id:
                folder_info = f" in folder {folder_id}"
            elif pdf_parents:
                folder_info = f" in folder {pdf_parents[0]}"
            
            return f"Successfully exported '{original_name}' to PDF and saved to Drive as '{pdf_filename}' (ID: {pdf_file_id}, {pdf_size:,} bytes){folder_info}. PDF: {pdf_web_link} | Original: {web_view_link}"
            
        except Exception as e:
            return f"Error: Failed to upload PDF to Drive: {str(e)}. PDF was generated successfully ({pdf_size:,} bytes) but could not be saved to Drive."
  • Registers the export_doc_to_pdf function as an MCP tool using the @server.tool() decorator.
    @server.tool()
  • Input schema defined via function parameters and type hints: user_google_email (str), document_id (str), pdf_filename (str optional), folder_id (str optional). Output: str confirmation message.
    async def export_doc_to_pdf(
        service,
        user_google_email: str,
        document_id: str,
        pdf_filename: str = None,
        folder_id: str = None,
    ) -> str:
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries full burden. It mentions the action ('exports', 'saves') but lacks critical behavioral details: required permissions (e.g., edit access to the Doc, write access to Drive), whether the original Doc is modified, error conditions (e.g., invalid IDs, quota limits), or response format beyond the return statement. The description is minimal beyond basic functionality.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured and front-loaded: the first sentence states the core purpose, followed by organized sections for Args and Returns. Each sentence earns its place by explaining parameters and outcomes without redundancy, making it easy to scan and understand quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no annotations, 4 parameters with 0% schema coverage, and an output schema (returns str), the description is moderately complete. It covers parameter semantics and return type but lacks behavioral context (e.g., permissions, errors) and doesn't fully compensate for the missing annotations, leaving gaps for a mutation tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate. It adds meaningful context for all parameters: 'user_google_email' specifies the user's email, 'document_id' identifies the Doc, 'pdf_filename' explains naming rules (optional, default behavior), and 'folder_id' specifies save location (optional, defaults to root). This clarifies purpose beyond schema titles like 'Document Id'.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('Exports a Google Doc to PDF format') and the resource involved ('Google Doc'), then specifies the destination ('saves it to Google Drive'). It distinguishes from siblings like 'get_doc_content' (read-only) or 'create_doc' (creation) by focusing on format conversion and storage.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites (e.g., document accessibility, user permissions), compare to similar tools like 'get_drive_file_content' (which might retrieve files without conversion), or specify use cases (e.g., archiving, sharing).

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/ZatesloFL/google_workspace_mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server