wiki:Usage

Usage

To use VectorGraphics2D simply create an instance of the desired file format implementation:

  • for EPS use de.erichseifert.vectorgraphics2d.EPSGraphics2D
  • for PDF use de.erichseifert.vectorgraphics2d.PDFGraphics2D
  • for SVG use de.erichseifert.vectorgraphics2d.SVGGraphics2D

Simple geometry

For example, the following code shows how to draw a simple red ellipse into a PDF document:

import java.awt.Color;
import java.awt.Graphics2D;
import java.io.FileOutputStream;
import java.io.IOException;
import de.erichseifert.vectorgraphics2d.PDFGraphics2D;

public class EllipsePDF {
    public static void main(String[] args) throws IOException {
        // Create a new PDF document with a width of 210 and a height of 297
        PDFGraphics2D g = new PDFGraphics2D(0.0, 0.0, 210.0, 297.0);

        // Draw a red ellipse at the position (20, 30) with a width of 100 and a height of 150
        g.setColor(Color.RED);
        g.fillOval(20, 30, 100, 150);

        // Write the PDF output to a file
        FileOutputStream file = new FileOutputStream("ellipse.pdf");
        try {
            file.write(g.getBytes());
        } finally {
            file.close();
        }
    }
}

See the output: ellipse.pdf

Clipping

Here's an example of how to use a clipping path to restrict the painting area. This example fills an elliptical area with line strokes:

import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.io.FileOutputStream;
import java.io.IOException;

import de.erichseifert.vectorgraphics2d.SVGGraphics2D;

public class ClippingSVG {
    public static void main(String[] args) throws IOException {
        // Create a new PDF document with a width of 210 and a height of 297
        SVGGraphics2D g = new SVGGraphics2D(0.0, 0.0, 210.0, 297.0);

        // Only draw in a ellipse at the position (20, 30) with a width of 100 and a height of 150
        g.setClip(new Ellipse2D.Double(20.0, 30.0, 100.0, 150.0));

        // Draw lines all over the page
        for (double x = 0.0; x < 210.0; x += 2.0) {
                g.draw(new Line2D.Double(x, 0.0, x, 297.0));
        }

        // Write the SVG output to a file
        FileOutputStream file = new FileOutputStream("clipping.svg");
        try {
            file.write(g.getBytes());
        } finally {
            file.close();
        }
    }
}

See the output: clipping.svg

Last modified 7 years ago Last modified on Dec 2, 2010, 8:58:17 PM

Attachments (2)

Download all attachments as: .zip