0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaでBase64 PDFを処理:デコード、編集、再エンコード

Posted at

Web API、分散サービス、サーバーレス関数などの環境では、PDF ファイルが Base64 文字列 としてやり取りされるケースが少なくありません。Base64 形式を利用することで、ファイル操作を省略でき、ネットワーク経由の受け渡しに適しています。
受信した PDF を加工(例:透かし追加、注釈、署名など)するには、Base64 と PDF の相互変換 および PDF 編集 の手順を理解することが重要です。

この記事では、Java と Free Spire.PDF for Java を使い、以下の操作を実現する方法を紹介します:

  • Base64文字列をPDFにデコード
  • PDFの編集(例:各ページに「Processed」というテキスト透かしを追加)
  • 編集後のPDFを再度Base64文字列にエンコード

準備

最初に Free Spire.PDF for Java をプロジェクトに追加してください。Maven での設定例は以下の通りです。

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.cn/repository/maven-public/</url>
    </repository>
</repositories>
<dependency>
    <groupId>e-iceblue</groupId>
    <artifactId>spire.pdf.free</artifactId>
    <version>9.13.0</version>
</dependency>

Step 1: Base64をデコードしてPDFを読み込み

外部システムやAPIから受信した Base64 文字列をバイト配列にデコードし、PdfDocument.loadFromBytes() を利用して PDF ドキュメントを読み込みます。

コード例:

import com.spire.pdf.*;
import java.util.Base64;

String base64Pdf = "..."; // 入力Base64文字列
byte[] pdfBytes = Base64.getDecoder().decode(base64Pdf);

// PDFを読み込み
PdfDocument pdf = new PdfDocument();
pdf.loadFromBytes(pdfBytes);

Step 2: PDFを編集

Spire.PDF には描画APIが用意されており、テキスト・画像・図形をページに追加できます。ここでは例として、各ページに青色の太字テキスト「Processed」を追加し、処理済みであることを示します。

操作手順:

  1. ドキュメント内のすべてのページをループ処理する
  2. フォントとブラシを作成する
  3. drawString() で文字列を描画する

コード例:

import com.spire.pdf.graphics.*;
import java.awt.*;

for (PdfPageBase page : (Iterable<PdfPageBase>) pdf.getPages()) {
    PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.BOLD, 36));
    PdfSolidBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.BLUE));
    page.getCanvas().drawString("Processed", font, brush, 100, 100);
}

Step 3: PDFを保存してBase64に再エンコード

編集が終わったら、PDFをメモリストリームに保存し、再度Base64文字列に変換します。これにより、ファイルとして保存せずに直接ネットワーク経由で返すことができます。

コード例:

import java.io.*;

ByteArrayOutputStream output = new ByteArrayOutputStream();
pdf.saveToStream(output);
pdf.close();

// Base64文字列に再変換
String resultBase64 = Base64.getEncoder().encodeToString(output.toByteArray());
System.out.println(resultBase64);

完全なコード例

import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.io.*;
import java.util.Base64;

public class EditBase64Pdf {
    public static void main(String[] args) throws Exception {
        String base64Pdf = "..."; // 入力Base64文字列

        // Step 1: デコードしてPDFを読み込み
        byte[] pdfBytes = Base64.getDecoder().decode(base64Pdf);
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromBytes(pdfBytes);

        // Step 2: 各ページに透かし文字を追加
        for (PdfPageBase page : (Iterable<PdfPageBase>) pdf.getPages()) {
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.BOLD, 36));
            PdfSolidBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.BLUE));
            page.getCanvas().drawString("Processed", font, brush, 100, 100);
        }

        // Step 3: 保存してBase64に変換
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        pdf.saveToStream(output);
        pdf.close();

        String resultBase64 = Base64.getEncoder().encodeToString(output.toByteArray());
        System.out.println(resultBase64);
    }
}

変更されたPDF文書:

Javaを使用してBase64経由でPDFを編集する

まとめ

本記事では、Java と Spire.PDF を利用して Base64 PDF を処理する手順を解説しました。具体的には:

  • Base64とPDFの相互変換:ネットワーク通信やファイルレス環境で便利
  • PDF編集操作:テキスト透かしや画像追加など柔軟な加工が可能
  • メモリストリーム処理:高効率で柔軟な運用ができ、API やマイクロサービスに適用可能

この方法は特に APIのPDF返却クラウド環境でのバッチ処理分散システムでの文書管理 などに有効です。

さらに詳しいチュートリアルはこちらをご覧ください:
Spire.PDF for Java チュートリアルセンター

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?