1 package org.simantics.export.core.pdf;
3 import java.awt.Graphics2D;
5 import java.io.FileInputStream;
6 import java.io.FileOutputStream;
7 import java.io.IOException;
8 import java.security.KeyStore;
9 import java.security.KeyStoreException;
10 import java.security.NoSuchAlgorithmException;
11 import java.security.PrivateKey;
12 import java.security.UnrecoverableKeyException;
13 import java.security.cert.Certificate;
14 import java.security.cert.CertificateException;
15 import java.util.ArrayList;
16 import java.util.Collections;
17 import java.util.HashMap;
18 import java.util.List;
21 import org.simantics.Simantics;
22 import org.simantics.databoard.binding.mutable.Variant;
23 import org.simantics.export.core.ExportContext;
24 import org.simantics.export.core.error.ExportException;
25 import org.simantics.export.core.intf.Format;
26 import org.simantics.export.core.manager.Content;
27 import org.simantics.utils.page.MarginUtils.Margins;
28 import org.simantics.utils.page.PageDesc;
29 import org.simantics.utils.page.PageOrientation;
31 import com.lowagie.text.Document;
32 import com.lowagie.text.DocumentException;
33 import com.lowagie.text.Element;
34 import com.lowagie.text.ExceptionConverter;
35 import com.lowagie.text.Font;
36 import com.lowagie.text.PageSize;
37 import com.lowagie.text.Phrase;
38 import com.lowagie.text.Rectangle;
39 import com.lowagie.text.pdf.AcroFields;
40 import com.lowagie.text.pdf.BadPdfFormatException;
41 import com.lowagie.text.pdf.ColumnText;
42 import com.lowagie.text.pdf.FontMapper;
43 import com.lowagie.text.pdf.PdfContentByte;
44 import com.lowagie.text.pdf.PdfCopy;
45 import com.lowagie.text.pdf.PdfDictionary;
46 import com.lowagie.text.pdf.PdfFileSpecification;
47 import com.lowagie.text.pdf.PdfImportedPage;
48 import com.lowagie.text.pdf.PdfReader;
49 import com.lowagie.text.pdf.PdfSignatureAppearance;
50 import com.lowagie.text.pdf.PdfStamper;
51 import com.lowagie.text.pdf.PdfTemplate;
52 import com.lowagie.text.pdf.PdfWriter;
55 * A PDF writer object.
57 * @author toni.kalajainen@semantum.fi
59 public class ExportPdfWriter {
62 public Document document;
64 /** PDF Output stream */
65 public PdfCopy pdfCopy;
67 /** Open output stream */
68 public FileOutputStream fos;
70 /** The direct content byte of the document */
71 public PdfContentByte cb;
73 /** Contains Pdf Templates, e.g. symbols. Resource Uri -> Template mapping */
74 public Map<String, PdfTemplate> templates = new HashMap<String, PdfTemplate>();
77 public List<Page> pages = new ArrayList<Page>();
79 /** Suggested Page Desc */
80 public PageDesc defaultPageDesc;
82 /** PageDesc as PDF rectangle */
83 public Rectangle defaultRectangle;
85 /** Initialized FontMapper */
86 public FontMapper fontMapper;
88 /** The output file */
89 public File outputFile;
92 public Variant options;
95 public ExportContext ctx;
97 /** The margins the user selected. */
98 public Margins margins;
100 /** Compression Level */
101 public int compressionLevel;
106 * @param (Optional) page description. If null is used, the default size is used.
107 * @return Page for writing
108 * @throws ExportException
110 public Page createPage( PageDesc pd ) throws ExportException {
113 if ( pd == null || pd.isInfinite() ) {
114 pd = defaultPageDesc;
115 rect = defaultRectangle;
117 rect = toRectangle( pd );
120 Page page = new Page( pd, rect, pages.size() );
126 * Create a new template.
128 * Note, template is not visible on the document until you add it with
129 * cb.addTemplate( template.tp, 0, 0);
131 * @param name (Optional) Template identifier
132 * @param pd (Optional) template size description. If null is used, the default size is used.
133 * @return Template handle
134 * @throws ExportException
136 public Template createTemplate( String name, PageDesc pd ) throws ExportException {
138 if ( pd == null || pd.isInfinite() ) {
139 pd = defaultPageDesc;
140 rect = defaultRectangle;
142 rect = toRectangle( pd );
145 int w = (int) pd.getWidth();
146 int h = (int) pd.getHeight();
147 PdfTemplate tp = cb.createTemplate(w, h);
148 Template canvas = new Template( name, pd, rect, tp );
150 if ( name!=null ) templates.put(name, tp);
155 * Sign the file with a private+public key pair (PPK).
156 * The file must be closed already.
158 * @param keystoreFile the keystore file
159 * @param keystorePassword (optional) password
160 * @param privateKeyPassword (optional) password
161 * @param signLocation (optional) sign locaiton, e.g. "Helsinki"
162 * @param signReason (optional) e.g. "approved"
163 * @throws ExportException
165 public void sign( File keystoreFile, String keystorePassword, String privateKeyPassword, String signLocation, String signReason) throws ExportException {
166 // Add Bouncycastle, if found. If not, try anyway.
168 if (providerAdded.compareAndSet(false, true)) {
170 String className = "org.bouncycastle.jce.provider.BouncyCastleProvider";
171 Class<?> clazz = Class.forName(className);
172 Provider provide = (Provider) clazz.newInstance();
173 Security.addProvider( provide );
174 } catch (SecurityException se) {
175 se.printStackTrace();
176 } catch (NullPointerException npe) {
177 npe.printStackTrace();
178 } catch (ClassNotFoundException e) {
180 } catch (InstantiationException e) {
182 } catch (IllegalAccessException e) {
188 FileInputStream ksfis = null;
189 FileInputStream fis = null;
190 FileOutputStream fos = null;
191 File signedFile = null;
193 KeyStore ks = KeyStore.getInstance("pkcs12");
194 signedFile = new File( outputFile.getCanonicalPath()+".signed" );
195 if (signedFile.exists()) signedFile.delete();
196 ksfis = new FileInputStream(keystoreFile);
197 fis = new FileInputStream(outputFile);
198 fos = new FileOutputStream( signedFile );
199 ks.load(ksfis, keystorePassword != null ? keystorePassword.toCharArray() : null);
201 List<String> aliases = Collections.list(ks.aliases());
202 String alias = aliases.get(0);
203 PrivateKey key = (PrivateKey)ks.getKey(alias, privateKeyPassword != null ? privateKeyPassword.toCharArray() : null);
204 Certificate[] chain = ks.getCertificateChain(alias);
206 PdfReader reader = new PdfReader( fis );
207 PdfStamper stp = PdfStamper.createSignature(reader, fos, '\0');
208 PdfSignatureAppearance sap = stp.getSignatureAppearance();
211 String fieldName = "sign"; //signReason==null?"sign":URIUtil.encodeFilename( signReason );
212 AcroFields af = stp.getAcroFields();
213 AcroFields.Item item = af.getFieldItem(fieldName);
214 if (signReason!=null) sap.setReason( signReason );
215 if (signLocation!=null) sap.setLocation( signLocation );
216 sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);
217 sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
218 sap.setRender(PdfSignatureAppearance.SignatureRenderNameAndDescription);
220 // Make field the signature
221 //sap.setVisibleSignature(fieldName);
224 //AcroFields af = stp.getAcroFields();
225 //AcroFields.Item item = af.getFieldItem(fieldName);
226 //sap.setVisibleSignature(new Rectangle(0, 0, 100, 10), 0, fieldName);
228 // comment next line to have an invisible signature
229 //sap.setVisibleSignature(new Rectangle(682, 130, 822, 145), 1, "approved_by");
231 //stp.getAcroFields().setField(fieldName, "someValue");
236 } catch (DocumentException e) {
237 throw new ExportException( e.getClass().getName()+": "+e.getMessage(), e );
238 } catch (UnrecoverableKeyException e) {
239 throw new ExportException( e.getClass().getName()+": "+e.getMessage(), e );
240 } catch (NoSuchAlgorithmException e) {
241 throw new ExportException( e.getClass().getName()+": "+e.getMessage(), e );
242 } catch (CertificateException e) {
243 throw new ExportException( e.getClass().getName()+": "+e.getMessage(),e );
244 } catch (IOException e) {
245 throw new ExportException( e.getClass().getName()+": "+e.getMessage(), e );
246 } catch (KeyStoreException e) {
247 throw new ExportException( e.getClass().getName()+": "+e.getMessage(), e );
249 if ( ksfis != null ) try { ksfis.close(); } catch (IOException e) {}
250 if ( fis != null ) try { fis.close(); } catch (IOException e) {}
251 if ( fos != null ) try { fos.close(); } catch (IOException e) {}
253 if ( signedFile!=null && signedFile.exists() && outputFile.exists() ) {
255 signedFile.renameTo( outputFile );
261 public void addAttachment(Content content) throws ExportException {
263 if ( content.tmpFile == null ) throw new ExportException("Could not export "+content.filename+", null file.");
264 if ( !content.tmpFile.exists() ) throw new ExportException("Could not export "+content.filename+", file not found.");
266 Format format = ctx.eep.getFormat( content.formatId );
267 //byte[] data = StreamUtil.readFully( content.tmpFile );
268 PdfDictionary fileParameter = new PdfDictionary();
269 PdfFileSpecification spec = PdfFileSpecification.fileEmbedded(
271 content.tmpFile.getAbsolutePath(),
275 "application/simantics/"+format.id(),
278 pdfCopy.addFileAttachment( content.filename, spec );
281 } catch (IOException e) {
282 throw new ExportException( e.getClass().getName()+": "+e.getMessage() );
286 public void close() throws ExportException {
289 if ( pages.isEmpty() ) {
290 Page page = createPage(null);
291 Graphics2D g2d = page.createGraphics(true);
293 g2d.drawString("This page is intentionally left blank.", 100, 100);
299 for ( Page page : pages ) page.close();
301 Font f = new Font(Font.HELVETICA, 8);
306 for ( Page page : pages ) {
307 PdfReader reader = new PdfReader( page.tmpFile.getAbsolutePath() );
309 totalPages += reader.getNumberOfPages();
315 for ( Page page : pages ) {
316 PdfReader reader = new PdfReader( page.tmpFile.getAbsolutePath() );
318 int n = reader.getNumberOfPages();
320 for (int i = 0; i < n; ) {
321 Rectangle pageSize = reader.getPageSizeWithRotation(n);
323 PdfImportedPage imp = pdfCopy.getImportedPage(reader, ++i);
324 PdfCopy.PageStamp ps = pdfCopy.createPageStamp(imp);
326 PdfContentByte over = ps.getOverContent();
328 ColumnText.showTextAligned(over, Element.ALIGN_RIGHT,
330 String.format("%d / %d", currentPage++, totalPages), f),
331 pageSize.getWidth()-12, 12, 0);
333 pdfCopy.addPage(imp);
340 } catch (IOException e) {
341 throw new ExportException( e );
342 } catch (ExceptionConverter e) {
343 throw new ExportException( e );
344 } catch (BadPdfFormatException e) {
345 throw new ExportException( e );
346 } catch (Exception e) {
347 throw new ExportException( e );
349 for ( Page page : pages ) {
350 if ( page.tmpFile != null ) { page.tmpFile.delete(); page.tmpFile = null; }
354 if ( document != null ) { document.close(); document = null; }
355 if ( pdfCopy != null ) { pdfCopy.close(); pdfCopy = null; }
356 if ( fos != null ) { try {
358 } catch (IOException e) {
359 throw new ExportException(e);
366 /** PDF Output stream */
367 public PdfWriter pdfWriter;
370 public Document document;
372 /** Open output stream */
373 public FileOutputStream fos;
375 /** The direct content byte of the document */
376 public PdfContentByte cb;
378 /** Tmp-file where the page is written to */
381 /** Suggested Page Desc */
382 public PageDesc pageDesc;
384 /** PageDesc as PDF rectangle */
385 public Rectangle rectangle;
388 public int pageNumber;
390 Page(PageDesc pageDesc, Rectangle rect, int pageNumber) throws ExportException {
392 this.pageDesc = pageDesc;
393 this.rectangle = rect;
394 this.pageNumber = pageNumber;
395 this.tmpFile = Simantics.getTempfile("export.core", "pdf");
396 this.fos = new FileOutputStream( tmpFile, false );
397 this.document = new Document(rectangle);
398 this.document.setPageSize( rect ); // redundant?
399 this.pdfWriter = PdfWriter.getInstance(document, fos);
400 this.pdfWriter.setPdfVersion(PdfWriter.PDF_VERSION_1_7);
401 this.pdfWriter.setCompressionLevel( compressionLevel );
402 this.pdfWriter.setPageEvent(new ServiceBasedPdfExportPageEvent());
403 this.document.open();
404 this.cb = this.pdfWriter.getDirectContent();
405 if (!this.document.newPage()) throw new ExportException("Failed to create new page.");
406 } catch (IOException e) {
407 throw new ExportException( e );
408 } catch (DocumentException e) {
409 throw new ExportException( e );
414 * Create a graphics 2d Context that uses millimeters.
416 * @param applyMargins top left position of margins is applied
417 * @return graphics 2d context
419 public Graphics2D createGraphics(boolean applyMargins) {
420 float w = rectangle.getWidth();
421 float h = rectangle.getHeight();
422 double pw = pageDesc.getOrientedWidth();
423 double ph = pageDesc.getOrientedHeight();
424 Graphics2D g2d = cb.createGraphics(w, h, fontMapper);
426 if ( applyMargins ) {
427 Margins m = pageDesc.getMargins();
429 double mw = pw - m.left.diagramAbsolute - m.right.diagramAbsolute;
430 double mh = ph - m.top.diagramAbsolute - m.bottom.diagramAbsolute;
431 double sx = m.left.diagramAbsolute;
432 double sy = m.top.diagramAbsolute;
435 mw = PageDesc.toPoints( mw );
436 mh = PageDesc.toPoints( mh );
437 sx = PageDesc.toPoints( sx );
438 sy = PageDesc.toPoints( sy );
440 g2d.translate(sx, sy);
443 g2d.scale(w/pw, h/ph);
448 * Of area inside the margins, return the width of the page in millimeters.
452 public double getWidth() {
453 Margins m = pageDesc.getMargins();
454 return pageDesc.getOrientedWidth() - m.left.diagramAbsolute - m.right.diagramAbsolute;
457 public double getHeight() {
458 Margins m = pageDesc.getMargins();
459 return pageDesc.getOrientedHeight() - m.top.diagramAbsolute - m.bottom.diagramAbsolute;
463 * Add attachment to this page
465 * @throws ExportException
467 public void addAttachment(Content content) throws ExportException {
470 if ( content.tmpFile == null ) throw new ExportException("Could not export "+content.filename+", null file.");
471 if ( !content.tmpFile.exists() ) throw new ExportException("Could not export "+content.filename+", file not found.");
473 Format format = ctx.eep.getFormat( content.formatId );
474 //byte[] data = StreamUtil.readFully( content.tmpFile );
475 PdfDictionary fileParameter = new PdfDictionary();
476 PdfFileSpecification spec = PdfFileSpecification.fileEmbedded(
478 content.tmpFile.getAbsolutePath(),
482 "application/simantics/"+format.id(),
485 pdfWriter.addFileAttachment( content.filename, spec );
486 } catch (IOException e) {
487 throw new ExportException( e.getClass().getName()+": "+e.getMessage() );
489 ExportPdfWriter.this.addAttachment(content);
492 public void close() throws ExportException {
494 if ( document != null ) { document.close(); document = null; }
495 if ( pdfWriter != null ) { pdfWriter.close(); pdfWriter = null; }
496 if ( fos != null ) { fos.close(); fos = null; }
497 if ( cb != null ) { cb = null; }
498 } catch (IOException e) {
499 throw new ExportException(e);
505 public class Template {
507 /** Suggested Page Desc */
508 public PageDesc pageDesc;
510 /** PageDesc as PDF rectangle */
511 public Rectangle rectangle;
517 public PdfTemplate tp;
519 Template(String name, PageDesc pd, Rectangle rect, PdfTemplate tp) {
521 this.rectangle = rect;
526 public Graphics2D createGraphics() {
527 double w = pageDesc.getWidth();
528 double h = pageDesc.getHeight();
529 return tp.createGraphics((float) w, (float) h, fontMapper);
534 public static Rectangle toRectangle(PageDesc pageDesc) {
535 String arg = PageDesc.toPoints(pageDesc.getWidth()) + " " + PageDesc.toPoints(pageDesc.getHeight());
536 Rectangle r = PageSize.getRectangle(arg);
538 if (PageOrientation.Landscape == pageDesc.getOrientation())
541 // Disable inherent borders from the PDF writer.