Example usage for org.w3c.dom DOMImplementation createDocument

List of usage examples for org.w3c.dom DOMImplementation createDocument

Introduction

In this page you can find the example usage for org.w3c.dom DOMImplementation createDocument.

Prototype

public Document createDocument(String namespaceURI, String qualifiedName, DocumentType doctype)
        throws DOMException;

Source Link

Document

Creates a DOM Document object of the specified type with its document element.

Usage

From source file:edu.fullerton.viewerplugin.PluginSupport.java

/**
 * Create a Scalable Vector Graphics (SVG) file from a JFree Chart
 * @param chart the plot ready for saving
 * @param filename the output filename//from   ww w. ja  v a  2 s . c  o m
 * @throws WebUtilException 
 */
public void saveImageAsSvgFile(JFreeChart chart, String filename) throws WebUtilException {
    // THE FOLLOWING CODE BASED ON THE EXAMPLE IN THE BATIK DOCUMENTATION...
    // Get a DOMImplementation
    DOMImplementation domImpl;
    domImpl = SVGDOMImplementation.getDOMImplementation();

    // Create an instance of org.w3c.dom.Document
    Document document = domImpl.createDocument(null, "svg", null);
    // Create an instance of the SVG Generator
    SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
    // set the precision to avoid a null pointer exception in Batik 1.5
    svgGenerator.getGeneratorContext().setPrecision(6);
    // Ask the chart to render into the SVG Graphics2D implementation
    chart.draw(svgGenerator, new Rectangle2D.Double(0, 0, width, height), null);
    // Finally, stream out SVG to a file using UTF-8 character to
    // byte encoding
    boolean useCSS = true;
    Writer out;
    try {
        out = new OutputStreamWriter(new FileOutputStream(new File(filename)), "UTF-8");
        svgGenerator.stream(out, useCSS);
        out.close();
    } catch (IOException ex) {
        throw new WebUtilException("Writing SVG image", ex);
    }
}

From source file:org.nekorp.workflow.desktop.servicio.reporte.orden.servicio.OrdenServicioDataFactory.java

private String generaImagenCombustibleSVG(double porcentaje) {
    try {// w  w  w  . j a va 2s  .c  o m
        // Get a DOMImplementation.
        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 g2 = new SVGGraphics2D(document);
        int width = 186;
        int height = 15;
        g2.setSVGCanvasSize(new java.awt.Dimension(width, height));
        IndicadorBarraGraphicsView view = new IndicadorBarraGraphicsView();
        view.setWidthBar(width);
        view.setHeightBar(height);
        view.setPorcentaje(porcentaje);
        g2.setColor(Color.WHITE);
        g2.fillRect(0, 0, width, height);
        view.paint(g2);
        File file = new File("data/nivelCombustible.svg");
        try {
            g2.stream(file.getCanonicalPath());
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
        return file.getCanonicalPath();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.nekorp.workflow.desktop.servicio.reporte.orden.servicio.OrdenServicioDataFactory.java

private void generaSVGImagenDamage(ShapeView fondo, List<DamageDetailsVB> danios, File outputfile, int width,
        int height) {
    // Get a DOMImplementation.
    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 g2 = new SVGGraphics2D(document);
    // pintar.//from w ww  .  jav a  2 s. c  o  m
    g2.setSVGCanvasSize(new java.awt.Dimension(width, height));
    Point contexto = new Point((width - fondo.getShapeWidth()) / 2, (height - fondo.getShapeHeight()) / 2);
    g2.setColor(Color.WHITE);
    g2.fillRect(0, 0, width, height);
    AffineTransform saveXform = g2.getTransform();
    AffineTransform toCenterAt = new AffineTransform();
    toCenterAt.translate(contexto.getX(), contexto.getY());
    g2.transform(toCenterAt);
    fondo.paint(g2);
    g2.setTransform(saveXform);
    for (DamageDetailsVB x : danios) {
        DamageDetailGraphicsView obj = new DamageDetailGraphicsView();
        obj.setFontSize(esquemaFontSize);
        obj.setPosicion(new Point(x.getX(), x.getY()));
        obj.setContexto(contexto);
        if (x.getX() <= fondo.getShapeWidth() / 2) {
            if (x.getY() <= fondo.getShapeHeight() / 2) {
                obj.setOrientacion(DamageDetailGraphicsView.SuperiorIzquierda);
                //obj.setOrientacion(DamageDetailGraphicsView.SuperiorDerecha);
            } else {
                obj.setOrientacion(DamageDetailGraphicsView.InferiorIzquierda);
                //obj.setOrientacion(DamageDetailGraphicsView.InferiorDerecha);
            }
        } else {
            if (x.getY() <= fondo.getShapeHeight() / 2) {
                obj.setOrientacion(DamageDetailGraphicsView.SuperiorDerecha);
                //obj.setOrientacion(DamageDetailGraphicsView.SuperiorIzquierda);
            } else {
                obj.setOrientacion(DamageDetailGraphicsView.InferiorDerecha);
                //obj.setOrientacion(DamageDetailGraphicsView.InferiorIzquierda);
            }
        }
        obj.setCategoria(x.getCategoria());
        obj.setCaracteristica(x.getCaracteristica());
        obj.paint(g2);
    }
    try {
        g2.stream(outputfile.getCanonicalPath());
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:web.diva.server.model.pca.PCAImageGenerator.java

@SuppressWarnings("CallToPrintStackTrace")
public String toPdfFile(File userFolder, String url) {
    try {/*from   w  ww.j  a va  2 s .  com*/
        BufferedImage pdfImage = image;
        DOMImplementation domImpl = new SVGDOMImplementation();
        String svgNS = "http://www.w3.org/2000/svg";
        SVGDocument svgDocument = (SVGDocument) domImpl.createDocument(svgNS, "svg", null);
        SVGGraphics2D svgGenerator = new SVGGraphics2D(svgDocument);
        svgGenerator.setSVGCanvasSize(new Dimension(pdfImage.getWidth(), pdfImage.getHeight()));
        svgGenerator.setPaint(Color.WHITE);
        svgGenerator.drawImage(pdfImage, 0, 0, null);
        File pdfFile = new File(userFolder, divaDataset.getName() + "_PCA_PLOT" + ".pdf");
        if (!pdfFile.exists()) {
            pdfFile.createNewFile();
        } else {
            pdfFile.delete();
            pdfFile.createNewFile();
        }
        // write the svg file
        File svgFile = new File(pdfFile.getAbsolutePath() + ".temp");
        OutputStream outputStream = new FileOutputStream(svgFile);
        BufferedOutputStream bos = new BufferedOutputStream(outputStream);
        Writer out = new OutputStreamWriter(bos, "UTF-8");

        svgGenerator.stream(out, true /* use css */);
        outputStream.flush();
        outputStream.close();
        bos.close();
        System.gc();
        String svgURI = svgFile.toURI().toString();
        TranscoderInput svgInputFile = new TranscoderInput(svgURI);

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

        //             write as pdf
        Transcoder pdfTranscoder = new PDFTranscoder();
        pdfTranscoder.addTranscodingHint(PDFTranscoder.KEY_PIXEL_UNIT_TO_MILLIMETER, 0.084666f);
        pdfTranscoder.transcode(svgInputFile, output);
        outstream.flush();
        outstream.close();
        bos.close();
        System.gc();
        return url + userFolder.getName() + "/" + pdfFile.getName();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return "";

}

From source file:edu.ur.ir.ir_export.service.DefaultCollectionExportService.java

/**
 * Generate an xml file with the specified collections.
 * /*from w w w .  j  a  v  a 2 s  .  c o  m*/
 * @see edu.ur.dspace.export.CollectionExporter#generateCollectionXMLFile(java.io.File, java.util.Collection)
 */
public Set<FileInfo> createXmlFile(File f, Collection<InstitutionalCollection> collections,
        boolean includeChildren) throws IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;

    Set<FileInfo> allPictures = new HashSet<FileInfo>();
    String path = FilenameUtils.getPath(f.getCanonicalPath());
    if (!path.equals("")) {
        File pathOnly = new File(FilenameUtils.getFullPath(f.getCanonicalPath()));
        FileUtils.forceMkdir(pathOnly);
    }

    if (!f.exists()) {
        if (!f.createNewFile()) {
            throw new IllegalStateException("could not create file");
        }
    }

    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new IllegalStateException(e);
    }

    DOMImplementation impl = builder.getDOMImplementation();
    DOMImplementationLS domLs = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer serializer = domLs.createLSSerializer();
    LSOutput lsOut = domLs.createLSOutput();

    Document doc = impl.createDocument(null, "institutionalCollections", null);
    Element root = doc.getDocumentElement();

    FileOutputStream fos;
    OutputStreamWriter outputStreamWriter;
    BufferedWriter writer;

    try {
        fos = new FileOutputStream(f);

        try {
            outputStreamWriter = new OutputStreamWriter(fos, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e);
        }
        writer = new BufferedWriter(outputStreamWriter);
        lsOut.setCharacterStream(writer);
    } catch (FileNotFoundException e) {
        throw new IllegalStateException(e);
    }

    // create XML for the child collections
    for (InstitutionalCollection c : collections) {
        Element collection = doc.createElement("collection");

        this.addIdElement(collection, c.getId().toString(), doc);
        this.addNameElement(collection, c.getName(), doc);
        this.addDescription(collection, c.getDescription(), doc);
        this.addCopyright(collection, c.getCopyright(), doc);

        if (c.getPrimaryPicture() != null) {
            this.addPrimaryImage(collection, c.getPrimaryPicture().getFileInfo().getNameWithExtension(), doc);
            allPictures.add(c.getPrimaryPicture().getFileInfo());
        }
        Set<IrFile> pictures = c.getPictures();

        if (pictures.size() > 0) {
            Element pics = doc.createElement("pictures");
            for (IrFile irFile : pictures) {
                Element picture = doc.createElement("picture");
                this.addImage(picture, irFile.getFileInfo().getNameWithExtension(), doc);
                pics.appendChild(picture);
                allPictures.add(irFile.getFileInfo());
            }
            collection.appendChild(pics);
        }

        if (c.getLinks().size() > 0) {
            Element links = doc.createElement("links");
            for (InstitutionalCollectionLink l : c.getLinks()) {
                this.addLink(links, l, doc);
            }
            collection.appendChild(links);
        }

        if (includeChildren) {
            for (InstitutionalCollection child : c.getChildren()) {
                addChild(child, collection, doc, allPictures);
            }
        }
        root.appendChild(collection);
    }
    serializer.write(root, lsOut);

    try {
        fos.close();
        writer.close();
        outputStreamWriter.close();
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
    return allPictures;
}

From source file:be.docarch.odt2braille.PEF.java

/**
 * Converts the flat .odt filt to a .pef file according to the braille settings.
 *
 * This function/*from  w ww.j a va  2 s.com*/
 * <ul>
 * <li>uses {@link ODT} to convert the .odt file to multiple DAISY-like xml files,</li>
 * <li>uses {@link LiblouisXML} to translate these files into braille, and</li>
 * <li>recombines these braille files into one single .pef file.</li>
 * </ul>
 *
 * First, the document <i>body</i> is processed and split in volumes, then the <i>page ranges</i> are calculated
 * and finally the <i>preliminary pages</i> of each volume are processed and inserted at the right places.
 * The checker checks the DAISY-like files and the volume lengths.
 *
 */

public boolean makePEF() throws IOException, ParserConfigurationException, TransformerException,
        InterruptedException, SAXException, ConversionException, LiblouisXMLException, Exception {

    logger.entering("PEF", "makePEF");

    Configuration settings = odt.getConfiguration();

    Element[] volumeElements;
    Element sectionElement;
    File bodyFile = null;
    File brailleFile = null;
    File preliminaryFile = null;

    List<Volume> volumes = manager.getVolumes();

    String volumeInfo = capitalizeFirstLetter(
            ResourceBundle.getBundle(L10N, settings.mainLocale).getString("in")) + " " + volumes.size() + " "
            + ResourceBundle.getBundle(L10N, settings.mainLocale)
                    .getString((volumes.size() > 1) ? "volumes" : "volume")
            + "\n@title\n@pages";

    volumeElements = new Element[volumes.size()];

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setValidating(false);
    docFactory.setNamespaceAware(true);
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    DOMImplementation impl = docBuilder.getDOMImplementation();

    Document document = impl.createDocument(pefNS, "pef", null);
    Element root = document.getDocumentElement();
    root.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", pefNS);
    root.setAttributeNS(null, "version", "2008-1");

    Element headElement = document.createElementNS(pefNS, "head");
    Element metaElement = document.createElementNS(pefNS, "meta");
    metaElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:dc", "http://purl.org/dc/elements/1.1/");
    Element dcElement = document.createElementNS("http://purl.org/dc/elements/1.1/", "dc:identifier");
    dcElement.appendChild(document.createTextNode(Integer.toHexString((int) (Math.random() * 1000000)) + " "
            + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format((new Date()))));
    metaElement.appendChild(dcElement);
    dcElement = document.createElementNS("http://purl.org/dc/elements/1.1/", "dc:format");
    dcElement.appendChild(document.createTextNode("application/x-pef+xml"));
    metaElement.appendChild(dcElement);
    headElement.appendChild(metaElement);

    root.appendChild(headElement);

    int columns = pefSettings.getColumns();
    int rows = pefSettings.getRows();
    boolean duplex = pefSettings.getDuplex();
    int rowgap = pefSettings.getEightDots() ? 1 : 0;
    int beginPage = settings.getBeginningBraillePageNumber();

    if (statusIndicator != null) {
        statusIndicator.start();
        statusIndicator.setSteps(volumes.size());
        statusIndicator.setStatus(ResourceBundle.getBundle(L10N, statusIndicator.getPreferredLocale())
                .getString("statusIndicatorStep"));
    }

    for (int volumeCount = 0; volumeCount < volumes.size(); volumeCount++) {

        volumeElements[volumeCount] = document.createElementNS(pefNS, "volume");
        volumeElements[volumeCount].setAttributeNS(null, "cols", String.valueOf(columns));
        volumeElements[volumeCount].setAttributeNS(null, "rows",
                String.valueOf(rows + (int) Math.ceil(((rows - 1) * rowgap) / 4d)));
        volumeElements[volumeCount].setAttributeNS(null, "rowgap", String.valueOf(rowgap));
        volumeElements[volumeCount].setAttributeNS(null, "duplex", duplex ? "true" : "false");

        Volume volume = volumes.get(volumeCount);

        // Body section

        logger.info("Processing volume " + (volumeCount + 1) + " : " + volume.getTitle());

        if (!(volume instanceof PreliminaryVolume)) {

            bodyFile = File.createTempFile(TMP_NAME, ".daisy.body." + (volumeCount + 1) + ".xml", TMP_DIR);
            bodyFile.deleteOnExit();
            brailleFile = File.createTempFile(TMP_NAME, ".txt", TMP_DIR);
            brailleFile.deleteOnExit();

            odt.getBodyMatter(bodyFile, volume);
            liblouisXML.configure(bodyFile, brailleFile, false, beginPage);
            liblouisXML.run();

            // Read pages
            sectionElement = document.createElementNS(pefNS, "section");
            int pageCount = addPagesToSection(document, sectionElement, brailleFile, rows, columns, -1);
            volumeElements[volumeCount].appendChild(sectionElement);

            // Checker
            if (checker != null) {
                checker.checkDaisyFile(bodyFile);
            }

            // Braille page range
            volume.setBraillePagesStart(beginPage);
            volume.setNumberOfBraillePages(pageCount);
            beginPage += pageCount;

            // Print page range
            if (volume.getFrontMatter() && settings.getVolumeInfoEnabled()) {
                extractPrintPageRange(bodyFile, volume, settings);
            }
        }

        // Special symbols list
        if (volume.getSpecialSymbolListEnabled()) {
            extractSpecialSymbols(bodyFile, volume, volumeCount, settings);
        }

        // Preliminary section

        if (volume.getFrontMatter() || volume.getTableOfContent() || volume.getTranscribersNotesPageEnabled()
                || volume.getSpecialSymbolListEnabled()) {

            preliminaryFile = File.createTempFile(TMP_NAME, ".daisy.front." + (volumeCount + 1) + ".xml",
                    TMP_DIR);
            preliminaryFile.deleteOnExit();
            brailleFile = File.createTempFile(TMP_NAME, ".txt", TMP_DIR);
            brailleFile.deleteOnExit();

            odt.getFrontMatter(preliminaryFile, volume, volumeInfo);
            liblouisXML.configure(preliminaryFile, brailleFile, true,
                    volume.getTableOfContent() ? volume.getFirstBraillePage() : 1);
            liblouisXML.run();

            // Page range
            int pageCount = countPages(brailleFile, volume);
            volume.setNumberOfPreliminaryPages(pageCount);

            // Translate again with updated volume info and without volume separator marks
            brailleFile = File.createTempFile(TMP_NAME, ".txt", TMP_DIR);
            brailleFile.deleteOnExit();
            odt.getFrontMatter(preliminaryFile, volume, volumeInfo);
            liblouisXML.configure(preliminaryFile, brailleFile, false,
                    volume.getTableOfContent() ? volume.getFirstBraillePage() : 1);
            liblouisXML.run();

            // Read pages
            sectionElement = document.createElementNS(pefNS, "section");
            addPagesToSection(document, sectionElement, brailleFile, rows, columns, pageCount);
            volumeElements[volumeCount].insertBefore(sectionElement,
                    volumeElements[volumeCount].getFirstChild());

            // Checker
            if (checker != null) {
                checker.checkDaisyFile(preliminaryFile);
            }
        }

        if (statusIndicator != null) {
            statusIndicator.increment();
        }
    }

    if (checker != null) {
        checker.checkVolumes(volumes);
    }

    Element bodyElement = document.createElementNS(pefNS, "body");

    for (int volumeCount = 0; volumeCount < volumes.size(); volumeCount++) {
        bodyElement.appendChild(volumeElements[volumeCount]);
    }

    root.appendChild(bodyElement);

    document.insertBefore((ProcessingInstruction) document.createProcessingInstruction("xml-stylesheet",
            "type='text/css' href='pef.css'"), document.getFirstChild());

    OdtUtils.saveDOM(document, pefFile);

    logger.exiting("PEF", "makePEF");

    if (!validatePEF(pefFile)) {
        return false;
    }

    return true;
}

From source file:org.pentaho.platform.uifoundation.chart.JFreeChartEngine.java

/**
 * Create an SVG image file from a JFreeChart object
 * //from  ww w  .  j  a v  a2s.co m
 * @param chart
 *          The chart object to create an image from
 * @param path
 *          The path and name of the image file to create
 * @param width
 *          The width of the image in pixels
 * @param height
 *          The height of the image in pixels
 * @throws IOException
 */
private static void saveChartAsSVG(final JFreeChart chart, final String path, final int width, final int height,
        final ChartRenderingInfo info) throws IOException {
    // THE FOLLOWING CODE BASED ON THE EXAMPLE IN THE BATIK DOCUMENTATION...
    // Get a DOMImplementation
    org.w3c.dom.DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
    // Create an instance of org.w3c.dom.Document
    Document document = domImpl.createDocument(null, "svg", null); //$NON-NLS-1$
    // Create an instance of the SVG Generator
    SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
    // set the precision to avoid a null pointer exception in Batik 1.5
    svgGenerator.getGeneratorContext().setPrecision(6);
    // Ask the chart to render into the SVG Graphics2D implementation
    chart.draw(svgGenerator, new Rectangle2D.Double(0, 0, width, height), info);
    // Finally, stream out SVG to a file using UTF-8 character to byte
    // encoding
    boolean useCSS = true;
    Writer out = new OutputStreamWriter(new FileOutputStream(new File(path + ".svg")), //$NON-NLS-1$
            LocaleHelper.getSystemEncoding());
    svgGenerator.stream(out, useCSS);
}

From source file:SciTK.Plot.java

/**
 * Exports a JFreeChart to a SVG file using Apache Batik library.
 * //  ww w.jav  a2  s. co m
 * @param chart JFreeChart to export
 * @param bounds the dimensions of the viewport
 * @param svgFile the output file.
 * @throws IOException if writing the svgFile fails.
 */
protected void exportChartAsSVG(JFreeChart chart, Rectangle bounds, File svgFile) throws IOException {
    // see http://dolf.trieschnigg.nl/jfreechart/

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

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

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

    // Write svg file
    OutputStream outputStream = new FileOutputStream(svgFile);
    Writer out = new OutputStreamWriter(outputStream, "UTF-8");
    svgGenerator.stream(out, true /* use css */);

    // write and close file:                   
    outputStream.flush();
    outputStream.close();
}

From source file:com.collabnet.tracker.core.PTrackerWebServicesClient.java

private Document createNewXMLDocument(String namespace, String qualifiedTagName) {
    DocumentBuilderFactory dbf;// = DocumentBuilderFactory.newInstance();
    DocumentBuilder db;//from   w w w  .  j a  va2s . c  om
    Document doc = null;

    try {
        dbf = DocumentBuilderFactory.newInstance();
        db = dbf.newDocumentBuilder();
        DOMImplementation di = db.getDOMImplementation();

        doc = di.createDocument(namespace, qualifiedTagName, null);
    } catch (ParserConfigurationException e) {
        log(e, "could not create document");
    }
    return doc;
}

From source file:fr.inria.atlanmod.collaboro.ui.views.NotationView.java

/**
 * Builds the SVG for the corresponding notationElement. The representation is for
 * the abstract syntax element./*from  w ww. j  a va2  s  . c om*/
 * 
 * @param notationElement
 * @return
 */
public SVGDocument buildSVG(NotationElement notationElement) {
    DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
    String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
    SVGDocument doc = (SVGDocument) impl.createDocument(svgNS, "svg", null);
    buildSVG(notationElement, doc, START_X, START_Y);
    return doc;
}