извлечение <table>из строки html и создание PDF с использованием - PullRequest
0 голосов
/ 12 октября 2018

Я пытаюсь извлечь таблицу тегов (html) из строки и вывести их в виде таблицы в формате pdf, которую я загружаю на свой локальный компьютер.

В качестве строки, содержащей содержимое HTMLявляется динамическим, поэтому я не могу делать отображение ячейка за ячейкой или строка за строкой.

Например,

private String message = "<html><body><p class=\"MsoNormal\"><b><span style=\"color: rgb(68, 84, 106);\">Dear Agent,<br><br>Please be informed that because no TRMF or reason for delay were received by the due date mentioned below, we consider the Transaction to be Paid in Error. We are going to act accordingly which means charging the Paying Account in case we are not able to defend legal dispute without TRMF.</span></b><span style=\"font-size: 10pt; line-height: 14.2667px;\"><o:p></o:p></span></p><p class=\"MsoNormal\"><span style=\"font-size: 10pt; line-height: 14.2667px;\">&nbsp;</span></p><div><span style=\"font-size: 10pt; line-height: 14.2667px;\"><br></span></div><table class=\"MsoNormalTable\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"0\" style=\"width: 472.9pt; margin-left: 5.9pt;border-collapse: collapse;\"><tr><td>Neeraj</td><td>Chand</td></tr><tr><td>Sowmya</td><td>Javvadi</td></tr></table></body></html>";

Я получу такую ​​строку, которая будет содержать html-контент.Я должен создать файл PDF, соответствующий такому содержанию.Входная строка может иметь или не иметь никакого содержимого таблицы.

Я попробовал ниже, но это не работает, и я получаю ошибку, что "ширина таблицы не может быть 0".

public StreamedContent getFile() throws IOException, DocumentException {
        final PortletResponse portletResponse = (PortletResponse) FacesContext.getCurrentInstance().getExternalContext()
                .getResponse();
        final HttpServletResponse res = PortalUtil.getHttpServletResponse(portletResponse);
        res.setContentType("application/pdf");
        res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // res.setHeader("Content-Disposition", "attachment; filename=\".pdf\"");
        res.setHeader("Content-Disposition", "attachment; filename=" + subject + ".pdf");
        res.setHeader("Refresh", "1");
        res.flushBuffer();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        OutputStream out = res.getOutputStream();
        Document document = new Document(PageSize.LETTER);
        PdfWriter.getInstance(document, baos);
        document.open();
        document.addCreationDate();
        /* without parsing html, it works and generates pdf
        Table table = new Table(2, 2);
        document.add(new Paragraph("converted to PdfPTable:"));
        table.setConvert2pdfptable(true);
        document.add(table);
         */

        //below doesn't work
        HTMLWorker htmlWorker = new HTMLWorker(document);
        String str = this.getMessage();
        htmlWorker.parse(new StringReader(str));
        PdfPTable table= new PdfPTable(2); // not sure what to give here as nummber of columns is dynamic
        table.setTotalWidth(document.getPageSize().getWidth() - 80);
        document.add(table);
        document.close();
        baos.writeTo(out);
        out.flush();
        out.close();
        return null;
    }

Можно ли сгенерировать pdf из любой предоставленной строки html?Или, если есть какой-либо другой инструмент, который я могу использовать для этого, пожалуйста, дайте мне знать.

...