Convert Excel to PDF in Java

Spire.XLS for Java offers two methods called Workbook.saveToFile() and Worksheet.saveToPdf() to convert a whole Excel file or a specified worksheet to PDF. Besides, it allows to control conversion parameters using the ConvertSettings class, for example, you can let worksheets to fit to page.

The following screenshot is an Excel file including two worksheets. The following code samples will demonstrate how to convert it to PDF with the help of Spire.XLS for Java.

Convert Excel to PDF in Java

Convert a whole Excel file to PDF

import com.spire.xls.FileFormat;
import com.spire.xls.Workbook;

public class ConvertExcelToPdf {

    public static void main(String[] args) {

        //Create a Workbook instance and load an Excel file
        Workbook workbook = new Workbook();
        workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");

        //Set worksheets to fit to page when converting
        workbook.getConverterSetting().setSheetFitToPage(true);

        //Save the resulting document to a specified path
        workbook.saveToFile("output/ExcelToPdf.pdf", FileFormat.PDF);
    }
}

Convert Excel to PDF in Java

Convert a specified worksheet to PDF

import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class ConvertWorksheetToPdf {

    public static void main(String[] args) {

        //Create a Workbook instance and load an Excel file
        Workbook workbook = new Workbook();
        workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");

        //Set worksheets to fit to width when converting
        workbook.getConverterSetting().setSheetFitToWidth(true);

        //Get the first worksheet
        Worksheet worksheet = workbook.getWorksheets().get(0);

        //Convert to PDF and save the resulting document to a specified path
        worksheet.saveToPdf("output/WorksheetToPdf.pdf");
    }
}

Convert Excel to PDF in Java