1

I have a requirement to convert XML to HTML document. Am trying to convert XML to HTML with the help of XSLT. In my XSLT i have few charaters like é & while parsing into HTML document its giving below error.

The entity "eacute" was referenced, but not declareded for é.

The entity "euro" was referenced, but not declareded. for

Please find my XSLT file

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/receipt">
    <html>
        <head>
        </head>
        <body>
            <table style="width: 100%;">
                <tr>
                    <td style="text-align: center; width: 25%;">
                    </td>
                    <td style="font-size: 12px; vertical-align: top; width: 25%;">

                        46-68 Kléber<br/>
                        Tél: +1 <br/>
                        Fax: +1
                    </td>
                    <td style="font-size: 12px; vertical-align: top; width: 25%;">
                        725 € <br />

                    </td>
                    <td style="text-align: center; width: 25%;">Date <xsl:value-of select="date" /></td>
                </tr>
            </table>
        </body>
    </html>
</xsl:template>
</xsl:stylesheet>

Am writting Java code for XML to HTML parsing. Please find my code below.

public static StringWriter getOrderAcknowledgementPDF(JSONObject obj) throws IOException, DocumentException
{

     StringBuilder xml = new StringBuilder();
     String header="<?xml version=\"1.0\" encoding=\"UTF-8\"?>";

            StringBuilder sb = new StringBuilder();
            sb.append(header);
            JSONObject json = new JSONObject(obj.toString());
            xml.append(header);
            xml.append("\n");
            xml.append("<delivery_receipt>");
            xml.append(XML.toString(json));
            xml.append("</delivery_receipt>");


        System.out.println("XML--->"+xml);

        Transformer transformer;
        try {
            transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(new File("D:/Phase2/UAT_Phase/Order_Acknowledgement/template.xsl")));
        } catch (TransformerConfigurationException | TransformerFactoryConfigurationError e1) {
            throw ExceptionUtils.handle((Exception) e1);
        }
        StringWriter sw = new StringWriter();
        try {
            transformer.transform(new StreamSource(new ByteArrayInputStream(xml.toString().getBytes("UTF-8"))), new StreamResult(sw));
        } catch (TransformerException e) {
            throw ExceptionUtils.handle(e);
        }
        return sw;
}


protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

try {
        String orderid=req.getParameter("item");    
        String reportname = "OrderAcknowledgement"; 
        resp.setHeader("Content-Disposition", "attachment; filename=" + reportname + ".pdf");

        StringWriter result = service.getOrderAcknowledgementPDF(orderid);
        File file = File.createTempFile("Order_Acknowledgement-", ".pdf");
        ITextRenderer renderer = new ITextRenderer();
        try {
            renderer.getFontResolver().addFont("C:/WINDOWS/FONTS/ARIAL.TTF", true);
        } catch (DocumentException e) {
            throw ExceptionUtils.handle(e);
        }
        String fileNameWithPath = "D:/" + "PDF-FromHtmlString.pdf";
        String str=result.toString().replace("<META http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">", "<META http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />");
         str=str.replace("<br>", "<br />");
        System.out.println("after replacing....-->"+str);
        XMLResource res = XMLResource.load(new StringReader("<html><head><style>@page { size : 45cm 30cm; }</style></head><body>"+str + "</body></html>"));
        resp.setContentType("application/pdf");
        org.w3c.dom.Document doc2 = res.getDocument();
        renderer.setDocument(doc2, "file:/C:/");
        renderer.layout();
        if(fileNameWithPath != null)
        {
              resp.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", fileNameWithPath));
        }

        OutputStream browserStream = resp.getOutputStream();
        renderer.createPDF(browserStream);
    }
}

Am getting error in the below line :

 XMLResource res = XMLResource.load(new StringReader("<html><head><style>@page { size : 45cm 30cm; }</style></head><body>"+str + "</body></html>"));
9
  • For which line of your Java code do you get that error? Are you sure it is not the XML input giving the error and having entity references? The XSLT you have inserted in your description seems to have literal characters and no entity references so that XSLT does not explain the error you have shown. Commented Apr 14, 2018 at 8:16
  • @MartinHonnen - Placed my whole java code. Am parsing XML to HTML and creating pdf out of it am download that created PDF file. In this code am getting error on XMLResource res = XMLResource.load(new StringReader("<html><head><style>@page { size : 45cm 30cm; }</style></head><body>"+str + "</body></html>")); line. Commented Apr 14, 2018 at 8:40
  • 1
    Where is the variable named result in your Java code declared and initialized? And it looks as if the error is not related to XSLT but rather occurs when you try to feed the HTML result of your XSLT transformation as XML to XMLResource. I don't know that class but its name suggests it is for parsing XML and not HTML. Commented Apr 14, 2018 at 9:18
  • @MartinHonnen - I have reformated my code. Placed full code now, due to more number of lines only i have cut short few lines of code. Actual requirement is to make PDF out of JSON object. so, I parsed JSON to XML first (parsed successfully). then, XML to HTML using XSL ( not able to parse with é & characters without this characters am able to parse and PDF also generating without any issue) Commented Apr 14, 2018 at 9:39
  • 1
    Well, you have to check the documentation of XMLResource then whether it allows to load HTML instead of XML if you want to go that route. Currently your XSLT creates HTML output and with that html output method the Transformer can produce the HTML entity references. Of course you can avoid the hassle of needing to convert the HTML output back to XML by simply using a stylesheet that uses <xsl:output method="xml"/>, perhaps additionally using the XHTML namespace <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml">. Commented Apr 14, 2018 at 10:58

1 Answer 1

2

Try to change the XSLT to create XHTML with e.g.

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:template match="/receipt">
    <html>
        <head>
        </head>
        <body>
            <table style="width: 100%;">
                <tr>
                    <td style="text-align: center; width: 25%;">
                    </td>
                    <td style="font-size: 12px; vertical-align: top; width: 25%;">

                        46-68 Kléber<br/>
                        Tél: +1 <br/>
                        Fax: +1
                    </td>
                    <td style="font-size: 12px; vertical-align: top; width: 25%;">
                        725 € <br />

                    </td>
                    <td style="text-align: center; width: 25%;">Date <xsl:value-of select="date" /></td>
                </tr>
            </table>
        </body>
    </html>
</xsl:template>
</xsl:stylesheet>

then instead of using a StringWriter and a StreamResult use a

DOMResult result = new DOMResult();

use that as the transformation result e.g.

transformer.transform(new StreamSource(new ByteArrayInputStream(xml.toString().getBytes("UTF-8"))), result);

and then you can feed Document resultDoc = result.getNode() to your

renderer.setDocument(resultDoc, ...); 

That should avoid the problem with entity references, I don't know how the renderer you use works with XHTML so there might be better ways to use that API, but based on the approach you have shown so far my suggestion at least might solve the error you get.

Sign up to request clarification or add additional context in comments.

3 Comments

Document resultDoc = result.getNode() is not working, throwing The method getNode() is undefined for the type Result error
See the edit and use DOMResult result = new DOMResult()
Many Many thanks., its working like a charm Martin Honnen.. Many Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.