Javaでスクレイピング→PDF帳票化→メール送信まで一括実行する方法【業務自動化】

「Webサイトから情報を取得し、PDF帳票として整形し、メールで関係者に送信する」
この一連の作業をJavaで完全自動化する方法を、実践的なコード付きで解説します。


この記事の対象者

  • Javaで業務系ツールを開発している方
  • レポート・報告書の自動生成を考えている方
  • Webスクレイピング後のPDF出力と通知までを一括処理したい方

全体の流れ

  1. JsoupでWebサイトをスクレイピング
  2. iTextでPDFに整形
  3. JavaMailでPDF添付メール送信

1. Webスクレイピングでデータ取得

Jsoupを使って、例としてニュース記事タイトルを取得します。


import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import java.util.List;
import java.util.stream.Collectors;

public class Scraper {
    public static List<String> getHeadlines(String url) throws Exception {
        Document doc = Jsoup.connect(url).get();
        Elements headlines = doc.select("h2.headline"); // 適宜変更
        return headlines.stream()
                .map(e -> e.text())
                .collect(Collectors.toList());
    }
}

2. スクレイピング結果をPDF帳票に変換

iText 7を使用して、簡単なPDFレポートを作成します。


<dependency>
  <groupId>com.itextpdf</groupId>
  <artifactId>itext7-core</artifactId>
  <version>8.0.2</version>
  <type>pom</type>
</dependency>

import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;

import java.util.List;

public class PdfGenerator {
    public static String createPdf(List<String> headlines, String filename) throws Exception {
        PdfWriter writer = new PdfWriter(filename);
        PdfDocument pdf = new PdfDocument(writer);
        Document document = new Document(pdf);

        document.add(new Paragraph("Webニュースレポート").setBold().setFontSize(16));
        document.add(new Paragraph(" "));

        for (String line : headlines) {
            document.add(new Paragraph("- " + line));
        }

        document.close();
        return filename;
    }
}

3. PDFをメール添付して送信

JavaMailを使って、PDFを添付ファイルとして送信します。


<dependency>
  <groupId>com.sun.mail</groupId>
  <artifactId>jakarta.mail</artifactId>
  <version>2.0.1</version>
</dependency>

import jakarta.mail.*;
import jakarta.mail.internet.*;

import java.io.File;
import java.util.Properties;

public class MailSender {
    public static void sendMail(String to, String filePath) throws Exception {
        String from = "your@example.com";
        String host = "smtp.example.com";

        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("your@example.com", "your-password");
            }
        });

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(
                Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSubject("【自動送信】Webニュースレポート");

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText("最新ニュースのレポートを添付します。");

        MimeBodyPart attachmentPart = new MimeBodyPart();
        attachmentPart.attachFile(new File(filePath));

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        multipart.addBodyPart(attachmentPart);

        message.setContent(multipart);

        Transport.send(message);
        System.out.println("メール送信完了: " + to);
    }
}

4. 一括実行するMainクラス

上記3ステップを1つのJavaアプリケーションとしてまとめます。


public class AutoReportApp {
    public static void main(String[] args) throws Exception {
        // ステップ1: データ取得
        List<String> headlines = Scraper.getHeadlines("https://example.com/news");

        // ステップ2: PDF化
        String pdfPath = "report.pdf";
        PdfGenerator.createPdf(headlines, pdfPath);

        // ステップ3: メール送信
        MailSender.sendMail("receiver@example.com", pdfPath);
    }
}

まとめ:一括自動化で時間と手間を削減

Javaを使えば、スクレイピング→PDF帳票化→メール通知という一連の業務プロセスを完全自動化できます。
日次・週次のレポート配信や監視レポートなど、業務効率化に直結する仕組みです。
ぜひこの仕組みをベースに、自社業務へ応用してみてください。

タイトルとURLをコピーしました