0

I need help for converting html content to a pdf.

I am currently using OpenPDF 1.3.30 to generate my pdf file in Java. I have a vue component that uses Vue Editor which is a rich text editor wrapper for Vue from Quill.

Currently I am sending the html content as a string to my backend class and converting the html content to a pdf document using jsoup and openhtmltopdf. I want to add the content to a pdf document that I am generating which has other content aswell. I want to add the content to a PdfPTable.

I am stuck on how to add the content to the pdf that is being generated and also apply the quill css styles that I included in my resources.

Here is my code:

This code is from my class that generates that converts the html content.

` public PdfPTable buildComments(int mBottom) throws IOException {
        PdfPTable table = new PdfPTable(1);
        try {
                reportPrintUtilities.setCellGrey(cellGrey);
                reportPrintUtilities.setReport(report);
            
                table.setTotalWidth(width);
                table.setLockedWidth(true);

                try {
                    String htmlContent = "<div class=\"ql-editor\">" + report.getComment() + "</div>";
                    createHtmlFile();
                    table.addCell(reportPrintUtilities.buildCell(new Phrase("Additional Comments", headFont), 1, 1, 18, "center", 2, 2, 1, 1, true, false));
                    buildCommentHtmlFile(htmlContent);
                    File htmlFile = new File(HTML_FILE);
                    org.jsoup.nodes.Document doc = createWellFormedHtml(htmlFile);
                    xhtmlToPdf(doc, PDF_OUTPUT);

                    //table.addCell(cell);

                    //Element qlEditor = (Element) doc.body().getElementsByClass("ql-editor");

                    //String extractedText = extractTextFromPdf(PDF_OUTPUT);
                    PdfPCell cell = new PdfPCell(new Paragraph(doc.body().html()));
                    table.addCell(cell);

                    //htmlFile.delete();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                table.setSpacingBefore(5F);
        } catch(DocumentException de) {
            throw new ExceptionConverter(de);
        }
        return table;
    }

    public void createHtmlFile() throws IOException {
        File file = new File(HTML_FILE);
        if (!file.exists()) file.createNewFile();
        StringBuilder htmlBuilder = new StringBuilder();
        htmlBuilder.append("<!DOCTYPE html>\n" +
                "<head>\n" +
                CSS_FILE +"\n"+
                " <style>\n" +
                "  body {\n" +
                "   margin: 0;\n" +
                "   padding: 0;\n" +
                "  }\n" +
                "  p, h1, h2, h3 {\n" +
                "   margin: 0;\n" +
                "   padding: 0;\n" +
                "  }\n" +
                " </style>\n" +
                "</head>\n" +
                "<body>\n" +
                "</body>\n" +
                "</html>");

        FileWriter writer = new FileWriter(file);
        writer.write(htmlBuilder.toString());
        writer.close();
    }

    public void buildCommentHtmlFile(String htmlString) throws IOException {
        File inputHTML = new File(HTML_FILE);
        org.jsoup.nodes.Document doc = Jsoup.parse(inputHTML, "UTF-8");

        org.jsoup.nodes.Element body = doc.body();
        body.append(htmlString);



        FileWriter writer = new FileWriter(inputHTML);
        writer.write(doc.outerHtml());
        writer.close();
    }

    private org.jsoup.nodes.Document createWellFormedHtml(File inputHTML) throws IOException {
        org.jsoup.nodes.Document document = Jsoup.parse(inputHTML, "UTF-8");
        document.outputSettings().syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml);
        return document;
    }

    private void xhtmlToPdf(org.jsoup.nodes.Document doc, String outputPdf) throws IOException {
        try (OutputStream os = new FileOutputStream(outputPdf)) {
            String baseUri = FileSystems.getDefault()
                    .getPath("src/main/resources/")
                    .toUri()
                    .toString();
            PdfRendererBuilder builder = new PdfRendererBuilder();

            builder.withUri(outputPdf);
            builder.toStream(os);

            builder.withW3cDocument(new W3CDom().fromJsoup(doc), baseUri);
            builder.run();
        }
    }

Here is part of my code that generates the pdf:


        Rectangle pdfLayout = PageSize.A4;

        ReportHeaderFooter headerFooter = new ReportHeaderFooter();
        headerFooter.setCloudfront(cloudfront);
        headerFooter.setReport(report);
        headerFooter.setCellGrey(cellGrey);


        Document document = new Document(pdfLayout, 5, 5, 85, mBottom);
        float width = document.getPageSize().getWidth() - 10;

        ReportSectionOne reportSectionOne = new ReportSectionOne();
        reportSectionOne.setReport(report);
        reportSectionOne.setCellGrey(cellGrey);
        reportSectionOne.setWidth(width);

        String testDate = new SimpleDateFormat("yyyy-MM-dd").format(report.getTestDate());
        String fileName = report.getReportNo() + "-" + report.getMethodType() + "-" + testDate +   ".pdf";

        reportPrintUtilities.setCloudfront(cloudfront);
        reportPrintUtilities.setReport(report);
        reportPrintUtilities.setCellGrey(cellGrey);

        File pdfFile = new File(fileName);
        FileOutputStream fos = new FileOutputStream(pdfFile);
        PdfWriter writer = PdfWriter.getInstance(document, fos);
        writer.open();
        writer.setFullCompression();
        writer.setPageEvent(headerFooter);
        document.open();
        
                // Comments
        if(!report.getComment().isEmpty()){
            ReportComments reportComments = new ReportComments();
            reportComments.setReport(report);
            reportComments.setWidth(width);
            reportComments.setCellGrey(cellGrey);
            reportComments.setCloudfront(cloudfront);
            reportComments.setDocument(document);
            document.add(reportComments.buildComments(mBottom));

        }

any suggestion will be greatly appreciated.

1 Answers1

0

Hey I usually do that.

final StringReader reader = new StringReader(<your html in string>);
                HtmlParser.parse(document, reader); 

This is the final code.

        try {
            try (Document document = new Document()) {
                document.setPageSize(PageSize.LETTER);
                PdfWriter.getInstance(document, new FileOutputStream("openpdfdemo/src/main/resources/output/openpdf.pdf"));
                document.open();
                final StringReader reader = new StringReader(TemplateParseUtils.generateHTMLDocument(TEMPLATE_CORREO_LIBRANZA));
                HtmlParser.parse(document, reader);
            } catch (DocumentException | IOException de) {
                System.err.println(de.getMessage());
            }
        } catch (DocumentException de) {
            System.err.println(de.getMessage());
        }
    } 

But there's a problem is to generate css styles embedded in your html.

Open PDF is not able to generate the styles.

I usually got this enter image description here

For that reason i had to find another library