Skip to content
No results
  • Clean Code
  • Basic
  • Roadmap
    • Roadmap Beginner
    • Roadmap Intermediate
  • Tentang Penulis
  • Daftar Isi
Tutorial Nest.js
  • Clean Code
  • Basic
  • Roadmap
    • Roadmap Beginner
    • Roadmap Intermediate
  • Tentang Penulis
  • Daftar Isi
Tutorial Nest.js
Framework Nest.js
Framework Nest.js

Cara Bikin PDF di Backend NestJS Terus Kirim Lewat Email (Auto Attachment)

  • Abdan Zam Zam RamadhanAbdan Zam Zam Ramadhan
  • October 1, 2025
  • Basic

Pernah kepikiran gak sih, gimana caranya bikin sistem yang bisa langsung generate PDF (kayak invoice, laporan, atau slip gaji) terus otomatis dikirim ke email user? 🤔
Nah, di NestJS ini gampang banget kok, tinggal mix antara library buat bikin PDF sama mailer buat kirim email.

🔧 Tools Wajib

Sebelum eksekusi, kenalan dulu sama tools yang bakal dipakai:

📝 Buat PDF

  • pdfkit → bikin PDF langsung dari NodeJS. Simple & cepat.
  • puppeteer → render HTML ke PDF (cocok kalo lo udah punya template HTML/CSS kece).
  • pdfmake → lebih ke style declarative, gampang buat layout.

📩 Kirim Email

  • @nestjs-modules/mailer → gampang banget dipakai di NestJS (dibungkus dari nodemailer).
  • nodemailer → bisa dipakai juga, tapi lebih raw.

🚀 Step by Step

Langsung aja ke contoh paling simpel: generate PDF pakai pdfkit lalu kirim lewat email.

1️⃣ Service Buat Generate PDF

// pdf.service.ts
import { Injectable } from '@nestjs/common';
import * as PDFDocument from 'pdfkit';
import { join } from 'path';
import { writeFileSync } from 'fs';

@Injectable()
export class PdfService {
  async generatePdf(filename: string): Promise<string> {
    const doc = new PDFDocument();
    const filePath = join(__dirname, `../../storage/${filename}`);

    doc.pipe(writeFileSync(filePath, { flag: 'w' }) as any);
    doc.fontSize(16).text('Hello from NestJS PDF!', { align: 'center' });
    doc.text('PDF ini dibuat otomatis di backend NestJS 🚀', { align: 'left' });
    doc.end();

    return filePath;
  }
}

📌 Intinya: service ini bikin file PDF dan nyimpen sementara di folder storage.

2️⃣ Service Buat Kirim Email

// mail.service.ts
import { Injectable } from '@nestjs/common';
import { MailerService } from '@nestjs-modules/mailer';

@Injectable()
export class AppMailService {
  constructor(private readonly mailerService: MailerService) {}

  async sendMailWithPdf(to: string, filePath: string) {
    await this.mailerService.sendMail({
      to,
      subject: 'PDF Kamu Udah Jadi 🎉',
      text: 'Cek lampiran ya!',
      attachments: [
        {
          filename: 'report.pdf',
          path: filePath,
        },
      ],
    });
  }
}

📌 Jadi nanti email masuk ke inbox user, ada PDF langsung nempel di attachment.

3️⃣ Controller Buat Ngetes

// app.controller.ts
import { Controller, Get } from '@nestjs/common';
import { PdfService } from './pdf.service';
import { AppMailService } from './mail.service';

@Controller()
export class AppController {
  constructor(
    private readonly pdfService: PdfService,
    private readonly mailService: AppMailService,
  ) {}

  @Get('send-pdf')
  async sendPdf() {
    const filePath = await this.pdfService.generatePdf('report.pdf');
    await this.mailService.sendMailWithPdf('user@example.com', filePath);
    return { message: 'Email dengan PDF udah dikirim! 🚀' };
  }
}

📌 Endpoint GET /send-pdf ini bisa langsung lo hit, terus PDF bakal dikirim ke email target.

💡 Tips Santai

  • Kalo pengen PDF yang desainnya rapi kayak invoice → coba puppeteer, tinggal render HTML pake CSS.
  • Di serverless (kayak vercel/functions) → lebih aman langsung stream PDF ke buffer, jangan tulis file di disk.
  • Jangan lupa config SMTP di mailer (bisa Gmail, SendGrid, Mailgun, etc.).

🎯 Kesimpulan

Dengan NestJS, bikin fitur auto-generate PDF + auto-email attachment itu gampang banget.
Lo bisa pake buat:

  • Invoice otomatis 💵
  • Slip gaji 💼
  • Laporan transaksi 📊

Semua tinggal hit API → PDF jadi → email masuk ke inbox user.
Simple, clean, dan mantap buat production 🚀.

Tags
# backend generate pdf# cara generate pdf di backend# generate pdf nestjs# nestjs kirim email# nestjs nodemailer# nestjs pdf# nestjs pdf attachment# nestjs pdf report# nestjs pdfkit# nestjs puppeteer# nestjs send email attachment# nodejs pdf email# nodejs puppeteer pdf# pdf invoice nestjs# tutorial nestjs pemula
Abdan Zam Zam Ramadhan
Abdan Zam Zam Ramadhan

Senior Software Engineer @ PT. Astra Internasional, Tbk.

Articles: 11
Framework Nest.js
Previous Post Belajar NestJS untuk Pemula: Clean Code, Best Practice, dan Studi Kasus
Next Post Authentication & Authorization di NestJS: Bedanya Apa, dan Cara Pakainya
Framework Nest.js

Related Posts

Framework Nest.js

Cara Install NestJS CLI dan Membuat Project Baru

  • October 14, 2025
Framework Nest.js

Pengenalan dan Konsep Dasar NestJS

  • October 9, 2025
Framework Nest.js

Mini Project: JWT Auth dengan TypeORM di NestJS (Access + Refresh + Logout)

  • October 2, 2025

Copyright © 2026 - Powered by Abdan Zam Zam Ramadhan

Powered by
...
►
Necessary cookies enable essential site features like secure log-ins and consent preference adjustments. They do not store personal data.
None
►
Functional cookies support features like content sharing on social media, collecting feedback, and enabling third-party tools.
None
►
Analytical cookies track visitor interactions, providing insights on metrics like visitor count, bounce rate, and traffic sources.
None
►
Advertisement cookies deliver personalized ads based on your previous visits and analyze the effectiveness of ad campaigns.
None
►
Unclassified cookies are cookies that we are in the process of classifying, together with the providers of individual cookies.
None
Powered by