画像の大きさ(縦横の長さ)が小さくなっても画素情報は失われない。たとえば、 (1inch x 1inch) の (1000px x 1000px) の画像になる。
package com.snail.exam.printexam;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfWriter;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
public class ITextExam3 {
public static void main(String[] args) {
try {
OutputStream out = new FileOutputStream("/tmp/iTextExample3.pdf");
//ByteArrayOutputStream out = new ByteArrayOutputStream();
Document doc = new Document(PageSize.A4, 50, 50, 50, 50);
PdfWriter pdfwriter = PdfWriter.getInstance(doc, out);
Image img = createImage();
doc.open();
doc.add(new Phrase("72dpi\n\n"));
doc.add(img);
doc.newPage();
img.scalePercent(50f);
doc.add(new Phrase("144dpi\n\n"));
doc.add(img);
doc.newPage();
img.scalePercent(25f);
doc.add(new Phrase("288dpi\n\n"));
doc.add(img);
doc.newPage();
img.scalePercent(10f);
doc.add(new Phrase("720dpi\n\n"));
doc.add(img);
doc.newPage();
img.scalePercent(5f);
doc.add(new Phrase("1440dpi\n\n"));
doc.add(img);
// Document End
doc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static Image createImage() throws IOException, BadElementException{
BufferedImage image = new BufferedImage(1000, 1000, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setColor(Color.WHITE);
g.fillRect(0, 0, image.getWidth(), image.getHeight());
g.setColor(Color.GRAY);
for (int x = 0; x < image.getWidth(); x += 5) {
g.drawLine(x, 0, x, image.getHeight());
}
for (int y = 0; y < image.getHeight(); y += 5) {
g.drawLine(0, y, image.getWidth(), y);
}
g.setColor(Color.BLACK);
g.setFont(new java.awt.Font(java.awt.Font.SANS_SERIF, java.awt.Font.PLAIN, 24));
g.drawString("20pt 123 ABC あいう アイウ", 0, 20);
g.setFont(new java.awt.Font(java.awt.Font.SANS_SERIF, java.awt.Font.PLAIN, 10));
g.drawString("10pt 123 ABC あいう アイウ", 0, 40);
g.setFont(new java.awt.Font(java.awt.Font.SANS_SERIF, java.awt.Font.PLAIN, 8));
g.drawString("8pt 123 ABC あいう アイウ", 0, 60);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(image, "png", out);
return com.itextpdf.text.Image.getInstance(out.getBytes());
}
}