Chen Jian's Java Blog 

Generate PDF from server side using Java

by Chen Jian


Posted on 2019-06-21 14:52 in Java


You can use OpenPDF to draw a PDF (the open source fork of iText). However, the learning curve of creating PDF with layouts and stuff is very high.

A more cost-effective solution is create an HTML version of it and convert it using Flying Saucer with its OpenPDF component

. As a Java developer you are already familiar with html + css, so doing that is quick.

There are some limitations and side effects of this approach

  • Your html must be XML/XHTML
  • Styles' version must be no more than CSS 2.1. (So you can't use flexbox layout)
  • No javascript
  • More: https://flyingsaucerproject.github.io/flyingsaucer/r8/guide/users-guide-R8.html#xil_6
  • The image quality seems worse than what you see on the html page, if there is any

And to create a PDF, your html can't be too wide, otherwise content may be lost.

Typically, say you are creating an A4 PDF with margin of 0.1 inch on both left and right, the width of your html should not be more than (A4's paper width - margin) * pixe density = (8.27inch - 0.1 inch * 2) * 96 DPI = 774 pixels

And here is how to set up the size and margin of the PDF in your html:

<head>
    <style>
        @page {
            margin-left: 9px;   /* about 0.1 inch */ 
            margin-right: 9px; 
            size: A4;
        }
    </style>
   ...



No one has commented yet.
该日志评论功能被禁用了。