Daily Archives: April 11, 2024

How to create PDF from HTML or image using java pdfbox framework

Following example code here:

In pom.xml insert or get the jar files and add them to the java project if you don't use maven 
<repositories>
  <repository>
    <id>jitpack.io</id>
    <url>https://jitpack.io</url>
  </repository>
</repositories>
<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>3.0.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.hkirk/java-html2image -->
<dependency>
   <groupId>com.github.hkirk</groupId>
   <artifactId>java-html2image</artifactId>
   <version>0.9</version>
</dependency>

and Java code here 
public static void main(String[] args) {
            String html = "<html lang=\"en\" xmlns=\http://www.w3.org/1999/xhtml\ style=\"cursor: default;\">"
                        + "<body id=\"body\" class=\"modal-open\" style=\"cursor: default; padding-right: 15px;\">\r\n"
                        + "<p>" + "Hello World</p>";
                        + "</body>\r\n" + "</html>\r\n" + "\r\n" + "";
            HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
            imageGenerator.loadHtml(html);
            BufferedImage bimg = imageGenerator.getBufferedImage();
            float width = bimg.getWidth();
            float height = bimg.getHeight();
            PDPage page = new PDPage(new PDRectangle(width, height));
            PDDocument document = new PDDocument();
            document.addPage(page);
            try {
                  PDImageXObject pdImage = LosslessFactory.createFromImage(document, bimg);

                  try (PDPageContentStream contentStream = new PDPageContentStream(document, page, AppendMode.OVERWRITE, true,
                              true)) {
                        contentStream.drawImage(pdImage, 0, 0, width, height);
                  }
                  document.save("xx.pdf");
                  document.close();
            } catch (IOException e) {
                 //
            } catch (Exception e) {
                  // 
            }
      }