下面列出了org.w3c.dom.DOMImplementation#createDocument ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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();
}
}
public static Document createDocument(final double width, final double height)
{
final DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
final Document doc = impl.createDocument(SVG_NS, "svg", null);
final Element root = doc.getDocumentElement();
root.setAttributeNS(null, "xmlns:xlink", XML_NS);
setAttribute(root, "width", width);
setAttribute(root, "height", height);
return doc;
}
public static void main(String[] args) throws Exception {
String format = "javax_imageio_1.0";
BufferedImage img =
new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
IIOMetadata meta =
iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), null);
DOMImplementationRegistry registry;
registry = DOMImplementationRegistry.newInstance();
DOMImplementation impl = registry.getDOMImplementation("XML 3.0");
Document doc = impl.createDocument(null, format, null);
Element root, text, entry;
root = doc.getDocumentElement();
root.appendChild(text = doc.createElement("Text"));
text.appendChild(entry = doc.createElement("TextEntry"));
// keyword isn't #REQUIRED by the standard metadata format.
// However, it is required by the PNG format, so we include it here.
entry.setAttribute("keyword", "Comment");
entry.setAttribute("value", "Some demo comment");
meta.mergeTree(format, root);
}
private String generatePipelineSvgImage( PipelineMeta pipelineMeta ) throws Exception {
float magnification = ZOOM_FACTOR;
Point maximum = pipelineMeta.getMaximum();
maximum.multiply( magnification );
DOMImplementation domImplementation = GenericDOMImplementation.getDOMImplementation();
// Create an instance of org.w3c.dom.Document.
String svgNamespace = "http://www.w3.org/2000/svg";
Document document = domImplementation.createDocument(svgNamespace, "svg", null);
HopSvgGraphics2D graphics2D = new HopSvgGraphics2D( document );
SvgGc gc = new SvgGc( graphics2D, new Point(maximum.x+100, maximum.y+100), 32, 0, 0 );
PipelinePainter pipelinePainter = new PipelinePainter( gc, pipelineMeta, maximum, null, null, null, null, null, new ArrayList<>(), 32, 1, 0, "Arial", 10, 1.0d );
pipelinePainter.setMagnification( magnification );
pipelinePainter.buildPipelineImage();
// convert to SVG
//
StringWriter stringWriter = new StringWriter();
graphics2D.stream( stringWriter, true );
return stringWriter.toString();
}
public static void main(String[] args) throws Exception {
String format = "javax_imageio_1.0";
BufferedImage img =
new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
IIOMetadata meta =
iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), null);
DOMImplementationRegistry registry;
registry = DOMImplementationRegistry.newInstance();
DOMImplementation impl = registry.getDOMImplementation("XML 3.0");
Document doc = impl.createDocument(null, format, null);
Element root, text, entry;
root = doc.getDocumentElement();
root.appendChild(text = doc.createElement("Text"));
text.appendChild(entry = doc.createElement("TextEntry"));
// keyword isn't #REQUIRED by the standard metadata format.
// However, it is required by the PNG format, so we include it here.
entry.setAttribute("keyword", "Comment");
entry.setAttribute("value", "Some demo comment");
meta.mergeTree(format, root);
}
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);
}
}
public static void main(String[] args) throws Exception {
String format = "javax_imageio_1.0";
BufferedImage img =
new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
IIOMetadata meta =
iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), null);
DOMImplementationRegistry registry;
registry = DOMImplementationRegistry.newInstance();
DOMImplementation impl = registry.getDOMImplementation("XML 3.0");
Document doc = impl.createDocument(null, format, null);
Element root, text, entry;
root = doc.getDocumentElement();
root.appendChild(text = doc.createElement("Text"));
text.appendChild(entry = doc.createElement("TextEntry"));
// keyword isn't #REQUIRED by the standard metadata format.
// However, it is required by the PNG format, so we include it here.
entry.setAttribute("keyword", "Comment");
entry.setAttribute("value", "Some demo comment");
meta.mergeTree(format, root);
}
public static void main(String[] args) throws Exception {
String format = "javax_imageio_1.0";
BufferedImage img =
new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
IIOMetadata meta =
iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), null);
DOMImplementationRegistry registry;
registry = DOMImplementationRegistry.newInstance();
DOMImplementation impl = registry.getDOMImplementation("XML 3.0");
Document doc = impl.createDocument(null, format, null);
Element root, text, entry;
root = doc.getDocumentElement();
root.appendChild(text = doc.createElement("Text"));
text.appendChild(entry = doc.createElement("TextEntry"));
// keyword isn't #REQUIRED by the standard metadata format.
// However, it is required by the PNG format, so we include it here.
entry.setAttribute("keyword", "Comment");
entry.setAttribute("value", "Some demo comment");
meta.mergeTree(format, root);
}
public SVGExporter(ExportRectangle bounds, double zoom) {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
DOMImplementation impl = docBuilder.getDOMImplementation();
DocumentType svgDocType = impl.createDocumentType("svg", "-//W3C//DTD SVG 1.0//EN",
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd");
_svg = impl.createDocument(sNamespace, "svg", svgDocType);
Element svgRoot = _svg.getDocumentElement();
svgRoot.setAttribute("xmlns:xlink", xlinkNamespace);
if (bounds != null) {
svgRoot.setAttribute("width", (bounds.getWidth() / SWF.unitDivisor) + "px");
svgRoot.setAttribute("height", (bounds.getHeight() / SWF.unitDivisor) + "px");
createDefGroup(bounds, null, zoom);
}
} catch (ParserConfigurationException ex) {
Logger.getLogger(SVGExporter.class.getName()).log(Level.SEVERE, null, ex);
}
gradients = new ArrayList<>();
}
public static void main(String[] args) throws Exception {
String format = "javax_imageio_1.0";
BufferedImage img =
new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
IIOMetadata meta =
iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), null);
DOMImplementationRegistry registry;
registry = DOMImplementationRegistry.newInstance();
DOMImplementation impl = registry.getDOMImplementation("XML 3.0");
Document doc = impl.createDocument(null, format, null);
Element root, text, entry;
root = doc.getDocumentElement();
root.appendChild(text = doc.createElement("Text"));
text.appendChild(entry = doc.createElement("TextEntry"));
// keyword isn't #REQUIRED by the standard metadata format.
// However, it is required by the PNG format, so we include it here.
entry.setAttribute("keyword", "Comment");
entry.setAttribute("value", "Some demo comment");
meta.mergeTree(format, root);
}
private static Document getDummyDocument( ) {
try {
if ( dbf == null ) {
dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware( true );
dbf.setValidating( false );
}
db = dbf.newDocumentBuilder();
DOMImplementation dim = db.getDOMImplementation();
d = dim.createDocument("http://java.sun.com/jaxp/xpath",
"dummyroot", null);
return d;
} catch ( Exception e ) {
e.printStackTrace();
}
return null;
}
@Override
public void setUp() throws Exception {
super.setUp();
DOMImplementationRegistry registry =
DOMImplementationRegistry.newInstance();
DOMImplementation domImpl = registry.getDOMImplementation(
"XML 1.0 Traversal 2.0");
String qname = "html";
String systemId = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";
String publicId = "-//W3C//DTD XHTML 1.0 Transitional//EN";
DocumentType documentType = domImpl.createDocumentType(
qname, publicId, systemId);
Document doc = domImpl.createDocument(null, null, documentType);
mq = new SimpleMessageQueue();
stack = new Html5ElementStack(doc, false, mq);
stack.open(false);
}
private static Element initXML() throws ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
DOMImplementation impl = builder.getDOMImplementation();
xmlDoc = impl.createDocument(null, "SavedMaps", null);
return xmlDoc.getDocumentElement();
}
/**
* Create a new prefs XML document.
*/
private static Document createPrefsDoc(String qname) {
try {
DOMImplementation di = DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
DocumentType dt = di.createDocumentType(qname, null, PREFS_DTD_URI);
return di.createDocument(null, qname, dt);
} catch (ParserConfigurationException e) {
throw new AssertionError(e);
}
}
private static Document createPrefsDoc( String qname ) {
try {
DOMImplementation di = DocumentBuilderFactory.newInstance().
newDocumentBuilder().getDOMImplementation();
DocumentType dt = di.createDocumentType(qname, null, PREFS_DTD_URI);
return di.createDocument(null, qname, dt);
} catch(ParserConfigurationException e) {
throw new AssertionError(e);
}
}
protected void saveWrapper() throws IOException
{
File outFile;
int returnVal = fcOut.showSaveDialog(fcOut);//fc.showOpenDialog(fc);
if (returnVal != JFileChooser.APPROVE_OPTION) return;
if(fcOut.getFileFilter().getDescription().equals
("Extensible Markup Language (.xml)"))
{
// add .xml to end of file name
// IF IT'S NOT ALREADY THERE
}
outFile = fcOut.getSelectedFile();
org.w3c.dom.Document resultDocument;
// copied from ProcessFile.setUpXML
try
{
DocumentBuilderFactory myFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder myDocBuilder = myFactory.newDocumentBuilder();
DOMImplementation myDOMImpl = myDocBuilder.getDOMImplementation();
//org.w3c.dom.Document
resultDocument =
myDOMImpl.createDocument("at.ac.tuwien.dbai.pdfwrap", "pdf-wrapper", null);
}
catch (ParserConfigurationException e)
{
e.printStackTrace();
return;
}
// make sure any text box contents are saved
wrapperGraphPanel.updateStatusBarControls();
Element docElement = resultDocument.getDocumentElement();
String granularity = "block";
if (segmentationMode == PageProcessor.PP_MERGED_LINES)
granularity = "line";
if (segmentationMode == PageProcessor.PP_LINE)
granularity = "raw-line";
docElement.setAttribute("granularity", granularity);
docElement.setAttribute("process-spaces", Boolean.toString(processSpaces));
docElement.setAttribute("process-ruling-lines", Boolean.toString(rulingLines));
docElement.setAttribute("area-based", "true");
docElement.setAttribute("output", "true");
pageDG.addAsXMLGraph
(resultDocument, docElement, false);
boolean toConsole = false;
String encoding = "UTF-8";
Writer output = null;
if( toConsole )
{
output = new OutputStreamWriter( System.out );
}
else
{
if( encoding != null )
{
output = new OutputStreamWriter(
new FileOutputStream( outFile ), encoding );
}
else
{
//use default encoding
output = new OutputStreamWriter(
new FileOutputStream( outFile ) );
}
//System.out.println("using out put file: " + outFile);
}
//System.out.println("resultDocument: " + resultDocument);
ProcessFile.serializeXML(resultDocument, output);
if( output != null )
{
output.close();
}
}
/**
* Equivalence class partitioning with state and input values orientation
* for public void setParameter(String name, Object value) throws
* DOMException, <br>
* <b>pre-conditions</b>: the root element has one CDATASection followed by
* one Text node, <br>
* <b>name</b>: cdata-sections <br>
* <b>value</b>: false. <br>
* <b>Expected results</b>: the root element has one Text node with text of
* the CDATASection and the Text node
*/
@Test
public void testCdataSections002() {
DOMImplementation domImpl = null;
try {
domImpl = DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
} catch (ParserConfigurationException pce) {
Assert.fail(pce.toString());
} catch (FactoryConfigurationError fce) {
Assert.fail(fce.toString());
}
Document doc = domImpl.createDocument("namespaceURI", "ns:root", null);
String cdataText = "CDATA CDATA CDATA";
String textText = "text text text";
CDATASection cdata = doc.createCDATASection(cdataText);
Text text = doc.createTextNode(textText);
DOMConfiguration config = doc.getDomConfig();
config.setParameter("cdata-sections", Boolean.FALSE);
Element root = doc.getDocumentElement();
root.appendChild(cdata);
root.appendChild(text);
setHandler(doc);
doc.normalizeDocument();
Node returned = root.getFirstChild();
if (returned.getNodeType() != Node.TEXT_NODE) {
Assert.fail("reurned: " + returned + ", expected: TEXT_NODE");
}
String returnedText = returned.getNodeValue();
if (!(cdataText + textText).equals(returnedText)) {
Assert.fail("reurned: " + returnedText + ", expected: \"" + cdataText + textText + "\"");
}
return; // Status.passed("OK");
}
@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();
}
/**
* 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();
}
}
/**
* Serializes the given PetriNet to PNML and returns the according Document object.
*
* @param the PetriNet
* @param tool integer indicating the tool
* @return Document object
*/
public static Document serialize(NetSystem net, int tool) throws SerializationException {
if (net == null) {
return null;
}
DocumentBuilderFactory docBFac = DocumentBuilderFactory.newInstance();
Document doc = null;
try {
DocumentBuilder docBuild = docBFac.newDocumentBuilder();
DOMImplementation impl = docBuild.getDOMImplementation();
doc = impl.createDocument("http://www.pnml.org/version-2009/grammar/pnml", "pnml", null);
} catch (ParserConfigurationException e) {
e.printStackTrace();
throw new SerializationException(e.getMessage());
}
Element root = doc.getDocumentElement();
Element netNode = doc.createElement("net");
root.appendChild(netNode);
if (!net.getId().equals(""))
netNode.setAttribute("id", net.getId());
else
netNode.setAttribute("id", "ptnet");
netNode.setAttribute("type", "http://www.pnml.org/version-2009/grammar/ptnet");
addElementWithText(doc, netNode, "name", net.getName());
Element page = doc.createElement("page");
page.setAttribute("id", "page0");
netNode.appendChild(page);
for (Place place:net.getPlaces()) {
addPlace(doc, page, net, place);
}
for (Transition trans:net.getTransitions()) {
addTransition(doc, page, trans);
}
for (Flow flow:net.getFlow()) {
addFlow(doc, page, flow);
}
if (tool == LOLA)
addFinalMarkings(doc, page, net);
return doc;
}