Java2D では AffineTransform クラスを駆使することでアフィン変換が可能。
既存アプリの描画処理をうまくモジュール化していれば iText の描画とうまく連携できるはず。
その連携の橋渡し部分を試してみるサンプル。
ソースコードのサンプル。
iText で AffineTransform を使って描画部分を縮小して処理する。
import java.awt.*;
import java.awt.geom.*;
import java.io.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
public class PdfGraphicsSample {
public static void main(String[] args) throws Exception{
// A4をB5に縮小してみるサンプル
com.lowagie.text.Rectangle inPageSize = PageSize.A4;
com.lowagie.text.Rectangle outPageSize = PageSize.B5;
byte[] pdf = getPDF(getShapes(inPageSize), inPageSize, outPageSize);
BufferedOutputStream bos =
new BufferedOutputStream(
new FileOutputStream("20070802_pdf_graphics_sample.pdf"));
bos.write(pdf);
bos.flush();
bos.close();
}
private static Shape[] getShapes(com.lowagie.text.Rectangle pagesize){
Shape[] s = new Shape[3];
s[0] = new Rectangle2D.Float(0,0,pagesize.getWidth(),pagesize.getHeight());
s[1] = new Line2D.Float(0,0,pagesize.getWidth(),pagesize.getHeight());
s[2] = new Line2D.Float(pagesize.getWidth(),0,0,pagesize.getHeight());
return s;
}
public static final byte[] getPDF(
Shape[] s,
com.lowagie.text.Rectangle inPageSize,
com.lowagie.text.Rectangle outPageSize) throws Exception {
System.out.println("PageSize in = " + inPageSize);
System.out.println("PageSize out = " + outPageSize);
double factorx = outPageSize.getWidth() / inPageSize.getWidth();
double factory = outPageSize.getHeight() / inPageSize.getHeight();
System.out.println("factorx = " + factorx);
System.out.println("factory = " + factory);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Document document = new Document(outPageSize);
PdfWriter writer = PdfWriter.getInstance(document, baos);
document.open();
PdfContentByte cb = writer.getDirectContent();
cb.saveState();
Graphics2D g = cb.createGraphics(outPageSize.getWidth(), outPageSize.getHeight());
g.setColor(Color.RED);
g.setStroke(new BasicStroke(10.0f));
// 縮小処理
g.setTransform(AffineTransform.getScaleInstance(factorx, factory));
for(int i=0; i<s.length; i++){
g.draw(s[i]);
}
g.dispose();
cb.restoreState();
document.close();
return baos.toByteArray();
}
}
出力結果。
PageSize in = Rectangle: 595.0x842.0 (rot: 0 degrees)
PageSize out = Rectangle: 498.0x708.0 (rot: 0 degrees)
factorx = 0.8369747996330261
factory = 0.8408551216125488
出力したPDFファイル → 20070802_pdf_graphics_sample.pdf
tags: zlashdot Java Java PDF iText
Posted by NI-Lab. (@nilab)