How to convert XSL FO to XSLT template

212 Views Asked by At

Using transformToFragment, by passing XSLT and XML document, I am able to achieve the PDF For another request, I have XSL FO. Can we use XSL FO and XML document to generate the pdf? Please advice

Using transformToFragment, by passing XSLT and XML document, I am able to achieve the PDF

For another request, I have XSL FO. Can we use XSL FO and XML document to generate the pdf?

Below is the code

var AppModule = function AppModule() {}; AppModule.prototype.transformUBLAndInsertIntoFrame = function (UBL, XSLT) {

let ublStr = b64DecodeUnicode(UBL?.replaceAll("\r\n", ""));    
let xsltStylesheet = b64DecodeUnicode(XSLT?.replaceAll("\r\n", ""));

const parser = new DOMParser();
let xmlDoc = parser.parseFromString(ublStr, "text/xml");
let resultDocument = document.implementation.createHTMLDocument("PDF Preview");       
let xsltDoc = parser.parseFromString(xsltStylesheet, "application/xml");
console.log("Serialize:" + new XMLSerializer().serializeToString(xsltDoc));



    let xsltProcessor = new XSLTProcessor();
    xsltProcessor.importStylesheet(xsltDoc);
    resultDocument = xsltProcessor.transformToFragment(xmlDoc, resultDocument); 
    resultDocument = new XMLSerializer().serializeToString(resultDocument)
    .replaceAll('&', '&')
    .replaceAll('&lt;', '<') .replaceAll('&gt;','>' ) .replaceAll('&quot;','"' ) .replaceAll('&apos;',"'" ); return resultDocument; };
1

There are 1 best solutions below

1
Karsten On

Here is all the Java code you need for transforming XML to PDF, using XSL-FO with the free implementation Apache FOP.

protected static byte[] format(byte[] xml, String xslTransformationName) throws PdfFormatterException
    {
        try(
            ByteArrayInputStream is = new ByteArrayInputStream(xml);
            ByteArrayOutputStream os = new ByteArrayOutputStream())
        {
            Fop fop = FopFactory.newInstance(new File(".").toURI()).newFop(MimeConstants.MIME_PDF, os);
            StreamSource xsl = new StreamSource(
                    PdfFormatter.class.getResourceAsStream(XSL_FO_DIRECTORY + xslTransformationName));
            
            var txFactory = TransformerFactory.newInstance();
            txFactory.setURIResolver((href, base) -> {
                return new StreamSource(PdfFormatter.class.getResourceAsStream(XSL_FO_DIRECTORY + href));
            }); // Allow xsl:import from the same directory as the original XSLT.
            
            Transformer tx = txFactory.newTransformer(xsl);
            tx.setErrorListener(ERROR_LISTENER);
            
            Result result = new SAXResult(fop.getDefaultHandler());
            tx.transform(new StreamSource(is), result);
            
            return os.toByteArray();
        }
        catch(IOException | FOPException | TransformerException e)
        {
            throw new PdfFormatterException("Error converting to PDF.", e);
        }
    }

private static final ErrorListener ERROR_LISTENER = new ErrorListener()
    {
        private static final Logger LOG = LoggerFactory.getLogger(PdfFormatter.class);
        
        @Override
        public void warning(TransformerException exception) throws TransformerException
        {
            LOG.warn(exception.getMessage(), exception);
        }
        
        @Override
        public void fatalError(TransformerException exception) throws TransformerException
        {
            LOG.error(exception.getMessage(), exception);
        }
        
        @Override
        public void error(TransformerException exception) throws TransformerException
        {
            LOG.error(exception.getMessage(), exception);
        }
    };
  • The Fop object comes from Apache FOP.
  • XSL Transformations are stored within the JAR file in directory XSL_FO_DIRECTORY = "/xsl-fo"
  • Input is an XML document as byte array, result is the PDF document as byte array, too.