直接上代码:
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importorg.apache.batik.transcoder.Transcoder;
importorg.apache.batik.transcoder.TranscoderException;
importorg.apache.batik.transcoder.TranscoderInput;
importorg.apache.batik.transcoder.TranscoderOutput;
importorg.apache.fop.svg.PDFTranscoder;
publicclassTest{
publicstaticvoidmain(String[]argv)throwsTranscoderException,FileNotFoundException
{
Transcodertranscoder=newPDFTranscoder();
TranscoderInputtranscoderInput=newTranscoderInput(newFileInputStream(newFile("/tmp/test.svg")));
TranscoderOutputtranscoderOutput=newTranscoderOutput(newFileOutputStream(newFile("/tmp/test.pdf")));
transcoder.transcode(transcoderInput,transcoderOutput);
}
}
The compile-and-run commands arejavac-cp batik-rasterizer.jar-d buildTest.javajava-cp build:batik-rasterizer.jarTest
The important point is that TranscoderInput and TranscoderOutput can work with any InputStream and OutputStream, not just file streams. Note that one of the constructors takes a org.w3c.dom.Document, which means that you don't even need to serialize an SVG DOM into an SVG string, saving an additional step.
This version also doesn't write anything to stdout/stderr, unlike the high-level API.
For JPEG, PNG, or TIFF output, replace org.apache.fop.svg.PDFTranscoder with org.apache.batik.transcoder.p_w_picpath.JPEGTranscoder, PNGTranscoder, or TIFFTranscoder (note that these raster formats are in a different package).
(I'm not quite sure how Java finds the org.apache.batk.transcoder.* and org.apache.fop.svg.PDFTranscoder classes, since I don't see them in the batik-rasterizer.jar.)
Edit:
Although the simple commandline-compilation works with the batik-rasterizer.jar only, it's doing some sort of classloader magic to find all the necessary classes. In a more realistic case (building a project with Ant), you have to find the classes by hand. They can be found in batik-1.7.zip from the Batik project and fop-1.1.zip from the FOP project. From Batik, you need to compile with batik-transcoder.jar and run withbatik-transcoder.jar
batik-anim.jar
batik-awt-util.jar
batik-bridge.jar
batik-css.jar
batik-dom.jar
batik-ext.jar
batik-gvt.jar
batik-parser.jar
batik-script.jar
batik-svg-dom.jar
batik-util.jar
batik-xml.jar
xml-apis-ext.jar
From FOP, you need to compile with fop.jar and run withfop.jar
avalon-framework-4.2.0.jar
xmlgraphics-commons-1.5.jar