Export to SVG Example

Table of Contents

Export to SVG Example

The export SVG code snippet below shows ho easy it is to convert a PDF document to the SVG file format.

The source-code for this example is located at:

A primer on using Maven or Gradle build commands can be found here (Maven) and here (Gradle)

try {

    if (pdfDocument != null &&
            (pageNumber >= 0 && pageNumber < pdfDocument.getNumberOfPages())) {
        // Get a DOMImplementation
        DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
        // Create an instance of org.w3c.dom.Document
        org.w3c.dom.Document document = domImpl.createDocument(null, "svg",
                null);
        // Create an instance of the SVG Generator
        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
        // Ask the test to render into the SVG Graphics2D implementation

        float userRotation = 0;
        float userZoom = 1;
        PDimension pdfDimension = pdfDocument.getPageDimension(pageNumber, userRotation, userZoom);
        svgGenerator.setSVGCanvasSize(pdfDimension.toDimension());
        
        // paint the page to the Batik svgGenerator graphics context. 
        pdfDocument.paintPage(pageNumber, svgGenerator,
                GraphicsRenderingHints.PRINT,
                Page.BOUNDARY_CROPBOX,
                userRotation, userZoom);

        // Finally, stream out SVG to the standard output using UTF-8
        // character to byte encoding
        boolean useCSS = true;              // we want to use CSS style attribute
        //            File f=new File("a.svg");
        //            Writer out = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
        svgGenerator.stream(out, useCSS);
    }
} catch (org.apache.batik.svggen.SVGGraphics2DIOException e) {
    logger.log(Level.SEVERE, "Error creating svg document.", e);
}

The source-code for the example is located in the [install_dir]/icepdf/examples/svg/ directory.

Tooltip
Make sure to always call document.dispose() when you are done processing a PDF document. Dispose cleans resources used by the document object.
Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.

© Copyright 2017 ICEsoft Technologies Canada Corp.