Skip to content

Commit

Permalink
pdf usinjg pdflif
Browse files Browse the repository at this point in the history
  • Loading branch information
rayhanalmim committed Jun 12, 2024
1 parent 151c99d commit b72d57d
Show file tree
Hide file tree
Showing 5 changed files with 155 additions and 114 deletions.
55 changes: 55 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
name: CICD for EBS in node js
on:
push:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [20.x]
steps:
- uses: actions/checkout@v2
- name: Cache node modules
uses: actions/cache@v2
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: Node ${{ matrix.node-version }}
uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
- name: Installing NPM
run: npm install
- name: Building application
run: npm run build

- name: Generate deployment package
run: zip -r deploy.zip * -x "**node_modules**"
- name: Get timestamp
uses: gerred/actions/current-time@master
id: current-time
- name: Run string replace
uses: frabert/replace-string-action@master
id: format-time
with:
pattern: '[:\.]+'
string: "${{ steps.current-time.outputs.time }}"
replace-with: "-"
flags: "g"
- name: Beanstalk Deploy for app
uses: einaregilsson/beanstalk-deploy@v20
with:
aws_access_key: ${{secrets.ACCESS_KEY_ID}}
aws_secret_key: ${{secrets.SECRET_ACCESS_KEY}}
application_name: loamic-server
environment_name: Environment name
region: Region
version_label: "my-app-${{ steps.format-time.outputs.replaced }}"
deployment_package: deploy.zip
- name: Deployed!
run: echo App deployed to EBS
89 changes: 31 additions & 58 deletions dist/app/modules/pdftoemail/pdftomail.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PdfController = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const handlebars_1 = __importDefault(require("handlebars"));
const aws_sdk_1 = __importDefault(require("aws-sdk"));
const html_pdf_1 = __importDefault(require("html-pdf"));
const pdf_lib_1 = require("pdf-lib"); // Import pdf-lib for creating PDFs
const config_1 = __importDefault(require("../../config"));
// Configure AWS
aws_sdk_1.default.config.update({
Expand All @@ -37,65 +34,41 @@ const generateAndUploadPdf = (req, res) => __awaiter(void 0, void 0, void 0, fun
message: "Title and content are required.",
});
}
// HTML template as a string
const templateContent = `
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<h1>{{title}}</h1>
<p>{{content}}</p>
</body>
</html>
`;
// Compile the template
const template = handlebars_1.default.compile(templateContent);
// Generate HTML from the template and data
const html = template({ title: pdfData.title, content: pdfData.content });
// Use html-pdf to generate the PDF
html_pdf_1.default.create(html).toFile((err, fileInfo) => {
if (err) {
console.error("Error generating PDF:", err);
// Create a new PDF document
const pdfDoc = yield pdf_lib_1.PDFDocument.create();
const page = pdfDoc.addPage();
// Draw title and content on the page
page.drawText(pdfData.title, { x: 50, y: 750 });
page.drawText(pdfData.content, { x: 50, y: 700 });
// Serialize the PDFDocument to bytes
const pdfBytes = yield pdfDoc.save();
// Upload the PDF to AWS S3
const uploadParams = {
Bucket: "loamic-media",
Key: `pdfs/${Date.now()}-output.pdf`,
Body: pdfBytes,
ContentType: "application/pdf",
};
s3.upload(uploadParams, (uploadErr, data) => __awaiter(void 0, void 0, void 0, function* () {
if (uploadErr) {
console.error("Error uploading to S3:", uploadErr);
return res.status(500).json({
success: false,
message: "Failed to generate PDF",
error: err,
message: "Failed to upload PDF to S3",
error: uploadErr,
});
}
// Upload the PDF to AWS S3
const fileContent = fs_1.default.readFileSync(fileInfo.filename);
const uploadParams = {
// Generate a pre-signed URL for the uploaded PDF
const signedUrl = yield s3.getSignedUrlPromise("getObject", {
Bucket: "loamic-media",
Key: `pdfs/${Date.now()}-${path_1.default.basename(fileInfo.filename)}`,
Body: fileContent,
ContentType: "application/pdf",
};
s3.upload(uploadParams, (uploadErr, data) => __awaiter(void 0, void 0, void 0, function* () {
if (uploadErr) {
console.error("Error uploading to S3:", uploadErr);
fs_1.default.unlinkSync(fileInfo.filename); // Ensure temporary file is deleted even on upload failure
return res.status(500).json({
success: false,
message: "Failed to upload PDF to S3",
error: uploadErr,
});
}
// Generate a pre-signed URL for the uploaded PDF
const signedUrl = yield s3.getSignedUrlPromise("getObject", {
Bucket: "loamic-media",
Key: uploadParams.Key,
Expires: 60 * 5, // Link expires in 5 minutes
});
// Delete temporary file
fs_1.default.unlinkSync(fileInfo.filename);
res.json({
downloadUrl: signedUrl,
message: "Email sent successfully",
});
}));
});
Key: uploadParams.Key,
Expires: 60 * 5, // Link expires in 5 minutes
});
res.json({
downloadUrl: signedUrl,
message: "PDF generated and uploaded successfully",
});
}));
}
catch (error) {
console.error("Unexpected error:", error);
Expand Down
38 changes: 38 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"html-pdf": "^3.0.1",
"http-status": "^1.7.4",
"mongoose": "^8.4.1",
"pdf-lib": "^1.17.1",
"phantomjs-prebuilt": "^2.1.16",
"puppeteer-core": "^10.4.0"
},
Expand Down
86 changes: 30 additions & 56 deletions src/app/modules/pdftoemail/pdftomail.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import fs from "fs";
import path from "path";
import handlebars from "handlebars";
import AWS from "aws-sdk";
import pdf from "html-pdf";
import { PDFDocument } from "pdf-lib"; // Import pdf-lib for creating PDFs
import config from "../../config";

// Configure AWS
Expand All @@ -27,71 +27,45 @@ const generateAndUploadPdf = async (req: Request, res: Response) => {
});
}

// HTML template as a string
const templateContent = `
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<h1>{{title}}</h1>
<p>{{content}}</p>
</body>
</html>
`;
// Create a new PDF document
const pdfDoc = await PDFDocument.create();
const page = pdfDoc.addPage();

// Compile the template
const template = handlebars.compile(templateContent);
// Draw title and content on the page
page.drawText(pdfData.title, { x: 50, y: 750 });
page.drawText(pdfData.content, { x: 50, y: 700 });

// Generate HTML from the template and data
const html = template({ title: pdfData.title, content: pdfData.content });
// Serialize the PDFDocument to bytes
const pdfBytes = await pdfDoc.save();

// Use html-pdf to generate the PDF
pdf.create(html).toFile((err, fileInfo) => {
if (err) {
console.error("Error generating PDF:", err);
// Upload the PDF to AWS S3
const uploadParams = {
Bucket: "loamic-media",
Key: `pdfs/${Date.now()}-output.pdf`,
Body: pdfBytes,
ContentType: "application/pdf",
};

s3.upload(uploadParams, async (uploadErr: any, data: any) => {
if (uploadErr) {
console.error("Error uploading to S3:", uploadErr);
return res.status(500).json({
success: false,
message: "Failed to generate PDF",
error: err,
message: "Failed to upload PDF to S3",
error: uploadErr,
});
}

// Upload the PDF to AWS S3
const fileContent = fs.readFileSync(fileInfo.filename);
const uploadParams = {
// Generate a pre-signed URL for the uploaded PDF
const signedUrl = await s3.getSignedUrlPromise("getObject", {
Bucket: "loamic-media",
Key: `pdfs/${Date.now()}-${path.basename(fileInfo.filename)}`,
Body: fileContent,
ContentType: "application/pdf",
};

s3.upload(uploadParams, async (uploadErr: any, data: any) => {
if (uploadErr) {
console.error("Error uploading to S3:", uploadErr);
fs.unlinkSync(fileInfo.filename); // Ensure temporary file is deleted even on upload failure
return res.status(500).json({
success: false,
message: "Failed to upload PDF to S3",
error: uploadErr,
});
}

// Generate a pre-signed URL for the uploaded PDF
const signedUrl = await s3.getSignedUrlPromise("getObject", {
Bucket: "loamic-media",
Key: uploadParams.Key,
Expires: 60 * 5, // Link expires in 5 minutes
});

// Delete temporary file
fs.unlinkSync(fileInfo.filename);
Key: uploadParams.Key,
Expires: 60 * 5, // Link expires in 5 minutes
});

res.json({
downloadUrl: signedUrl,
message: "Email sent successfully",
});
res.json({
downloadUrl: signedUrl,
message: "PDF generated and uploaded successfully",
});
});
} catch (error) {
Expand Down

0 comments on commit b72d57d

Please sign in to comment.