Transform XML via Java

Transform and load XML into PDF document. Use Aspose.PDF for Java to modify PDF documents programmatically

How to Transform XML with Java Library

In order to transform XML into PDF, we’ll use Aspose.PDF for Java API which is a feature-rich, powerful and easy to use conversion API for Java platform. You can download its latest version directly from Maven and install it within your Maven-based project by adding the following configurations to the pom.xml.

Repository

<repository>
    <id>AsposeJavaAPI</id>
    <name>Aspose Java AP</name>
    <url>https://releases.aspose.com/java/repo/</url>
</repository>

Dependency

<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-pdf</artifactId>
<version>version of aspose-pdf API</version>
</dependency>

Transform XML and load into PDF via Java


You need Aspose.PDF for Java to try the code in your environment.

  1. Set page parameters.
  2. Upload XSLT file.
  3. Then Load and Transform.

Transform XML into PDF - Java

This sample code shows how to transform XML into PDF File


    public class WorkingWithXML {

    private static String _dataDir = "/home/admin1/pdf-examples/Samples/";
    public static void ExampleXSLTtoPDF() throws TransformerException {
            String xslFile = _dataDir + "XMLFile1.xml", xmlFile = _dataDir +  "XSLTFile1.xslt";  
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = 
                factory.newTransformer( new StreamSource( xslFile ) );
            StreamSource xmlsource = new StreamSource( xmlFile );
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            StreamResult output = new StreamResult( baos );
            transformer.transform( xmlsource, output );
            com.aspose.pdf.HtmlLoadOptions options = new com.aspose.pdf.HtmlLoadOptions();
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            com.aspose.pdf.Document pdfDocument = new com.aspose.pdf.Document(bais, options);        
            pdfDocument.save(_dataDir + "data_xml.pdf");
    }
    }