Skip to content

Instantly share code, notes, and snippets.

@jefferyshivers
Last active October 1, 2019 03:04
Show Gist options
  • Save jefferyshivers/99eaa4f380b647e88ac43ef41d98cf88 to your computer and use it in GitHub Desktop.
Save jefferyshivers/99eaa4f380b647e88ac43ef41d98cf88 to your computer and use it in GitHub Desktop.
Example implementation of Flying Saucer to render a PDF from HTML.
import com.lowagie.text.DocumentException;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.*;
import java.net.URL;
public class PDF {
private void render() throws DocumentException, IOException {
ITextRenderer iTextRenderer = new ITextRenderer();
iTextRenderer.setDocument(getHtml());
iTextRenderer.layout();
iTextRenderer.createPDF(new FileOutputStream("example.pdf"));
}
private File getHtml() throws FileNotFoundException {
final String fileName = "example.html";
ClassLoader classLoader = this.getClass().getClassLoader();
URL url = classLoader.getResource(fileName);
if (url != null) {
return new File(url.getFile());
} else {
throw new FileNotFoundException(fileName);
}
}
public static void main(String... args) {
try {
new PDF().render();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment