2

I need to merge multiple documents into a single PDF in a web application running on Ubuntu Server. I've merged PDFs in the past so that shouldn't be an issue, but the documents can also contain doc, docx, xls, and xlsx files. I'm guessing my best bet it to convert those to PDF first.

After searching around a bit it seems the most popular way of doing this is to run LibreOffice from the command line to convert them. I've tested it and it works, however it seems that installing that requires installing X11 on the server, which is less than ideal.

Even beyond that issue, when I've tested it will Excel documents it seems to just page break the spreadsheet by columns in a way that makes it impossible to follow.

So I guess my questions are:

  1. Is approach the best choice for this?
  2. If so, is there a way to install LibreOffice without x11?
  3. Is there a way to more gracefully handle how it converts spreadsheets?
1
  • Not sure if it can be installed without X11 (as it also includes a GUI) or how it deals with Excel, but maybe Calibre could be an option?
    – Izzy
    Commented Nov 10, 2020 at 22:50

3 Answers 3

0

If you cannot find a suitable software that solves your requirements, you might need to write it yourself. The DocumentConverter class from the LEADTOOLS SDK is specifically designed to convert from any document format to any other document format, including Office formats and PDF, and it can even perform OCR automatically for raster based files. It’s supported for both Java and .NET Core, and contains fully functional command line demos for both. Just as a disclaimer, I work for the company that writes this library.

The code is very simple for basic conversion, but can also be fully customized for more complex tasks. The following .Net code could be used (Java is very similar):

using (DocumentConverter converter = new DocumentConverter()){
    converter.SetDocumentWriterInstance(new DocumentWriter());
    DocumentConverterJobData jobData = new DocumentConverterJobData{
        InputDocumentFileName = @”C:\temp\InputFile.docx”,
        OutputDocumentFileName = @”C:\temp\OutputFile.pdf”,
        DocumentFormat = DocumentFormat.Pdf,
        RasterImageFormat = RasterImageFormat.Unknown, // To not output to a raster based image
    };
    DocumentConverterJob converterJob = converter.Jobs.CreateJob(jobData);
    converter.Jobs.RunJob(converterJob);
}
0

NOTE FROM MODERATORS: Links below go through third-party redirection servers. A request has been made to the poster to update all links to direct links. All non-direct links below have been temporarily disabled until this has been completed.

Syncfusion provides .NET Core libraries to convert Excel (XLS, XLSX) and Word (DOC, DOCX) to PDF without the need of LibreOffice, Adobe SDK, or Microsoft Office. You can give it a try.

Word to PDF conversion docs

Word to PDF demo

Excel to PDF conversion docs

Excel to PDF demo

Syncfusion Excel to PDF converter library provides the following options to customize the page/column break behavior.

• Automatic – Prints sheets at their actual size. The default one. • Custom Scaling – Print sheets at specified scaling option (i.e.) zoom value set in page setup. • Fit all columns on one page • Fit all rows on one page • Fill the entire sheet on one page

Please refer to this documentation page to know about customizing the Layout and other options.

https://help.syncfusion.com/file-formats/xlsio/excel-to-pdf-converter-settings#layout-options

2
  • 1
    Welcome Johnson! Do you have any affiliation with this product? If so, please disclose it in your answer in full. Also, please edit all your links to be direct links without going through third-party redirection services. Commented Feb 25, 2021 at 15:43
  • Johnson Manickam, I would happily edit your post, but I think it would look better if you would do it.
    – peterh
    Commented Feb 26, 2021 at 12:43
0

You may take a look at Spire.Office for Java library. It allows you to convert multiple file types like Word .doc/.docx, RTF, Excel .xls/.xlsx, PowerPoint .ppt/.pptx, text and images etc. to PDF without having MS Office, Adobe Acrobat or other software to be installed.

The following is a basic example shows how to convert Word .doc/.docx, Excel .xls/.xlsx, PowerPoint .ppt/.pptx and image within a particular directory to PDF files and combine the resultant files 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();
    }
}

Apart from file conversion, it also provides lots of other functionalities, you can visit the documentation for more information: https://www.e-iceblue.com/Tutorials.html

Your Answer

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

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