I have started working with Java spring boot a couple of months ago, along with my react project with kepler.gl. And the first task that I had was to convert an image to pdf in Java. I used iTextPdf to do it. You can find the link to Github repo with full code at the bottom of this post. I have explained the steps below to add image to pdf in java.
Adding Dependency
First add the itextpdf
to your pom.xml
and install the dependency.
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itext7-core</artifactId> <version>7.1.11</version> <type>pom</type> </dependency>
Converting image to pdf
So instead of converting the image to pdf, you can just insert the image in pdf.
You can create a PdfWriter
to create a new PdfDocument
. You can specify the page height and width with PageSize
and set the margins as per your requirement.
Now create an itextpdf image element from your image and add it in the document you have just created. I am adding the complete method I have created to do this. The method will take a file object, convert it to pdf and save it in your project directory. You can update the code according to your needs.
public void convertImageToPdf(File imageFile) { PdfWriter pdfWriter = null; String pdfFile = imageFile.getName().split("\\.")[0] + ".pdf"; try { pdfWriter = new PdfWriter(pdfFile); } catch (FileNotFoundException e) { logger.info("Unable to create pdfWriter. Pdf file not found for file: " + imageFile.toString()); return; } PdfDocument pdfDocument = new PdfDocument(pdfWriter); PageSize pageSize = new PageSize(936.0F, 684.0F); try (Document document = new Document(pdfDocument, pageSize)) { document.setLeftMargin(0); document.setRightMargin(0); document.setBottomMargin(0); document.setTopMargin(0); try { ImageData data = ImageDataFactory.create(imageFile.toString()); com.itextpdf.layout.element.Image img = new com.itextpdf.layout.element.Image(data); document.add(img); } catch (MalformedURLException e) { logger.info("Unable to add image to the pdf. Error: " + e.toString()); } } logger.info(imageFile.getName() + " converted to pdf"); }
Converting multiple images to pdf
I have also created a method which uses the method above to convert multiple images from a path to multiple pdfs. Here is the code for that:
public void convertImagesToPdf(Path directory) { File[] images = directory.toFile().listFiles(); if (images != null) { for (File image : images) { convertImageToPdf(image); } } }
I have created a small java application with this functionality and added it on Github. Check it out.
What do you use?
What do you used to convert your images to pdf? Share in comments.
If this post was helpful, please like and share to help this blog grow.
Also Read: Daemon Threads in Java