Convert SVG to PDF by using iText in Java(ZT)

http://www.cnblogs.com/hardrock/archive/2006/08/09/472143.html

 

As promised here is a very simple PDF that contains a SVG-based image. 

The SVG contains the following data:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"
>
<svg width="300" height="300" version="1.1"
 xmlns
="http://www.w3.org/2000/svg">
<rect x="40" y="20" rx="20" ry="20" width="250" height="250"
  style
="fill:red;stroke:black;stroke-width:1;"/>
</svg>
Here is the Java code:

 

publicstaticvoid main(String[] args) {

        Document document 
=new Document();
try {
            PdfWriter writer 
= PdfWriter.getInstance(document,
new FileOutputStream("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("file:///c:\\java\\svg.xml");
            prm.transcode(ti, 
null);

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

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

        } 
catch (DocumentException e) {
            System.err.println(e);
        } 
catch (IOException e) {
            System.err.println(e);
        }
        document.close();

      }

 

Keep in mind that you will need the Batik and Xerces libraries in addition to the iTExt jar file.


http://xml.apache.org/batik/
http://www.lowagie.com/iText/
http://xml.apache.org/xerces2-j/

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章