我们如何使用java / struts2中的itext库在pdf中添加'.svg'格式化图像

时间:2015-01-20 07:20:41

标签: java struts2 itext batik

我有“.svg”格式的图片,我希望通过使用'itext'库和'batik'库来编写PDF文件,将这些图像包含在“PDF”中,'itext'仅支持jpeg / png / tiff / gif图像格式。

 try{
        PdfWriter writer = PdfWriter.getInstance(document,
        new FileOutputStream("E://svg.pdf"));
        document.open();
        document.add(new Paragraph("SVG Example"));

        int width = 250;
        int height = 250;
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate template = cb.createTemplate(width,height);         
        Graphics2D g2 = template.createGraphics(width,height);          

        PrintTranscoder prm = new PrintTranscoder();
        TranscoderInput ti = new TranscoderInput("E://firoz_trend.xml");//also tried E://firoz_trend.svg
        prm.transcode(ti, null);

        PageFormat pg = new PageFormat();
        Paper pp= new Paper();
        pp.setSize(width, height);
        pp.setImageableArea(0, 0, width, height);
        pg.setPaper(pp);
        prm.print(g2, pg, 0); 
        g2.dispose(); 

        ImgTemplate img = new ImgTemplate(template);           
        document.add(img);

  } catch (Exception e) {
     System.out.println("CreatePdf "+e);
  }

它给出了一个例外 org.apache.batik.transcoder.TranscoderException:null 附上例外: 无法理解连接的URL 请帮我这个

1 个答案:

答案 0 :(得分:1)

TranscoderInput的构造函数需要String需要一个URI,并且您传入了一个文件名,因此它失败了。

在将文件传递给构造函数之前自己打开文件:

TranscoderInput ti = new TranscoderInput(new FileInputStream("E:\\firoz_trend.svg"));

(注意,在您自己的代码中,请确保在方法结束时关闭文件以防止文件描述符泄漏)