package org.simantics.document.linking.report.pdf; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.font.FontRenderContext; import java.io.File; import java.io.FileOutputStream; import com.lowagie.text.Document; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.PdfContentByte; import com.lowagie.text.pdf.PdfTemplate; import com.lowagie.text.pdf.PdfWriter; public class PDFPage { public PDFPageStream stream; public Graphics2D g2d; public Document document; public PdfWriter writer; public File tempFile; public PdfContentByte cb; public PdfTemplate template = null; public Font font; FontRenderContext frc; FontMetrics fm; int currentPixel = 0; int currentLine = 0; int availableLines = 0; public PDFPage(PDFPageStream stream) throws Exception{ this.stream = stream; Rectangle pageSize = stream.getPageSize(); document = new Document(pageSize); tempFile = File.createTempFile("ReportGenerator", ".pdf"); //$NON-NLS-1$ //$NON-NLS-2$ writer = PdfWriter.getInstance(document, new FileOutputStream(tempFile)); document.open(); this.cb = writer.getDirectContent(); writer.flush(); template = cb.createTemplate(pageSize.getWidth(), pageSize.getHeight()); g2d = template.createGraphics(pageSize.getWidth(), pageSize.getHeight()); g2d.translate(stream.marginLeft, stream.marginTop); g2d.setClip(0, 0, stream.contentWidth, stream.contentHeight); currentPixel = 0; currentLine = 1; setFont(stream.getDefaultFont()); } protected int getLineHeight() { return fm.getHeight(); } public boolean isOpen() { return template != null; } public void setFont(Font font) { this.font = font; g2d.setFont(font); fm = g2d.getFontMetrics(); frc = new FontRenderContext(g2d.getTransform(), true, true); estimateAvailableLines(); } protected void estimateAvailableLines() { availableLines = (int)Math.floor((stream.contentHeight-currentPixel)/getLineHeight()); } public Font getFont() { return font; } public void writeLine(String line) throws Exception{ writeLine(line, 0); } public void writeLine(String line, int x) throws Exception{ g2d.drawString(line, x, currentPixel+getLineHeight()); currentLine++; availableLines--; currentPixel += getLineHeight(); stream.checkNextPage(); } public void close() { g2d.dispose(); cb.addTemplate(template, 0, 0); template = null; document.close(); if (writer != null) writer.close(); document = null; writer = null; cb = null; g2d = null; } }