java使用batik转换svg文件

本文介绍了一种使用Batik工具包将SVG矢量图片格式转换为PDF和PNG的方法,并提供了一个Java工具类示例,便于开发者快速实现转换功能。

svg是一种矢量图片格式,用来保存高保真的图片。我们可以用编辑器打开svg,我们可以看到svg文件其实就是一个xml文件,这种文件浏览器也可以识别。因此要查看svg用现成的浏览器就可以了。值得庆幸的是java也提供了开发包来转换svg文件,目前用的最多的是svg转pdf,jpg,png.这个开发工具包就是batik,需要的话可以直接到百度输入batik下载。

下面分享下我最近使用batik的心得

1.为了方便以后使用,我把转换的操作写成了一个工具类,如下所示

开发之前要导入batik的lib目录下面的所有jar包引入到项目中

package org.lxh;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.batik.transcoder.Transcoder;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.fop.svg.PDFTranscoder;
import org.apache.batik.transcoder.image.PNGTranscoder;

/**
 * svg转换工具类(以下方法开发足够用了)
 * @param svg
 * @param pdf
 * @throws IOException
 * @throws TranscoderException
 */
public class SvgUtil {
    //svg文件转成
	public static void convertSvgFile2Pdf(File svg, File pdf) throws IOException,TranscoderException 
	{
		InputStream in = new FileInputStream(svg);
		OutputStream out = new FileOutputStream(pdf);
		out = new BufferedOutputStream(out);
		convert2Pdf(in, out);
	}
	public static void convert2Pdf(InputStream in, OutputStream out)throws IOException, TranscoderException
	{
		Transcoder transcoder = new PDFTranscoder();
		try {
			TranscoderInput input = new TranscoderInput(in);
			try {
				TranscoderOutput output = new TranscoderOutput(out);
				transcoder.transcode(input, output);
			} finally {
				out.close();
			}
		} finally {
			in.close();
		}
	}
	//svg转为png
	public static void convertSvgFile2Png(File svg, File pdf) throws IOException,TranscoderException 
	{
		InputStream in = new FileInputStream(svg);
		OutputStream out = new FileOutputStream(pdf);
		out = new BufferedOutputStream(out);
		convert2PNG(in, out);
	}
	public static void convert2PNG(InputStream in, OutputStream out)throws IOException, TranscoderException
	{
		Transcoder transcoder = new PNGTranscoder();
		try {
			TranscoderInput input = new TranscoderInput(in);
			try {
				TranscoderOutput output = new TranscoderOutput(out);
				transcoder.transcode(input, output);
			} finally {
				out.close();
			}
		} finally {
			in.close();
		}
	}
	//字符串转成pdf
	public static void convertStr2Pdf(String svg, File pdf) throws IOException,TranscoderException 
	{
		InputStream in = new ByteArrayInputStream(svg.getBytes());
		OutputStream out = new FileOutputStream(pdf);
		out = new BufferedOutputStream(out);
		convert2Pdf(in, out);
	}
	
}

2.下面准备svg文件,这种文件可以到开发包的samples目录下面找,使用方法很简单如下所示

package org.lxh;

import java.io.File;
public class ConvertSvg {
	public static void main(String[] args) throws Exception {
		//注:使用的是svg字符串转pdf的情况可能会出现编码错误的异常,就把字符串里的UTF-8替换为GBK
        File f=new File("src/sun.svg");
        File destFile=new File("src/sun.pdf");
		SvgUtil.convertSvgFile2Pdf(f, destFile);
	}
}

来看看转换后的文件


Batik是由Apache软件基金会开发的Java库,可用于处理和渲染SVG图形,能在任何使用Java的地方操作SVG文档,也可在应用程序或Applet中生成、操作以及转换SVG图像,为使用SVG实现各种功能提供了可能[^1][^2]。以下是使用JavaBatik库实现SVG画布的一般步骤和示例代码: ### 1. 添加依赖 若使用Maven项目,需在`pom.xml`文件里添加Batik库的依赖: ```xml <dependency> <groupId>org.apache.xmlgraphics</groupId> <artifactId>batik-all</artifactId> <version>1.14</version> </dependency> ``` ### 2. 创建SVG文档 借助Batik的API创建一个新的SVG文档: ```java import org.apache.batik.dom.GenericDOMImplementation; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.Element; public class SVGCanvasExample { public static void main(String[] args) { // 获取DOM实现 DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); // 创建SVG文档 String svgNS = "http://www.w3.org/2000/svg"; Document doc = domImpl.createDocument(svgNS, "svg", null); // 获取根元素 Element svgRoot = doc.getDocumentElement(); // 设置SVG画布的宽度和高度 svgRoot.setAttribute("width", "500"); svgRoot.setAttribute("height", "500"); // 可以在这里添加更多的SVG元素,例如矩形 Element rect = doc.createElementNS(svgNS, "rect"); rect.setAttribute("x", "100"); rect.setAttribute("y", "100"); rect.setAttribute("width", "200"); rect.setAttribute("height", "200"); rect.setAttribute("fill", "blue"); // 将矩形添加到SVG根元素中 svgRoot.appendChild(rect); // 打印SVG文档内容(这里只是简单示例,实际可保存到文件) System.out.println(doc.getDocumentElement().toString()); } } ``` ### 3. 代码解释 - **获取DOM实现**:`GenericDOMImplementation.getDOMImplementation()`用于获取DOM实现,以此创建SVG文档。 - **创建SVG文档**:`domImpl.createDocument(svgNS, "svg", null)`创建一个新的SVG文档。 - **设置画布属性**:`svgRoot.setAttribute("width", "500");`和`svgRoot.setAttribute("height", "500");`设置SVG画布的宽度和高度。 - **添加SVG元素**:通过`doc.createElementNS(svgNS, "rect")`创建矩形元素,设置其属性后添加到SVG根元素中。 ### 4. 保存SVG文档 若要将生成的SVG文档保存到文件,可使用以下代码: ```java import org.apache.batik.svggen.SVGGraphics2D; import org.w3c.dom.Document; import java.io.FileWriter; import java.io.IOException; public class SaveSVGToFile { public static void saveSVGToFile(Document doc, String filePath) { try (FileWriter writer = new FileWriter(filePath)) { SVGGraphics2D svgGenerator = new SVGGraphics2D(doc); svgGenerator.stream(writer, true); } catch (IOException e) { e.printStackTrace(); } } } ``` 在`main`方法中调用`saveSVGToFile`方法: ```java SaveSVGToFile.saveSVGToFile(doc, "output.svg"); ```
评论 9
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值