1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > JAVA中使用Apache Batik实现SVG文件转PDF文件导出

JAVA中使用Apache Batik实现SVG文件转PDF文件导出

时间:2024-07-13 12:45:11

相关推荐

JAVA中使用Apache Batik实现SVG文件转PDF文件导出

背景

业务中需要实现svg 编码转换为PDF或PNG文件进行导出的功能,通过查阅网上的资料,了解到Aspose.PDF和Apache 的 Batik包提供了相关的工具。两种方法都进行了尝试,最后发现Aspose导出的文件是有水印的,需要购买license才能去除水印,所以使用了Batik依赖来实现,在此做一下记录。

1.配置依赖

<dependency><groupId>org.apache.xmlgraphics</groupId><artifactId>batik-transcoder</artifactId><version>1.12</version></dependency><dependency><groupId>org.apache.xmlgraphics</groupId><artifactId>fop</artifactId><version>2.4</version></dependency>

2.代码实现

工具类

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.batik.transcoder.image.PNGTranscoder;import org.apache.fop.svg.PDFTranscoder;import java.io.*;public class SvgUtils {/*** SVG转PNG* @param svgCode SVG代码* @param out 输出流* @throws TranscoderException* @throws IOException*/public static void svg2PNG(String svgCode,OutputStream out) throws TranscoderException, IOException{Transcoder transcoder = new PNGTranscoder();svgConverte(svgCode, out, transcoder);}/*** SVG转PDF* @param svgCode SVG代码* @param out 输出流* @throws TranscoderException* @throws IOException*/public static void svg2PDF(String svgCode,OutputStream out) throws TranscoderException, IOException{Transcoder transcoder = new PDFTranscoder();svgConverte(svgCode, out, transcoder);}private static void svgConverte(String svgCode, OutputStream out, Transcoder transcoder) throws IOException, TranscoderException {svgCode = svgCode.replaceAll(":rect", "rect");TranscoderInput input = new TranscoderInput(new StringReader(svgCode));TranscoderOutput output = new TranscoderOutput(out);svgConverte(input,output,transcoder);}private static void svgConverte(TranscoderInput input, TranscoderOutput output, Transcoder transcoder) throws IOException, TranscoderException {transcoder.transcode(input, output);}}

业务代码

public void exportFloorSvg(Long floorId, HttpServletRequest request, HttpServletResponse response) throws IOException, TranscoderException {try {FloorSvg floorSvg = floorSvgRepository.selectOne(FloorSvg.builder().floorId(floorId).build());if (floorSvg==null){throw new CommonException("SVG不存在");}//解析出svg串JSON json = JSONUtil.parse(floorSvg.getSvg());String svgCode=String.valueOf(json.getByPath("floorSvg"));//文件名String fileName=floorSvg.getFileKey().substring(floorSvg.getFileKey().indexOf("@")+1,floorSvg.getFileKey().lastIndexOf(".")+1)+"pdf";//导出pdf文件 头设置response.addHeader("Content-Disposition", "attachment;filename="+ .URLEncoder.encode(fileName,"UTF-8"));response.setContentType("application/pdf");SvgUtils.svg2PDF(svgCode,response.getOutputStream()) ;}catch (Exception e){if (log.isDebugEnabled()){log.error(String.format("export pdf failed:%s",e.getMessage()));}}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。