This article demonstrates a simple solution to convert an Excel file to PDF in Java by using free Excel API – Free Spire.XLS for Java.
The following examples illustrate two possibilities to convert Excel to PDF:
- Convert the whole Excel file to PDF
- Convert a particular Excel Worksheet to PDF
Before start with coding, you need to Download Free Spire.XLS for Java package, unzip it and import Spire.Xls.jar file from the lib folder in your project as a denpendency.
1. Convert the whole Excel file to PDF
Spire.XLS for Java provides saveToFile method in Workbook class that enables us to easily save a whole Excel file to PDF.
import com.spire.xls.FileFormat;
import com.spire.xls.Workbook;
public class ExcelToPDF {
public static void main(String[] args){
//Create a Workbook
Workbook workbook = new Workbook();
workbook.loadFromFile("Sample.xlsx");
//Fit to page
workbook.getConverterSetting().setSheetFitToPage(true);
//Save the Excel to PDF
workbook.saveToFile("WorkbookToPDF.pdf", FileFormat.PDF);
}
}
2. Convert a particular Excel Worksheet to PDF
We can use saveToPdf method in Worksheet class to convert a particular worksheet to PDF.
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class ExcelToPDF {
public static void main(String[] args){
//Create a Workbook
Workbook workbook = new Workbook();
workbook.loadFromFile("Sample.xlsx");
//Get the second worksheet
Worksheet worksheet = workbook.getWorksheets().get(1);
//Fit to page
worksheet.getPageSetup().setFitToPagesWide(1);
worksheet.getPageSetup().setFitToPagesTall(1);
//Save the worksheet to PDF
worksheet.saveToPdf("WorksheetToPDF.pdf");
}
}
Comments
Post a Comment