Skip to main content

How to Upload a PDF Template

This guide walks you through the complete process of creating a template and uploading a PDF file to use as your document template in Legalesign.

What You'll Learn

By the end of this guide, you'll know how to:

  1. Create a new template in your Legalesign group
  2. Get the template ID needed for upload
  3. Upload your PDF file to the template
  4. Verify the upload was successful

Prerequisites

Before you start, make sure you have:

  • A Legalesign account with API access
  • Your authentication credentials (see our authentication guide)
  • A PDF file ready to upload (maximum 50MB)
  • Your group ID (the workspace where you want to create the template)

The Complete Process

Step 1: Create a Template

First, you need to create an empty template in Legalesign. This gives you a template ID that you'll use for the PDF upload. To do this you'll need to run a GraphQL mutation, if you haven't done this before see the Introduction to GraphQL.

What is a Template?

A template is a reusable document structure in Legalesign. Once you upload a PDF to a template, you can:

  • Add signature fields and form fields
  • Send it to multiple recipients
  • Reuse it for different signers

GraphQL Mutation

mutation CreateTemplate($input: templateCreateInput!) {
createTemplate(input: $input) {
template {
id
title
groupId
created
}
}
}

Input Variables

{
"input": {
"groupId": "grpYourGroupAPIId",
"title": "Employment Contract Template"
}
}

Parameters Explained

  • groupId: The base 64 ID of your group/workspace (you can grab this from the URL in Console [https://console.legalesign.com/])
  • title: A descriptive name for your template (you can change this later)

Step 2: Extract the Template ID

The mutation returns a template object. You need to save the id field - this is what you'll use to upload your PDF.

Example response:

{
"data": {
"createTemplate": {
"template": {
"title": "Employment Contract Template",
"groupId": "grpYourGroupId"
}
}
}
}
tip

The template ID is a Base64-encoded string. Save this ID - you'll need it for the next step.

Step 3: Request Upload Permission

Now that you have a template ID, request a pre-signed URL to upload your PDF.

query GetUploadUrl {
upload(
id: "dHBsYjQ5YTg5NWQtYWRhMy0xMWYwLWIxZGMtMDY5NzZlZmU0MzIx",
uploadType: TEMPLATE,
extension: "pdf"
) {
url
}
}

Parameters

  • id: The template ID from Step 2
  • uploadType: Must be TEMPLATE for PDF templates
  • extension: Must be "pdf" for template files

The response will contain a pre-signed URL:

{
"data": {
"upload": {
"url": "https://s3.amazonaws.com/bucket/path?signature=..."
}
}
}
note

This URL is only valid for 15 minutes. If it expires, simply request a new one.

Step 4: Upload Your PDF

Use the pre-signed URL to upload your PDF file directly to S3. This will be different depending on your development stack. In our javascript example we've used fetch but you can use other libraries including aws-amplify.

Complete Working Examples

import fs from 'fs';
import { AuthenticationDetails, CognitoUser, CognitoUserPool } from 'amazon-cognito-identity-js';

// Get authentication token from AWS Cognito
const getToken = (username, password, pool = 'eu-west-2_NUPAjABy7', appClientId = '38kn0eb9mf2409t6mci98eqdvt') => {
const authenticationDetails = new AuthenticationDetails({
Username: username,
Password: password
});

const userData = {
Username: username,
Pool: new CognitoUserPool({
UserPoolId: pool,
ClientId: appClientId
})
};

const cognitoUser = new CognitoUser(userData);

return new Promise((resolve, reject) =>
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: result => resolve(result.getAccessToken().getJwtToken()),
onFailure: err => reject(err)
})
);
};

const uploadPdfTemplate = async (username, password, groupId, title, pdfFilePath) => {
const graphqlEndpoint = 'https://graphql.uk.legalesign.com/graphql';

// Get authentication token
console.log('Authenticating...');
const authToken = await getToken(username, password);

// Step 1: Create the template
console.log('Creating template...');
const createResponse = await fetch(graphqlEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authToken}`
},
body: JSON.stringify({
query: `
mutation CreateTemplate($input: templateCreateInput!) {
createTemplate(input: $input) {
template {
id
title
}
}
}
`,
variables: {
input: {
groupId: groupId,
title: title
}
}
})
});

const createResult = await createResponse.json();
const templateId = createResult.data.createTemplate.template.id;
console.log('Template created with ID:', templateId);

// Step 2: Get upload URL
console.log('Requesting upload URL...');
const uploadUrlResponse = await fetch(graphqlEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authToken}`
},
body: JSON.stringify({
query: `
query GetUploadUrl($id: ID!) {
upload(
id: $id,
uploadType: TEMPLATE,
extension: "pdf"
) {
url
}
}
`,
variables: {
id: templateId
}
})
});

const uploadUrlResult = await uploadUrlResponse.json();
const uploadUrl = uploadUrlResult.data.upload.url;
console.log('Upload URL received');

// Step 3: Upload the PDF
console.log('Uploading PDF...');
const fileData = fs.readFileSync(pdfFilePath);

const uploadResponse = await fetch(uploadUrl, {
method: 'PUT',
body: fileData,
headers: {
'Content-Type': 'application/pdf'
}
});

if (!uploadResponse.ok) {
throw new Error(`Upload failed: ${uploadResponse.statusText}`);
}

console.log('PDF uploaded successfully!');

return {
success: true,
templateId: templateId,
title: title
};
};

// Usage example
uploadPdfTemplate(
'your-email@example.com',
'your-password',
'grpYourGroupId',
'Employment Contract',
'./contract.pdf'
).then(result => {
console.log('Complete!', result);
}).catch(error => {
console.error('Error:', error);
});

Install dependencies:

npm install amazon-cognito-identity-js

What Happens After Upload?

Once your PDF is uploaded, Legalesign automatically:

  1. Scans for viruses - Ensures the file is safe
  2. Validates the PDF - Checks it's a valid PDF format
  3. Extracts page information - Gets page count and dimensions
  4. Processes the file - Optimizes it for viewing and signing
  5. Stores it securely - Moves it to permanent storage

This process usually takes a few seconds. Once complete, your template is ready to use!

Next Steps

Now that you have a template with a PDF, you can:

  1. Add signature fields - Use the createTemplateElement mutation to add fields
  2. Create roles - Define who will sign the document
  3. Send for signing - Use the send mutation to send to recipients
  4. Use the Document Viewer - Integrate our Document Viewer component for a visual editor

Common Issues and Solutions

"No permission" Error

Problem: You don't have access to the group or template.

Solution:

  • Verify your group ID is correct
  • Ensure you're authenticated with the right account
  • Check you have permission to create templates in this group

"File too large" Error

Problem: Your PDF exceeds the 50MB limit.

Solution:

  • Compress your PDF using a tool like Adobe Acrobat or online compressors
  • Remove unnecessary images or reduce image quality
  • Split large documents into multiple templates

Upload URL Expired

Problem: The pre-signed URL expired (after 15 minutes).

Solution:

  • Request a new upload URL by running the upload query again
  • Upload your file immediately after receiving the URL
  • For large files, ensure your internet connection is stable

"Invalid PDF" Error

Problem: The file isn't a valid PDF or is corrupted.

Solution:

  • Open the PDF in a PDF reader to verify it's valid
  • Re-export or re-save the PDF
  • Ensure the file extension is .pdf

Best Practices

  1. Validate PDFs before upload - Open them in a PDF reader first
  2. Use descriptive titles - Makes templates easier to find later
  3. Keep PDFs under 10MB - Faster uploads and better performance
  4. Handle errors gracefully - Always check for errors at each step
  5. Store template IDs - Save them in your database for future reference

Security Considerations

  • Never expose authentication tokens - Keep them server-side
  • Validate file types - Only upload PDFs for templates
  • Check file sizes - Prevent users from uploading huge files
  • Use HTTPS - All uploads are encrypted in transit
  • Audit uploads - Keep logs of who uploaded what