Search code examples
javastruts2itextbatik

How can we add '.svg' formatted image in pdf using itext library in java/struts2


I have ".svg" formatted image, I want to include those images in "PDF" by using 'itext' library and 'batik' library to write PDF file and 'itext' supports only for jpeg/png/tiff/gif image formats.

 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);
  }

It gives an exception org.apache.batik.transcoder.TranscoderException: null Enclosed Exception: Unable to make sense of URL for connection please help me for this


Solution

  • The constructor of TranscoderInput that takes a String expects a URI, and you're passing in a filename, so it fails.

    Open the file yourself before passing it to the constructor:

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

    (Note, in your own code, make sure that the file is closed at the end of your method to prevent file-descriptor leaks)