1
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?

iTextで印刷時のみ出力するウォーターマークを設定

Last updated at Posted at 2019-02-20

※2020.9.25追記
iText2.1.7はLGPLだけど、なんかライセンスが怪しいらしいです。記事内容はiText5以降でも使えるかも知れないんで技術情報として残しますが、まあなんかライセンスとかそういうのはちゃんと調べて気を付けたりとかして下さいね。

印刷時のみ出力とかあるの?

はえー、PDFってそんなんもあるのね。分かりました作りましょ。PDFと言えばiText。iTextで出来ない事なんかないよ。え? リニアライズドPDFはできるのかって? うるせえな、そういうの知ってるならこんな記事読んでんじゃねーよ。

オッケー分かった早速書いてみるよ

さて日本語を使うなら、iTextAsian.jariTextAsianCmaps.jarも忘れないでね。

Watermark.java
import java.awt.Color;
import java.io.FileOutputStream;
import java.util.stream.IntStream;

import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfGState;
import com.lowagie.text.pdf.PdfLayer;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;

import lombok.val;

public class Watermark {

	public static void draw(String src, String dest) {
		try {
			val reader = new PdfReader(src);

            try(val fos = new FileOutputStream(dest)) {
				val stamp = new PdfStamper(reader, fos);

				val layer = new PdfLayer("watermark", stamp.getWriter());

				layer.setOnPanel(true);

				layer.setOn(false);
				layer.setPrint("Watermark", true);
				layer.setView(false);

				val transparent = new PdfGState();
				
				// 透明度
				transparent.setStrokeOpacity(0.3f);
				transparent.setFillOpacity(0.3f);

				val bf_courier = BaseFont.createFont("HeiseiKakuGo-W5", "UniJIS-UCS2-H", BaseFont.NOT_EMBEDDED);

				IntStream.rangeClosed(1, stamp.getReader().getNumberOfPages()).forEach(page-> {

					val cb = stamp.getOverContent(page);

					cb.setColorFill(Color.RED);

					cb.beginLayer(layer);
					cb.setGState(transparent);

					val watermarkText = "持ち出し禁止";

					val cropBox = reader.getCropBox(page);
					
					cb.beginText();
					cb.setFontAndSize(bf_courier, 20);
					
					// 斜めに適当な間隔で書いてみる
					for(int x = 0; x < cropBox.getWidth(); x += 100) {
						for(int y = 0; y < cropBox.getHeight(); y += 100) {
							cb.showTextAligned(PdfContentByte.ALIGN_CENTER, watermarkText, x, y, 45);
						}
					}
					
					cb.endText();

					cb.endLayer();
				});

				stamp.close();
			}
		} 
		catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {

		if (args.length < 2) {
			System.out.println("Usage: Watermark src.pdf dest.pdf");
			return;
		}

		Watermark.draw(args[0], args[1]);
	}
}

#こんな感じになりましたとさ
ちょっと小さくて見づらいけど、印刷プレビューにだけウォーターマークが描画されたよ。
ま、大体こんな感じ。
wmpdf.png

1
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
1
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?