To create a full-stack application where a front-end user clicks a button to download a Word doc generated by AWS Lambda using DynamoDB data, follow these steps:
-
Create a DynamoDB table
- Sign in to the AWS Management Console and open the DynamoDB service.
- Create a new table with a suitable primary key (e.g., a "primary_key" string attribute).
- Add two additional attributes to store the required data (e.g., "column1" and "column2" string attributes).
-
Create an AWS Lambda function
- In the AWS Management Console, open the Lambda service.
- Create a new function with a suitable runtime (e.g., Node.js or Python).
- Upload the required dependencies to create a Word document, such as
docxtemplater and docx-utils for Node.js or python-docx for Python.
- Write the Lambda function code:
const AWS = require('aws-sdk');
const docxtemplater = require('docxtemplater');
const fs = require('fs');
const DocxtemplaterUtils = require('docxtemplater/out/Utils');
const docxConverter = require('docx-pdf');
const s3 = new AWS.S3();
exports.handler = async (event) => {
const params = {
TableName: 'your_dynamodb_table_name',
Key: {
'primary_key': { S: event.key },
},
};
let dynamoData;
try {
const data = await dynamodb.getItem(params).promise();
dynamoData = data.Item;
} catch (error) {
console.error('Error fetching data from DynamoDB:', error);
throw error;
}
const content = fs.readFileSync('template.docx');
const zip = new DocxtemplaterUtils.Zip(content);
const doc = new docxtemplater(zip);
doc.setData({
column1: dynamoData.column1.S,
column2: dynamoData.column2.S,
});
try {
doc.render();
} catch (error) {
console.error('Error rendering the document:', error);
throw error;
}
const buf = await doc.getZip().generate({ type: 'nodebuffer' });
const pdfBuf = await docxConverter(buf);
const response = {
statusCode: 200,
headers: {
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename=generated_document.pdf',
},
body: pdfBuf.toString('base64'),
isBase64Encoded: true,
};
return response;
};
- For Python:
import boto3
import base64
import io
from docx import Document
from docx.shared import Inches
from docx.opc.constants import RELATIONSHIP_TYPE as RT
dynamodb = boto3.client('dynamodb')
s3 = boto3.client('s3')
def lambda_handler(event, context):
key = event['key']
response = dynamodb.get_item(
TableName='your_dynamodb_table_name',
Key={
'primary_key': {'S': key}
}
)
item = response['Item']
column1 = item['column1']['S']
column2 = item['column2']['S']
doc = Document()
doc.add_heading('Generated Document', 0)
doc.add_paragraph(f'Column 1: {column1}')
doc.add_paragraph(f'Column 2: {column2}')
pdf_bytes = convert_docx_to_pdf(doc)
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename=generated_document.pdf'
},
'