You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ExampleJava2D2PDF.java 7.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /* $Id$ */
  18. package embedding;
  19. import java.awt.Color;
  20. import java.awt.Dimension;
  21. import java.awt.Font;
  22. import java.awt.Graphics2D;
  23. import java.io.File;
  24. import java.io.IOException;
  25. import java.io.OutputStream;
  26. import java.io.StringReader;
  27. import javax.swing.JEditorPane;
  28. import org.apache.commons.io.IOUtils;
  29. import org.apache.xmlgraphics.util.UnitConv;
  30. import org.apache.fop.configuration.Configuration;
  31. import org.apache.fop.configuration.ConfigurationException;
  32. import org.apache.fop.configuration.DefaultConfiguration;
  33. import org.apache.fop.svg.PDFDocumentGraphics2D;
  34. import org.apache.fop.svg.PDFDocumentGraphics2DConfigurator;
  35. /**
  36. * This example class demonstrates the use of {@link PDFDocumentGraphics2D} that can be
  37. * used to create a PDF file from Java2D graphics (using the {@link Graphics2D} API).
  38. */
  39. public class ExampleJava2D2PDF {
  40. private Configuration createAutoFontsConfiguration() {
  41. //Create a default configuration using auto-detection of fonts.
  42. //This can be a bit slow but covers most use cases.
  43. DefaultConfiguration c = new DefaultConfiguration("cfg");
  44. DefaultConfiguration fonts = new DefaultConfiguration("fonts");
  45. c.addChild(fonts);
  46. DefaultConfiguration autodetect = new DefaultConfiguration("auto-detect");
  47. fonts.addChild(autodetect);
  48. return c;
  49. /* You can also load the configuration from a file:
  50. DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
  51. return cfgBuilder.buildFromFile(configFile);
  52. */
  53. }
  54. private void configure(PDFDocumentGraphics2D g2d, Configuration cfg)
  55. throws ConfigurationException {
  56. PDFDocumentGraphics2DConfigurator configurator = new PDFDocumentGraphics2DConfigurator();
  57. boolean useComplexScriptFeatures = false;
  58. configurator.configure(g2d, cfg, useComplexScriptFeatures);
  59. }
  60. /**
  61. * Creates a PDF file. The contents are painted using a Graphics2D implementation that
  62. * generates an PDF file.
  63. * @param outputFile the target file
  64. * @throws IOException In case of an I/O error
  65. * @throws ConfigurationException if an error occurs configuring the PDF output
  66. */
  67. public void generatePDF(File outputFile) throws IOException, ConfigurationException {
  68. OutputStream out = new java.io.FileOutputStream(outputFile);
  69. out = new java.io.BufferedOutputStream(out);
  70. try {
  71. //Instantiate the PDFDocumentGraphics2D instance
  72. PDFDocumentGraphics2D g2d = new PDFDocumentGraphics2D(false);
  73. g2d.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext());
  74. //Configure the G2D with the necessary fonts
  75. configure(g2d, createAutoFontsConfiguration());
  76. //Set up the document size
  77. Dimension pageSize = new Dimension(
  78. (int)Math.ceil(UnitConv.mm2pt(210)),
  79. (int)Math.ceil(UnitConv.mm2pt(297))); //page size A4 (in pt)
  80. g2d.setupDocument(out, pageSize.width, pageSize.height);
  81. g2d.translate(144, 72); //Establish some page borders
  82. //A few rectangles rotated and with different color
  83. Graphics2D copy = (Graphics2D)g2d.create();
  84. int c = 12;
  85. for (int i = 0; i < c; i++) {
  86. float f = ((i + 1) / (float)c);
  87. Color col = new Color(0.0f, 1 - f, 0.0f);
  88. copy.setColor(col);
  89. copy.fillRect(70, 90, 50, 50);
  90. copy.rotate(-2 * Math.PI / c, 70, 90);
  91. }
  92. copy.dispose();
  93. //Some text
  94. g2d.rotate(-0.25);
  95. g2d.setColor(Color.RED);
  96. g2d.setFont(new Font("sans-serif", Font.PLAIN, 36));
  97. g2d.drawString("Hello world!", 140, 140);
  98. g2d.setColor(Color.RED.darker());
  99. g2d.setFont(new Font("serif", Font.PLAIN, 36));
  100. g2d.drawString("Hello world!", 140, 180);
  101. pageSize = new Dimension(pageSize.height, pageSize.width);
  102. g2d.nextPage(pageSize.width, pageSize.height);
  103. //Demonstrate painting rich text
  104. String someHTML = "<html><body style=\"font-family:Verdana\">"
  105. + "<p>Welcome to <b>page 2!</b></p>"
  106. + "<h2>PDFDocumentGraphics2D Demonstration</h2>"
  107. + "<p>We can <i>easily</i> paint some HTML here!</p>"
  108. + "<p style=\"color:green;\">"
  109. + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin accumsan"
  110. + " condimentum ullamcorper. Sed varius quam id arcu fermentum luctus. Praesent"
  111. + " nisi ligula, cursus sed vestibulum vel, sodales sed lectus.</p>"
  112. + "</body></html>";
  113. JEditorPane htmlComp = new JEditorPane();
  114. htmlComp.setContentType("text/html");
  115. htmlComp.read(new StringReader(someHTML), null);
  116. htmlComp.setSize(new Dimension(pageSize.width - 72, pageSize.height - 72));
  117. //htmlComp.setBackground(Color.ORANGE);
  118. htmlComp.validate();
  119. htmlComp.printAll(g2d);
  120. //Cleanup
  121. g2d.finish();
  122. } finally {
  123. IOUtils.closeQuietly(out);
  124. }
  125. }
  126. /**
  127. * Main method.
  128. * @param args command-line arguments
  129. */
  130. public static void main(String[] args) {
  131. try {
  132. System.out.println("FOP " + ExampleJava2D2PDF.class.getSimpleName() + "\n");
  133. System.out.println("Preparing...");
  134. //Setup directories
  135. File baseDir = new File(".");
  136. File outDir = new File(baseDir, "out");
  137. if (!outDir.isDirectory()) {
  138. if (!outDir.mkdirs()) {
  139. throw new IOException("Could not create output directory: " + outDir);
  140. }
  141. }
  142. //Setup output file
  143. File pdffile = new File(outDir, "ResultJava2D2PDF.pdf");
  144. System.out.println("Output: PDF (" + pdffile + ")");
  145. System.out.println();
  146. System.out.println("Generating...");
  147. ExampleJava2D2PDF app = new ExampleJava2D2PDF();
  148. app.generatePDF(pdffile);
  149. System.out.println("Success!");
  150. } catch (Throwable t) {
  151. t.printStackTrace(System.err);
  152. System.exit(-1);
  153. }
  154. }
  155. }