0

I'm looking for a free Java library to convert various file types (as many file types as possible) to PDF.

By various file types, I mean at least most images, Microsoft office documents (at least Word and Excel), text files, rich text format (RTF).

I want to convert static files, not video or audio.

4
  • Are you looking for a pure Java solution? Or are you open to calling command line tools from Java for instance?
    – Ryan
    Aug 22, 2021 at 2:47
  • @Ryan I am looking for java library. Java Solution Aug 27, 2021 at 7:00
  • Why is a pure java solution important for you? Are you under some sort of legal restriction to only run code in the JVM? Is there a specific reason you cannot call a command line tool?
    – Ryan
    Aug 27, 2021 at 15:55
  • @ryan I don't think that this is important. Can you please recommend Java library that can perform this kind of task? Also I will gladly hear about command line tools. Thanks Aug 27, 2021 at 16:20

2 Answers 2

1

For gratis solutions, you will get the best coverage from the following three applications, which can all convert many different file formats to PDF, and will work on Windows/Linux(/macos?).

LibreOffice : office files/text files

https://stackoverflow.com/a/30465397/3761687

ImageMagick : image formats

https://imagemagick.org/script/command-line-processing.php

Chrome (headless) : html/svg

https://stackoverflow.com/questions/64046452/headless-chrome-using-selenium-java-running-tests-in-normal-ui-mode-of-browser

All have command line options to convert many different file types to PDF, though for Chrome headless you need to use an interface to unlock all the options (e.g. to hide the default header/footer that chrome adds).

From there you can just use Java shell execute to trigger the commands you want. As a bonus, since each call is a separate process, you get process isolation (so your JVM is safe) and easy to scale parallelism/concurrency.

0

Spire.Office for Java library can be used to convert multiple file types like Word, RTF, Excel, PowerPoint, text and images etc. to PDF. It also provides a free community edition but with some limitations.

The following code example shows how to convert multiple documents (Word, Excel, PowerPoint, PDF and image) within a folder to PDFs and combine the resultant PDFs to a single PDF.

import com.spire.doc.Document;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfDocumentBase;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.*;
import com.spire.presentation.Presentation;
import com.spire.xls.Workbook;

import java.awt.*;
import java.awt.geom.Dimension2D;
import java.io.*;

public class MergeFilesToOnePDF {
    public static void main(String []args) throws Exception {        

        //Create a File object for directory
        File directoryPath = new File("D:\\Files");
        //Check if the directory exists
        if(!directoryPath.exists()){
            throw new RuntimeException("The directory does not exist.");
        }
        //Get the files in the directory
        File[] filesList = directoryPath.listFiles();

        //Create an InputStream array
        InputStream[] streams = new InputStream[filesList.length];
        int i = 0;
        //Loop through the files
        for (File file : filesList) {
            //Get the file name
            String fileName = file.getName();
            //Get the absolute file path
            String absolutePath = file.getAbsolutePath();
            //Get the file name extension
            String extension = fileName.substring(fileName.lastIndexOf("."), fileName.length());

            //Convert different types of files to PDF and save to streams
            switch (extension) {

                case ".doc":
                case ".docx":
                    //Convert Word to PDF and save to stream
                    Document doc = new Document();
                    doc.loadFromFile(absolutePath);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    doc.saveToStream(bos, com.spire.doc.FileFormat.PDF);
                    streams[i++] = new ByteArrayInputStream(bos.toByteArray());
                    break;

                case ".xls":
                case ".xlsx":
                    //Convert Excel to PDF and save to stream
                    Workbook workbook = new Workbook();
                    workbook.loadFromFile(absolutePath);
                    //workbook.getConverterSetting().setSheetFitToPage(true);
                    bos = new ByteArrayOutputStream();
                    workbook.saveToStream(bos, com.spire.xls.FileFormat.PDF);
                    streams[i++] = new ByteArrayInputStream(bos.toByteArray());
                    break;

                case ".ppt":
                case ".pptx":
                    //Convert PowerPoint to PDF and save to stream
                    Presentation ppt = new Presentation();
                    ppt.loadFromFile(absolutePath);
                    bos = new ByteArrayOutputStream();
                    ppt.saveToFile(bos, com.spire.presentation.FileFormat.PDF);
                    streams[i++] = new ByteArrayInputStream(bos.toByteArray());
                    break;

                 case ".pdf":
                    //Save PDF to stream
                    PdfDocument pdf = new PdfDocument();
                    pdf.loadFromFile(absolutePath);
                    bos = new ByteArrayOutputStream();
                    pdf.saveToStream(bos, com.spire.pdf.FileFormat.PDF);
                    streams[i++] = new ByteArrayInputStream(bos.toByteArray());
                    break;

                case ".png":
                case ".jpg":
                    //Convert image to PDF and save to stream
                    pdf = new PdfDocument();
                    //Convert inches to points
                    PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
                    float width = unitCvtr.convertUnits(8.5f, PdfGraphicsUnit.Inch, PdfGraphicsUnit.Point);
                    float height = unitCvtr.convertUnits(11.0f, PdfGraphicsUnit.Inch, PdfGraphicsUnit.Point);
                    Dimension2D size = new Dimension((int)width, (int)height);
                    //Set page size
                    pdf.getPageSettings().setSize(size);
                    PdfPageBase page = pdf.getPages().add();
                    PdfImage image = PdfImage.fromFile(absolutePath);
                    page.getCanvas().drawImage(image, 100, 50);
                    bos = new ByteArrayOutputStream();
                    pdf.saveToStream(bos, com.spire.pdf.FileFormat.PDF);
                    streams[i++] = new ByteArrayInputStream(bos.toByteArray());
                    break;

                default:
                    System.out.println("Invalid file format.");
                    break;
            }
        }

        //Merge PDFs in the streams into a single PDF
        PdfDocumentBase pdf = PdfDocument.mergeFiles(streams);
        OutputStream outputStream = new FileOutputStream("D:\\Output\\Combine.pdf");
        pdf.save(outputStream);
        pdf.close();
    }
}
1
  • What are the limitations of free community edition?
    – convert
    Jan 13, 2022 at 22:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.