javapdfitextopenpdf

How to convert HTML to Pdf with OpenPdf


How can I convert an HTML to PDF with OpenPDF?

For what I know, OpenPdf is a fork of Itext 4. Unluckily I can't find Itext 4 documentation.


Solution

  • Ok,it seems you can't do it directly with only OpenPDF, you have to use Flying Saucer: get flying-saucer-pdf-openpdf and then use it. An example:

    String inputFile = "my.xhtml";
    String outputFile = "generated.pdf";
    
    String url = new File(inputFile).toURI().toURL().toString();
    
    ITextRenderer renderer = new ITextRenderer();
    renderer.setDocument(url);
    renderer.layout();
    
    try (OutputStream os = Files.newOutputStream(Paths.get(outputFile))) {
        renderer.createPDF(os);
    }
    

    Source.

    PS: FlyingSaucer expects XHTML syntax. If you have some problems with yout HTML file, you could use Jsoup:

    String inputFile = "my.html";
    String outputFile = "generated.pdf";
    
    String html = new String(Files.readAllBytes(Paths.get(inputFile)));
    final Document document = Jsoup.parse(html);
    document.outputSettings().syntax(Document.OutputSettings.Syntax.xml);
    
    ITextRenderer renderer = new ITextRenderer();
    renderer.setDocumentFromString(document.html());
    renderer.layout();
    
    try (OutputStream os = Files.newOutputStream(Paths.get(outputFile))) {
        renderer.createPDF(os);
    }