android create pdf file from html text

android, html, itext, pdf

Solution

I've solved this issue recently. The problem was `Navruzbek Akhmedov <akhmedovnavruzbek@gmail.com>` in html text. iText lib seems to me sees `<akhmedovnavruzbek@gmail.com>` like HTML tag. It doesn't have actually in html tag list then gives error. That's all! :)))))))))))))))))))

Problem

Here is my code in order to convert html into pdf: ``` public boolean create (String htmlText, String absoluteFilePath) { try { Document document = new Document(PageSize.LETTER); PdfWriter pdfWriter = PdfWriter.getInstance (document, new FileOutputStream(absoluteFilePath)); document.open(); // Fixing xhtml tag Tidy tidy = new Tidy(); // obtain a new Tidy instance tidy.setXHTML(true); // set desired config options using tidy setters ByteArrayOutputStream output = new ByteArrayOutputStream(); tidy.setCharEncoding(Configuration.UTF8); tidy.parse(new ByteArrayInputStream(htmlText.getBytes(), output); String preparedText = output.toString("UTF-8"); Log.i("CHECKING", "JTidy Out: " + preparedText); InputStream inputStream = new ByteArrayInputStream(preparedText.getBytes()); XMLWorkerHelper.getInstance().parseXHtml(pdfWriter, document, inputStream, null, Charset.forName("UTF-8"), new MyFont()); document.close(); return true; } catch (Exception e) { File file = new File(absoluteFilePath); if(file.exists()) { boolean isDeleted = file.delete(); Log.i("CHECKING", "PDF isDeleted: " + isDeleted); } LOGGER.error("Exception: " + e.getMessage()); e.printStackTrace(); return false; } ``` } It works for this following htmlText ``` <p dir="ltr"><br> wwwww<br> --- <br> Sent bys.</p> <p>Original message:</p> <blockquote> <strong>From: </strong> nakhmedov@s.com <br/> <strong>Sent: </strong> Dec 1, 2014 5:10:19 PM <br/> <strong> To: </strong> ssss <br/> <strong>Subject: </strong> test <br/> <br/> <p dir="ltr"> <br> 123<br> --- <br> ssssssss.</p> </blockquote> ``` And it doesn`t work this following htmlText: ``` <p dir="ltr"><br> 123<br> --- <br> Sent by ss.</p> <p>Original message:</p> <blockquote> <strong>From: </strong> Navruzbek Akhmedov <akhmedovnavruzbek@gmail.com> <br/> <strong>Sent: </strong> Dec 1, 2014 5:14:36 PM <br/> <strong> To: </strong> Navruzbek Akhmedov <nakhmedov@sss.com> <br/> <strong>Subject: </strong> test <br/> <br/> <div dir="ltr">12345</div> </blockquote> ``` Please help me why it works differently and it gives an error for secon htmlText `document has no pages` and outputstream is empty after this `tidy.parse(new ByteArrayInputStream(htmlText.getBytes("ISO-8859-1")), output);`. Thanks in advance!

Original source