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

來源:互聯網
上載者:User

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:

public static void 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(0, 0, 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/

From:http://jroller.com/page/ghillert?entry=svg_and_pdf_example

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.