Java Code Examples for org.apache.batik.svggen.SVGGraphics2D#stream()

The following examples show how to use org.apache.batik.svggen.SVGGraphics2D#stream() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BatikUtils.java    From workcraft with MIT License 6 votes vote down vote up
private static void generateSvgGraphics(VisualModel model, OutputStream out) throws SerialisationException {
    try {
        Document doc = XmlUtils.createDocument();
        SVGGraphics2D g2d = new SVGGraphics2D(doc);
        g2d.setUnsupportedAttributes(null);
        g2d.scale(SCALE_FACTOR, SCALE_FACTOR);
        VisualGroup visualGroup = (VisualGroup) model.getRoot();
        Rectangle2D bounds = visualGroup.getBoundingBoxInLocalSpace();
        g2d.translate(-bounds.getMinX(), -bounds.getMinY());
        int canvasWidth = (int) (bounds.getWidth() * SCALE_FACTOR);
        int canvasHeight = (int) (bounds.getHeight() * SCALE_FACTOR);
        g2d.setSVGCanvasSize(new Dimension(canvasWidth, canvasHeight));
        model.draw(g2d, Decorator.Empty.INSTANCE);
        g2d.stream(new OutputStreamWriter(out, StandardCharsets.UTF_8));
        out.flush();
    } catch (ParserConfigurationException | IOException e) {
        throw new SerialisationException(e);
    }
}
 
Example 2
Source File: PlotUtils.java    From Scripts with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Exports a JFreeChart to a SVG file using the
 * <a href= "http://xmlgraphics.apache.org/batik/" target="_blank">Batik SVG
 * Toolkit</a>, bundled with Fiji. This method is taken from
 * {@literal http://dolf.trieschnigg.nl/jfreechart/}
 *
 * @param chart
 *            the <a href= "http://javadoc.imagej.net/JFreeChart/" target=
 *            "_blank">JFreeChart </a> to export.
 * @param bounds
 *            the Rectangle delimiting the boundaries within which the chart
 *            should be drawn.
 * @param file
 *            the output (destination) file.
 * @throws IOException
 *             if writing to output file fails.
 * @see #exportChartAsSVG(JFreeChart, Rectangle)
 * @see #exportChartAsPDF(JFreeChart, Rectangle)
 * @see #exportChartAsPDF(JFreeChart, Rectangle, File)
 */
public static void exportChartAsSVG(final JFreeChart chart, final Rectangle bounds, final File file)
		throws IOException {

	// Get a DOMImplementation and create an XML document
	final DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
	final org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);

	// Create an instance of the SVG Generator
	final SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

	// draw the chart in the SVG generator
	chart.draw(svgGenerator, bounds);

	// Write svg file
	final OutputStream outputStream = new FileOutputStream(file);
	final Writer out = new OutputStreamWriter(outputStream, "UTF-8");
	svgGenerator.stream(out, true /* use css */);
	outputStream.flush();
	outputStream.close();
}
 
Example 3
Source File: ParseTreeContextualMenu.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static void exportToSvg(UberTreeViewer parseTreeViewer, File file, boolean useTransparentBackground) {
    DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
    Document document = domImpl.createDocument("http://www.w3.org/2000/svg", "svg", null);
    SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

    if (!useTransparentBackground) {
        svgGenerator.setColor(JBColor.WHITE);
        svgGenerator.fillRect(0, 0, parseTreeViewer.getWidth(), parseTreeViewer.getHeight());
    }
    parseTreeViewer.paint(svgGenerator);

    try {
        svgGenerator.stream(file.getAbsolutePath(), true);
    } catch (SVGGraphics2DIOException e) {
        Logger.getInstance(ParseTreeContextualMenu.class)
                .error("Error while exporting parse tree to SVG file " + file.getAbsolutePath(), e);
    }
}
 
Example 4
Source File: FormulaParser.java    From pretty-formula with MIT License 6 votes vote down vote up
/**
 * Parses a mathematical formula like "(a+b)/c" to a pretty image and saves
 * it as an SVG file.
 * 
 * @param formula A raw formula input String.
 * @param file The SVG file to save to.
 * @throws ParseException When parsing the LaTeX formula failed.
 * @throws IOException When writing the file failed.
 * @throws DetailedParseCancellationException When parsing the raw formula to
 * LaTeX failed.
 */
public static void saveToSVG(String formula, File file)
        throws ParseException, IOException, DetailedParseCancellationException {
      String latexFormula = FormulaParser.parseToLatex(formula);
      TeXIcon icon = FormulaParser.getTeXIcon(latexFormula);
      
      DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation();
      Document document =domImpl.createDocument(
              SVGDOMImplementation.SVG_NAMESPACE_URI, "svg", null);
      SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(document);
      
      SVGGraphics2D g2 = new SVGGraphics2D(ctx, true);
      g2.setSVGCanvasSize(new Dimension(icon.getIconWidth(),icon.getIconHeight()));
      
      icon.paintIcon(null, g2, 0, 0);

      try (FileOutputStream svgs = new FileOutputStream(file)) {
         Writer out = new OutputStreamWriter(svgs, "UTF-8");
         g2.stream(out, false);
         svgs.flush();
      }
 }
 
Example 5
Source File: ShollAnalysisDialog.java    From SNT with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Exports a JFreeChart to a SVG file.
 *
 * @param chart
 *            JFreeChart to export
 * @param bounds
 *            the dimensions of the viewport
 * @param svgFile
 *            the output file.
 * @throws IOException
 *             if writing the svgFile fails.
 *
 *             This method is taken from:
 *             http://dolf.trieschnigg.nl/jfreechart/
 */
void exportChartAsSVG(final JFreeChart chart, final Rectangle bounds, final File svgFile) throws IOException {

	// Get a DOMImplementation and create an XML document
	final DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
	final Document document = domImpl.createDocument(null, "svg", null);

	// Create an instance of the SVG Generator
	final SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

	// draw the chart in the SVG generator
	chart.draw(svgGenerator, bounds);

	// Write svg file
	final OutputStream outputStream = new FileOutputStream(svgFile);
	final Writer out = new OutputStreamWriter(outputStream, "UTF-8");
	svgGenerator.stream(out, true /* use css */);
	outputStream.flush();
	outputStream.close();
}
 
Example 6
Source File: SwingExportUtil.java    From mzmine2 with GNU General Public License v2.0 6 votes vote down vote up
public static void writeToSVG(JComponent panel, File fileName) throws IOException {
  // print the panel to pdf
  int width = panel.getWidth();
  int height = panel.getWidth();
  logger.info(
      () -> MessageFormat.format("Exporting panel to SVG file (width x height; {0} x {1}): {2}",
          width, height, fileName.getAbsolutePath()));

  // Get a DOMImplementation
  DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation();
  org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
  SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
  svgGenerator.setSVGCanvasSize(new Dimension(width, height));
  panel.print(svgGenerator);

  boolean useCSS = true; // we want to use CSS style attribute

  try (Writer out = new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8")) {
    svgGenerator.stream(out, useCSS);
  }
}
 
Example 7
Source File: SVGExporter.java    From MogwaiERDesignerNG with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void fullExportToStream(ERDesignerGraph aGraph, OutputStream aStream) throws IOException {
    Object[] cells = aGraph.getRoots();
    Rectangle2D bounds = aGraph.toScreen(aGraph.getCellBounds(cells));
    if (bounds != null) {
        DOMImplementation theDomImpl = SVGDOMImplementation.getDOMImplementation();
        String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
        Document theDocument = theDomImpl.createDocument(svgNS, "svg", null);
        SVGGraphics2D theSvgGenerator = new SVGGraphics2D(theDocument);
        theSvgGenerator.translate(-bounds.getX() + 10, -bounds.getY() + 0);
        RepaintManager theRepaintManager = RepaintManager.currentManager(aGraph);
        theRepaintManager.setDoubleBufferingEnabled(false);
        boolean theDoubleBuffered = aGraph.isDoubleBuffered();
        // Disable double buffering to allow Batik to render svg elements
        // instead of images
        aGraph.setDoubleBuffered(false);
        aGraph.paint(theSvgGenerator);
        aGraph.setDoubleBuffered(theDoubleBuffered);
        Writer theWriter = new OutputStreamWriter(aStream, PlatformConfig.getXMLEncoding());
        theSvgGenerator.stream(theWriter, false);
        theRepaintManager.setDoubleBufferingEnabled(true);

        theWriter.flush();
        theWriter.close();
    }
}
 
Example 8
Source File: IDSrendService.java    From han3_ji7_tsoo1_kian3 with GNU Affero General Public License v3.0 6 votes vote down vote up
public void 字組成svg(String 組字式, OutputStream 輸出檔案)
		throws UnsupportedEncodingException, SVGGraphics2DIOException
{
	DOMImplementation domImpl = GenericDOMImplementation
			.getDOMImplementation();

	// Create an instance of org.w3c.dom.Document.
	String svgNS = "http://www.w3.org/2000/svg";
	Document document = domImpl.createDocument(svgNS, "svg", null);

	boolean useCSS = true; // we want to use CSS style
							// attributes
	// Create an instance of the SVG Generator.
	SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
	svgGenerator.setSVGCanvasSize(new Dimension(字型大細, 字型大細));
	組字(組字式, svgGenerator);
	OutputStreamWriter svgOutput = new java.io.OutputStreamWriter(輸出檔案,
			"UTF-8");
	svgGenerator.stream(svgOutput, useCSS);
	return;
}
 
Example 9
Source File: Export.java    From PDV with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Export component to pdf format
 * @param component Component
 * @param bounds Rectangle
 * @param exportFile Export file
 * @throws IOException
 * @throws TranscoderException
 */
private static void exportSVG(Component component, Rectangle bounds, File exportFile) throws IOException, TranscoderException {

    DOMImplementation domImplementation = SVGDOMImplementation.getDOMImplementation();
    String svgNS = "http://www.w3.org/2000/svg";
    SVGDocument svgDocument = (SVGDocument) domImplementation.createDocument(svgNS, "svg", null);

    SVGGraphics2D svgGraphics2D = new SVGGraphics2D(svgDocument);
    svgGraphics2D.setSVGCanvasSize(bounds.getSize());

    component.paintAll(svgGraphics2D);

    if (new File(exportFile.getAbsolutePath() + ".temp").exists()) {
        new File(exportFile.getAbsolutePath() + ".temp").delete();
    }

    OutputStream outputStream = new FileOutputStream(exportFile);
    BufferedOutputStream bos = new BufferedOutputStream(outputStream);
    Writer out = new OutputStreamWriter(bos, "UTF-8");

    svgGraphics2D.stream(out, true);
    outputStream.flush();
    outputStream.close();
    out.close();
    bos.close();
}
 
Example 10
Source File: SwingExportUtil.java    From mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
public static void writeToSVG(JComponent panel, File fileName) throws IOException {
  // print the panel to pdf
  int width = panel.getWidth();
  int height = panel.getWidth();
  logger.info(
      () -> MessageFormat.format("Exporting panel to SVG file (width x height; {0} x {1}): {2}",
          width, height, fileName.getAbsolutePath()));

  // Get a DOMImplementation
  DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation();
  org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
  SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
  svgGenerator.setSVGCanvasSize(new Dimension(width, height));
  panel.print(svgGenerator);

  boolean useCSS = true; // we want to use CSS style attribute

  try (Writer out = new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8")) {
    svgGenerator.stream(out, useCSS);
  }
}
 
Example 11
Source File: SVGExporter.java    From MogwaiERDesignerNG with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void exportToStream(Component aComponent, OutputStream aStream) throws IOException {
    DOMImplementation theDomImpl = GenericDOMImplementation.getDOMImplementation();
    Document theDocument = theDomImpl.createDocument(null, "svg", null);
    SVGGraphics2D theSvgGenerator = new SVGGraphics2D(theDocument);
    RepaintManager theRepaintManager = RepaintManager.currentManager(aComponent);
    theRepaintManager.setDoubleBufferingEnabled(false);

    Dimension theSize = aComponent.getPreferredSize();
    aComponent.setSize(theSize);

    aComponent.paint(theSvgGenerator);
    Writer theWriter = new OutputStreamWriter(aStream, PlatformConfig.getXMLEncoding());
    theSvgGenerator.stream(theWriter, false);
    theRepaintManager.setDoubleBufferingEnabled(true);

    theWriter.flush();
    theWriter.close();
}
 
Example 12
Source File: GraphicsParser.java    From tephra with MIT License 5 votes vote down vote up
private void save(SVGGraphics2D svgGraphics2D, double x, double y, double width, double height) throws IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    Element root = svgGraphics2D.getRoot();
    root.setAttribute("viewBox", "0 0 " + width + " " + height);
    svgGraphics2D.stream(root, new OutputStreamWriter(outputStream, StandardCharsets.UTF_8), false, false);
    svgGraphics2D.dispose();
    outputStream.flush();
    outputStream.close();

    ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toString().trim()
            .replaceAll("\\s+", " ")
            .replaceAll(" >", ">")
            .replaceAll("> <", "><")
            .replaceAll("<g [^>]+></g>", "").getBytes());
    String url = mediaWriter.write(MediaType.Svg, "geometry.svg", inputStream);
    inputStream.close();
    if (url == null)
        return;

    JSONObject object = new JSONObject();
    object.put("geometry", url);
    JSONObject anchor = new JSONObject();
    anchor.put("x", pdfHelper.pointToPixel(x));
    anchor.put("y", pdfHelper.pointToPixel(y));
    anchor.put("width", pdfHelper.pointToPixel(width));
    anchor.put("height", pdfHelper.pointToPixel(height));
    object.put("anchor", anchor);
    array.add(object);
}
 
Example 13
Source File: GeometryImpl.java    From tephra with MIT License 5 votes vote down vote up
private void parseGeometry(ReaderContext readerContext, XSLFSimpleShape xslfSimpleShape, JSONObject shape) throws IOException {
    SVGGraphics2D svgGraphics2D = new SVGGraphics2D(GenericDOMImplementation.getDOMImplementation()
            .createDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, "svg", null));
    Rectangle2D rectangle2D = xslfSimpleShape.getAnchor();
    xslfSimpleShape.draw(svgGraphics2D, new Rectangle2D.Double(0.0D, 0.0D, rectangle2D.getWidth(), rectangle2D.getHeight()));
    Element root = svgGraphics2D.getRoot();
    double[] viewBox = getViewBox(xslfSimpleShape);
    root.setAttribute("viewBox", "0 0 " + (viewBox == null ? (rectangle2D.getWidth() + " " + rectangle2D.getHeight())
            : (viewBox[0] + " " + viewBox[1])));

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    svgGraphics2D.stream(root, new OutputStreamWriter(outputStream, StandardCharsets.UTF_8), false, false);
    svgGraphics2D.dispose();
    outputStream.flush();
    outputStream.close();

    String svg = outputStream.toString().trim()
            .replaceAll("\\s+", " ")
            .replaceAll(" >", ">")
            .replaceAll("> <", "><")
            .replaceAll("<text [^>]+>[^<]*</text>", "")
            .replaceAll("<g [^>]+></g>", "");
    if (!svg.contains("<path "))
        return;

    ByteArrayInputStream inputStream = new ByteArrayInputStream(svg.getBytes());
    String geometry = readerContext.getMediaWriter().write(MediaType.Svg, "geometry.svg", inputStream);
    inputStream.close();

    shape.put("geometry", geometry);
}
 
Example 14
Source File: RenderUtils.java    From swcv with MIT License 5 votes vote down vote up
public static byte[] createSVG(WordCloudRenderer renderer, SVGTextStyleHandler styleHandler)
{
    // Create an instance of org.w3c.dom.Document.
    DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation();
    Document document = domImpl.createDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, "svg", null);

    // Configure the SVGGraphics2D
    SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(document);
    ctx.setStyleHandler(styleHandler);
    SVGGraphics2D svgGenerator = new SVGGraphics2D(ctx, false);

    // rendering the cloud
    renderer.render(svgGenerator);

    SVGSVGElement root = (SVGSVGElement)svgGenerator.getRoot();
    styleHandler.postRenderAction(root);

    try
    {
        Writer writer = new StringWriter();
        svgGenerator.stream(root, writer);
        writer.close();

        return writer.toString().getBytes("UTF-8");
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
}
 
Example 15
Source File: WordCloudMenuBar.java    From swcv with MIT License 5 votes vote down vote up
private void exportSVG(final JPanel panel, String selectedFile)
{
    // Create an instance of org.w3c.dom.Document.
    DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation();
    Document document = domImpl.createDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, "svg", null);

    // Create an instance of the SVG Generator.
    SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

    // Ask to render into the SVG Graphics2D implementation.
    if (panel instanceof FlexWordlePanel)
        ((FlexWordlePanel)panel).draw(svgGenerator, panel.getWidth(), panel.getHeight());
    else
        panel.paint(svgGenerator);

    // Finally, stream out SVG to the standard output using
    // UTF-8 encoding.
    boolean useCSS = true; // we want to use CSS style attributes
    Writer out;
    try
    {
        out = new OutputStreamWriter(new FileOutputStream(selectedFile), "UTF-8");
        svgGenerator.stream(out, useCSS);
        out.close();
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
}
 
Example 16
Source File: FlexWordCloudTest.java    From swcv with MIT License 5 votes vote down vote up
private static void buildSVG(String selectedFile)
{
    FlexWordlePanel panel = new FlexWordlePanel();
    // Get a DOMImplementation.
    DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation();
    Document document = domImpl.createDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, "svg", null);

    // Create an instance of the SVG Generator.
    SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

    // Ask to render into the SVG Graphics2D implementation.
    panel.draw(svgGenerator, 1024, 768);

    // Finally, stream out SVG to the standard output using
    // UTF-8 encoding.
    boolean useCSS = true; // we want to use CSS style attributes
    Writer out;
    try
    {
        out = new OutputStreamWriter(new FileOutputStream(selectedFile), "UTF-8");
        svgGenerator.stream(out, useCSS);
        out.close();
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
}
 
Example 17
Source File: SVGEmitter.java    From maze-harvester with GNU General Public License v3.0 5 votes vote down vote up
public void emit(SegmentPainter painter) throws IOException {
  DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();

  // Create an instance of org.w3c.dom.Document.
  String svgNS = "http://www.w3.org/2000/svg";
  Document document = domImpl.createDocument(svgNS, "svg", null);

  // Create an instance of the SVG Generator.
  SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
  SegmentSorter segmentSorter = new SegmentSorter();
  segmentSorter.collect(painter);

  computeBounds(segmentSorter.getBounds());
  svgGenerator.setSVGCanvasSize(
    new Dimension((int) paperSizePixels.getX(), (int) paperSizePixels.getY()));

  // white background (before the maze-coordinates transform)
  svgGenerator.setPaint(Color.WHITE);
  svgGenerator.fill(
      new Rectangle2D.Double(
          0, 0, paperSizePixels.getX(), paperSizePixels.getY()));

  // Set up the page transform so painters can paint in their
  // Room/Door coordinate system.
  svgGenerator.scale(scalePixelsPerRoom, scalePixelsPerRoom);
  svgGenerator.translate(-pageOffsetRooms.getX(), -pageOffsetRooms.getY());

  // Paint segments into the SVG
  segmentSorter.paint(svgGenerator);

  // Finally, stream out SVG to the standard output using
  // UTF-8 encoding.
  boolean useCSS = true; // we want to use CSS style attributes
  OutputStream outputStream = new FileOutputStream(outputFilename);
  Writer out = new OutputStreamWriter(outputStream, "UTF-8");
  svgGenerator.stream(out, useCSS);
}
 
Example 18
Source File: AbstractSvgTest.java    From jasperreports with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
protected void export(JasperPrint print, OutputStream out) throws JRException, IOException
{
	DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
	Document document = domImpl.createDocument(null, "svg", null);
	SVGGraphics2D grx = 
		new SVGGraphics2D(
			SVGGeneratorContext.createDefault(document), 
			false // this is for textAsShapes, but does not seem to have effect in our case
			);
	
	JRGraphics2DExporter exporter = new JRGraphics2DExporter();
	
	exporter.setExporterInput(new SimpleExporterInput(print));
	SimpleGraphics2DExporterOutput output = new SimpleGraphics2DExporterOutput();
	Graphics2D g = (Graphics2D)grx.create();
	output.setGraphics2D(g);
	exporter.setExporterOutput(output);
	
	for (int pageIndex = 0; pageIndex < print.getPages().size(); pageIndex++)
	{
		g.translate(0,  pageIndex * print.getPageHeight());
		
		SimpleGraphics2DReportConfiguration configuration = new SimpleGraphics2DReportConfiguration();
		configuration.setPageIndex(pageIndex);
		exporter.setConfiguration(configuration);

		exporter.exportReport();
	}
	
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	// use OutputStreamWriter instead of StringWriter so that we have "encoding" attribute in <xml> header tag.
	grx.stream(new OutputStreamWriter(baos, "UTF-8"), true);
	
	SVGTranscoder transcoder = new SVGTranscoder();
	transcoder.addTranscodingHint(SVGTranscoder.KEY_NEWLINE, SVGTranscoder.VALUE_NEWLINE_LF);
	try
	{
		transcoder.transcode(
			new TranscoderInput(new InputStreamReader(new ByteArrayInputStream(baos.toByteArray()), "UTF-8")), 
			new TranscoderOutput(new OutputStreamWriter(out, "UTF-8"))
			);
	}
	catch (TranscoderException e)
	{
		throw new JRException(e);
	}
	
	out.close();
}
 
Example 19
Source File: Export.java    From PDV with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Export component to pdf format
 * @param component Component
 * @param bounds Rectangle
 * @param exportFile Export file
 * @throws IOException
 * @throws TranscoderException
 */
private static void exportPDF(Component component, Rectangle bounds, File exportFile) throws IOException, TranscoderException {

    DOMImplementation domImplementation = SVGDOMImplementation.getDOMImplementation();
    String svgNS = "http://www.w3.org/2000/svg";
    SVGDocument svgDocument = (SVGDocument) domImplementation.createDocument(svgNS, "svg", null);

    SVGGraphics2D svgGraphics2D = new SVGGraphics2D(svgDocument);
    svgGraphics2D.setSVGCanvasSize(bounds.getSize());

    component.paintAll(svgGraphics2D);

    if (new File(exportFile.getAbsolutePath() + ".temp").exists()) {
        new File(exportFile.getAbsolutePath() + ".temp").delete();
    }

    File svgFile = new File(exportFile.getAbsolutePath() + ".temp");

    OutputStream outputStream = new FileOutputStream(svgFile);
    BufferedOutputStream bos = new BufferedOutputStream(outputStream);
    Writer out = new OutputStreamWriter(bos, "UTF-8");

    svgGraphics2D.stream(out, true);
    outputStream.flush();
    outputStream.close();
    out.close();
    bos.close();

    String svgURI = svgFile.toURI().toString();
    TranscoderInput svgInputFile = new TranscoderInput(svgURI);

    OutputStream outstream = new FileOutputStream(exportFile);
    bos = new BufferedOutputStream(outstream);
    TranscoderOutput output = new TranscoderOutput(bos);

    Transcoder pdfTranscoder = new PDFTranscoder();
    pdfTranscoder.addTranscodingHint(PDFTranscoder.KEY_DEVICE_RESOLUTION, (float) Toolkit.getDefaultToolkit().getScreenResolution());
    pdfTranscoder.transcode(svgInputFile, output);

    outstream.flush();
    outstream.close();
    bos.close();

    if (svgFile.exists()) {
        svgFile.delete();
    }

}
 
Example 20
Source File: Export.java    From PDV with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Exports the selected file to the selected format.
 * @param exportFile Output file
 * @param imageType Image type
 * @param svgGraphics2D SVGGraphics2D
 */
private static void exportExceptedFormatPic(File exportFile, ImageType imageType, SVGGraphics2D svgGraphics2D)
        throws IOException, TranscoderException {

    DecimalFormat df = new DecimalFormat("#.000000");

    if (new File(exportFile.getAbsolutePath() + ".temp").exists()) {
        new File(exportFile.getAbsolutePath() + ".temp").delete();
    }

    File svgFile = exportFile;

    if (imageType != ImageType.SVG) {
        svgFile = new File(exportFile.getAbsolutePath() + ".temp");
    }

    OutputStream outputStream = new FileOutputStream(svgFile);
    BufferedOutputStream bos = new BufferedOutputStream(outputStream);
    Writer out = new OutputStreamWriter(bos, "UTF-8");

    svgGraphics2D.stream(out, true);
    outputStream.flush();
    outputStream.close();
    //out.close();
    bos.close();

    if (imageType != ImageType.SVG) {
        String svgURI = svgFile.toURI().toString();
        TranscoderInput svgInputFile = new TranscoderInput(svgURI);

        OutputStream outstream = new FileOutputStream(exportFile);
        bos = new BufferedOutputStream(outstream);
        TranscoderOutput output = new TranscoderOutput(bos);

        if (imageType == ImageType.PDF) {

            Transcoder pdfTranscoder = new PDFTranscoder();
            pdfTranscoder.addTranscodingHint(PDFTranscoder.KEY_DEVICE_RESOLUTION, (float) Toolkit.getDefaultToolkit().getScreenResolution());
            pdfTranscoder.transcode(svgInputFile, output);

        } else if (imageType == ImageType.JPEG) {

            Transcoder tiffTranscoder = new TIFFTranscoder();
            tiffTranscoder.addTranscodingHint(TIFFTranscoder.KEY_PIXEL_UNIT_TO_MILLIMETER, new Float(df.format(25.4 / Toolkit.getDefaultToolkit().getScreenResolution())));
            tiffTranscoder.addTranscodingHint(TIFFTranscoder.KEY_FORCE_TRANSPARENT_WHITE, true);
            tiffTranscoder.transcode(svgInputFile, output);

        } else if (imageType == ImageType.PNG) {

            Transcoder pngTranscoder = new PNGTranscoder();
            pngTranscoder.addTranscodingHint(PNGTranscoder.KEY_PIXEL_UNIT_TO_MILLIMETER, new Float(df.format(25.4 / Toolkit.getDefaultToolkit().getScreenResolution())));
            pngTranscoder.transcode(svgInputFile, output);

        } else if (imageType == ImageType.SVG) {

        }

        outstream.flush();
        outstream.close();
        bos.close();

        if (svgFile.exists()) {
            svgFile.delete();
        }
    }
}