1 package net.sourceforge.barbecue.formatter;
2
3 import net.sourceforge.barbecue.Barcode;
4 import net.sourceforge.barbecue.output.SVGOutput;
5 import net.sourceforge.barbecue.output.OutputException;
6
7 import java.io.Writer;
8 import java.io.StringWriter;
9
10 public class SVGFormatter implements BarcodeFormatter {
11 private static final String [] UNITS = {"in", "px", "cm", "mm"};
12
13 private final Writer out;
14 private String units;
15 private double scalar;
16
17 public static String formatAsSVG(Barcode barcode) throws FormattingException {
18 StringWriter writer = new StringWriter();
19 new SVGFormatter(writer).format(barcode);
20 return writer.toString();
21 }
22
23 public SVGFormatter(Writer out) {
24 this(out, 1.0 / 128, "in");
25 }
26
27 public SVGFormatter(Writer out, double scalar, String units) {
28 this.out = out;
29 setSVGScalar(scalar, units);
30 }
31
32 public void format(Barcode barcode) throws FormattingException {
33 try {
34 barcode.output(new SVGOutput(out, barcode.getFont(),
35 barcode.getForeground(), barcode.getBackground(),
36 scalar, units));
37 }
38 catch (OutputException e) {
39 throw new FormattingException(e.getMessage(), e);
40 }
41 }
42
43 public void setSVGScalar(double scalar, String units) {
44 validateUnits(units);
45 this.scalar = scalar;
46 this.units = units;
47 }
48
49 private void validateUnits(String units) {
50 boolean found = false;
51
52 for (int i = 0; i < UNITS.length; i++) {
53 if (units.equals(UNITS[i])) {
54 found = true;
55 break;
56 }
57 }
58
59 if (!found) {
60 StringBuffer buf = new StringBuffer();
61 for (int i = 0; i < UNITS.length; i++) {
62 String unit = UNITS[i];
63 if (i > 0) {
64 buf.append(", ");
65 }
66 buf.append(unit);
67 }
68 throw new IllegalArgumentException("SVG Units must be one of " + buf.toString());
69 }
70 }
71 }