A dynamically generated PDF files refers to one where you need a header, footer, left and right panes for a document (can work with any one or one or combinations of any of them)

iText is probably one of the most popular and stable libraries to create PDF documents programmatically in Java world

In this post, we are going to create a PDF image that uses plain text as well as multimedia content i.e. images.

Step 1:

We are going to create a model that would act as a placeholder for all the content in our document:

public class PDFImagesTo {
    String header;
    String footer;
    String left;
    String right;
    Float leftMargin;
    Float rightMargin;

    public String getHeader() {
        return header;
    }
    public void setHeader(String header) {
        this.header = header;
    }
    public String getFooter() {
        return footer;
    }
    public void setFooter(String footer) {
        this.footer = footer;
    }
    public String getLeft() {
        return left;
    }
    public void setLeft(String left) {
        this.left = left;
    }
    public String getRight() {
        return right;
    }
    public void setRight(String right) {
        this.right = right;
    }
    public Float getLeftMargin() {
        return leftMargin;
    }
    public void setLeftMargin(Float leftMargin) {
        this.leftMargin = leftMargin;
    }
    public Float getRightMargin() {
        return rightMargin;
    }
    public void setRightMargin(Float rightMargin) {
        this.rightMargin = rightMargin;
    }
}

Step 2:

Next, we create a Utility class that would do the Job of creating content.

public class CreatePdfDocument {

    public static String createPDF(PDFImagesTo to, String content, String outputPath) {
        try {
            Float headerMargin = 90f;
            Float footerMargin = 36f;
            Float leftMargin = 36f;
            Float rightMargin = 36f;
            Image headerImage = null;
            Image footerImage = null;
            Image leftImage = null;
            Image rightImage = null;
            //adding image for header

            File file = new File(to.getHeader());
            if (file.exists()) {
                headerImage = Image.getInstance(to.getHeader());
                System.out.println(PageSize.A4.getWidth() + " " + PageSize.A4.getHeight());
                headerImage.scaleToFit(PageSize.A4.getWidth(), 200);
                //Setting Y coordinate of header image according to header image height
                Float effectiveHeaderY = PageSize.A4.getHeight() - headerImage.getPlainHeight();
                headerImage.setAbsolutePosition(0, effectiveHeaderY);
                headerMargin = headerImage.getPlainHeight() + 10;
            } else {
                return "Header image does not exists";
            }


            //adding image for footer
            File file = new File(to.getFooter());
            if (file.exists()) {
                footerImage = Image.getInstance(to.getFooter());
                footerImage.scaleToFit(PageSize.A4.getWidth(), 200);
                footerImage.setAbsolutePosition(0, 0);
                footerMargin = footerImage.getPlainHeight() + 10;
            } else {
                return "Footer image does not exists";
            }

            //adding image for left side
            File file = new File(to.getLeft());
            if (file.exists()) {
                leftImage = Image.getInstance(to.getLeft());
                leftImage.scaleAbsolute(leftImage.getPlainWidth(), leftImage.getPlainHeight());
                //Setting X and Y coordinate of Left image according to footer
                Float effectiveLeftY = (footerImage != null ? footerImage.getPlainHeight() : 0);
                leftImage.setAbsolutePosition(0, effectiveLeftY);
                leftMargin = leftImage.getPlainWidth() + ((to.getLeftMargin() != null && to.getLeftMargin() >= 0) ? to.getLeftMargin() : 2);
            } else {
                return "Left image does not exists";
            }

            //adding image for right side
            File file = new File(to.getRight());
            if (file.exists()) {
                rightImage = Image.getInstance(to.getRight());
                rightImage.scaleAbsolute(rightImage.getPlainWidth(), rightImage.getPlainHeight());
                Float effectiveLeftX = PageSize.A4.getWidth() - rightImage.getPlainWidth();
                Float effectiveRightY = (footerImage != null ? footerImage.getPlainHeight() : 0);
                rightImage.setAbsolutePosition(effectiveLeftX, effectiveRightY);
                rightMargin = rightImage.getPlainWidth() + ((to.getRightMargin() != null && to.getRightMargin() >= 0) ? to.getRightMargin() : 2);
            } else {
                return "Right image does not exists";
            }
                
            Document document = new Document(PageSize.A4, leftMargin, rightMargin, headerMargin, footerMargin);
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputPath));

            // add header and footer
            HeaderFooterPageEvent event = new HeaderFooterPageEvent();
            if (headerImage != null) {
                event.setHeader(headerImage);
            }
            if (footerImage != null) {
                event.setFooter(footerImage);
            }
            if (leftImage != null) {
                event.setLeft(leftImage);
            }
            if (rightImage != null) {
                event.setRight(rightImage);
            }
            writer.setPageEvent(event);
            // write to document
            document.open();
            if (content.trim().isEmpty()) {
                document.newPage();
                writer.setPageEmpty(false);
            }
            HTMLWorker htmlWorker = new HTMLWorker(document);
            htmlWorker.parse(new StringReader(content));
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }
}

NOTE:

We could calculate the coordinates i.e x and y of all images dynamically or we could hard code these values. In this example, I am going to use hardcoded values for sake of simplicity.

Make sure to add handler for cases where inputs are not as per expectation and how you want to fallback to some alternate text or multimedia instead.

Step 3:

Final step is to call this utility method by providing the required data and there you go.

public static void main(String... args) throws FileNotFoundException, DocumentException {

    String k = "";

    PDFImagesTo to = new PDFImagesTo();
    to.setHeader("D:/header.PNG");
    to.setFooter("D:/footer.PNG");
    to.setLeft("D:/left.PNG");
    to.setRight("D:/right.PNG");
    String outputPath = "D:/HeaderFooter7.pdf";
    CreatePdfDocument pdf = new CreatePdfDocument();
    pdf.createPDF(to, k, outputPath);
}

Hope this post gives you a rough idea of what you can do with this awesome iText library.

Creating a PDF document using Java and iText
Tagged on:         

Leave a Reply

Your email address will not be published. Required fields are marked *