Tuesday, 25 August 2020

[Java] How to convert Excel to PDF using Java

Do you always need to share your Excel workbook with people who don’t have MS Office installed on their system? Do you always need your Excel spreadsheets to keep their format and look exactly the same when opened on different systems? If yes, Converting Excel to PDF will be a perfect way to deal with these problems.

In this tutorial, I’ll show you how to convert Excel to PDF using Java code and Spire.XLS for Java API from the following aspects.

l  Converting the whole Excel workbook to PDF

l  Converting each worksheet in Excel file to different PDF

l  Converting selected range in worksheet to PDF

l  Converting CSV file to PDF

Spire.XLS for Java is a professional Java Excel API that enables developers to create, manage, manipulate, convert and print Excel worksheets without using Microsoft Office or Microsoft Excel. At the same time, it also supports all three operation systems – Windows, Mac OS and Linux.

Add Spire.Xls.jar as dependency

Method 1: Download Free Spire.XLS for Java pack, unzip it and import Spire.Xls.jar located in the “lib” folder in your project as a dependency. You can find the steps from the following screenshot.



Method 2: If you are creating a Maven project, please specify e-iceblue Maven Repository configuration and define Free Spire.XLS for Java API dependency in your pom.xml as follows.

<repositories>

        <repository>

            <id>com.e-iceblue</id>

            <name>e-iceblue</name>

            <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>

        </repository>

</repositories>

<dependencies>

    <dependency>

        <groupId> e-iceblue </groupId>

        <artifactId>spire.xls.free</artifactId>

        <version>2.2.0</version>

    </dependency>

</dependencies>

Finally, for IDEA, you need to click “Import Changes” to import the Spire.PDF jars, and for Eclipse, you just need to click the “Save” button.

Converting the whole Excel workbook to PDF

You first need to create a workbook and load an Excel example file, and then use the setSheetFitToPage method to adjust the width of worksheet. Finally, save the whole file to PDF using the workbook. saveToFile method.

import com.spire.xls.*;

public class WholeToPDF {
   
public static void main(String[] args) {
       
//Create a Workbook and load an Excel file
       
Workbook workbook = new Workbook();
        workbook.loadFromFile(
"C:\\Users\\Test1\\Desktop\\Sample.xlsx");

       
//Fit to page
       
workbook.getConverterSetting().setSheetFitToPage(true);

       
//Save to PDF file
       
workbook.saveToFile("output/WholeToPDF.pdf",FileFormat.PDF);
        }
    }

Output

Convert each worksheet to different PDF

Spire.XLS for Java offers a method of worksheet. SaveToPdf to convert each worksheet to PDF.

import com.spire.xls.*;
public class EachWorksheetToPDF {
   
public static void main(String[] args) {
       
//Create a workbook and load an Excel file
       
Workbook workbook = new Workbook();
        workbook.loadFromFile(
"C:\\Users\\Test1\\Desktop\\Sample.xlsx");
       
//Loop through all worksheets and save to different PDF files
       
for(int i = 0; i < workbook.getWorksheets().getCount(); i ++)
        {
            Worksheet worksheet = workbook.getWorksheets().get(i);
            String result =
"output/sheet-" + i + "-result.pdf";
            worksheet.saveToPdf(result);
        }
       }
 } 

Output


Converting selected Range in worksheet to PDF

The following are the steps to convert selected range in worksheet to PDF.

·      Create a workbook and load an Excel example file

·      Add a new sheet and copy the cells you want to convert to the new sheet.

·      Using the method autoFitColumns() to automatically fit the width.

·      Get the new sheet and save it to PDF file.

import com.spire.xls.*;
public class SelectedRangeToPDF {
   
public static void main(String[] args) {
       
//Create a workbook and load an Excel file
       
Workbook workbook = new Workbook();
        workbook.loadFromFile(
"C:\\Users\\Test1\\Desktop\\Sample.xlsx");
       
//Add a new sheet to workbook
       
workbook.getWorksheets().add("NewSheet");
       
//Copy your area to new sheet
   
workbook.getWorksheets().get(0).getCellRange("A1:C7").copy(workbook.getWorksheets().get(1).getCellRange("A11:C17"), true );
       
//Auto fit column width
       
workbook.getWorksheets().get(1).getCellRange("A1:F17").autoFitColumns();
       
//Save the document
       
String output = "SelectedRangeToPDF.pdf";
        Worksheet worksheet = workbook.getWorksheets().get(
1);
        String result =
"output/selectedRangeToPDF.pdf";
        worksheet.saveToPdf(result);
    }
}

Output


Converting CSV to PDF

A Comma Separated Values (CSV) file is a plain text file that contains a list of data, and we

can open it in spreadsheet programs (such as Microsoft Excel), which make them easier to read.

import com.spire.xls.*;
public class CsvToPDF {
   
public static void main(String[] args) {
        String inputFile =
"C:\\Users\\Test1\\Desktop\\Sample.csv";
       
//Create a workbook and load a csv file
       
Workbook workbook = new Workbook();
        workbook.loadFromFile( inputFile,
",", 1, 1);
       
//Set the setSheetFitToPage property as true
       
workbook.getConverterSetting().setSheetFitToPage(true);
       
//Get the first worksheet
       
Worksheet sheet = workbook.getWorksheets().get(0);
       
//AutoFit a column if the characters in the column exceed column width
       
for (int i = 1; i < sheet.getColumns().length; i++)
        {
            sheet.autoFitColumn(i);
        }        
//Save to PDF document
       
String output = "output/CSVToPDF.pdf";
        workbook.saveToFile(output,  FileFormat.
PDF);     }
}

Output


Conclusion

In this article, we can learn how to easily convert Excel to PDF using Spire.XLS for Java. If there are still some problems about Java code, you can leave a note on our Forum.






Wednesday, 19 August 2020

[Java] How to Convert PowerPoint to PDF/XPS/Image

PowerPoint is the king of presentation software, but when you need to have it for printing or distribution, an automated and time-saving solution is worth to be adopted that you can convert PowerPoint to other formats (such as PDF, XPS and Image) programmatically in Java especially when there is a bunch of PowerPoint documents that needs to be converted. Keeping this in mind, I’ll show you how to realize the conversion function in Java with Spire.Presentation for Java API.

PowerPoint to PDF/XPS/Image conversions in Java

In this article, we’ll know the following three aspects of PowerPoint conversions using Spire.Presentation for Java.

·   Converting PowerPoint to PDF

·   Converting PowerPoint to XPS

·   Converting PowerPoint to Image(mainly .png and .svg)

Install Spire.Presentation.Jar

You can directly either download Spire.Presentation.Jar or add it in your maven-based project using the following repository and dependency information.

<repositories>

        <repository>

            <id>com.e-iceblue</id>

            <name>e-iceblue</name>

            <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>

        </repository>

</repositories>

<dependencies>

    <dependency>

        <groupId> e-iceblue </groupId>

        <artifactId>spire.presentation.free</artifactId>

        <version>2.6.1</version>

    </dependency>

</dependencies>


Here is a screenshot of the sample PowerPoint file:


Converting PowerPoint to PDF

The following are the simple steps to convert PowerPoint to PDF

·    Create a presentation instance and load a sample file

·    Save slides to PDF file

The following is the full codes:

import com.spire.presentation.FileFormat;
import com.spire.presentation.Presentation;

public class ToPDF {
   
public static void main(String[] args) throws Exception {
       
//create a Presentation instance
       
Presentation presentation = new Presentation();

       
//load the sample PowerPoint file
       
presentation.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pptx");

       
//save to PDF file
       
presentation.saveToFile("output/toPDF.pdf", FileFormat.PDF);
        presentation.dispose();
    }
}

Output


Converting PowerPoint to XPS

The XML Paper Specification (XPS) format is basically an electronic representation of digital documents based on XML. It is a paginated fixed-layout format that retains the look and feeling of your electronic documents. As a form of electronic paper, the XPS format provides a way in which you can easily create, share, print and save digital documents.

import com.spire.presentation.*;
public class ToXPS {
   
public static void main(String[] args) throws Exception {
       
//create a presentation instance
       
Presentation ppt = new Presentation();
       
//load the sample PowerPoint file
       
ppt.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pptx");
       
//save to XPS file
       
ppt.saveToFile("output/toXPS.xps", FileFormat.XPS);
        ppt.dispose();     }
}
Output

Converting PowerPoint to Image

·   Save PowerPoint to .png Image

By using ISlide.SaveAsImage() method, we could easily convert specific presentation slide to BMP image

in Jpg, Png, Tiff, Bmp. Here we will use .pptx to .png as example:

import com.spire.presentation.Presentation;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage; import java.io.File;
public class ToImage1 {
   
public static void main(String[] args) throws Exception {
       
//create a presentation instance
         Presentation ppt = new Presentation();
       
//load the sample PowerPoint file
         ppt.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pptx");
       
//Save PPT document to images
       
for (int i = 0; i < ppt.getSlides().getCount(); i++) {
            BufferedImage image = ppt.getSlides().get(i).saveAsImage();
            String fileName = String.format(
"output/ToPNG.png", i);
            ImageIO.write(image,
"PNG",new File(fileName));         }
        ppt.dispose();
    }
}

Output


  • Save PowerPoint to SVG (Scalable Vector Graphics)
SVG, short for scalable vector graphics, is a XML-based file format used to depict two-dimensional

vector graphics. As SVG images are defined in XML text lines, they can be easily searched, indexed,

scripted, and supported by most of the up to date web browsers. Therefore, office documents are often

converted to SVG images for high fidelity viewing.


The following are the simple steps to convert PowerPoint to SVG:

·     Initialize an instance of Presentation class and load a sample PowerPoint document to it;

·     Convert PowerPoint document to byte array and store in a ArrayList object;

·     Initialize an instance of the FileOutputStream class with the specified file path and creation mode.

Full code snippets:

import com.spire.presentation.Presentation;
import java.io.FileOutputStream;
import java.util.ArrayList;
public class ToImage2 {
   
public static void main(String[] args) throws Exception {
       
//create a presentation instance
       
Presentation ppt = new Presentation();
       
//load the sample PowerPoint file
       
ppt.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pptx");
       
//Save PPT document to images
       
ArrayList svgBytes =(ArrayList) ppt.saveToSVG();
       
int count = svgBytes.size();
       
int len = svgBytes.size();
        
for (int i = 0; i < len; i++)
        {
           
byte[] bytes = (byte[]) svgBytes.get(i);
            FileOutputStream stream =
new FileOutputStream(String.format("output/ToSVG.svg", i));
            stream.write(bytes);
        }
        ppt.dispose();
    }
}
Output












Wednesday, 12 August 2020

Add, Edit, Read and Delete Bookmarks in a PDF Document in Java

It is very useful to add bookmarks to PDF files, especially technical documents and instruction manuals. After you add bookmarks to a PDF file, you can access to a specific part of a PDF file easily and efficiently. In this article, I’ll show you how to add, edit, read and delete bookmarks in a PDF document by using Free Spire.PDF for Java.

Dependency

First of all, please download the latest version of Free Spire.PDF for Java from the link, and add Spire.Pdf.jar to your project as a dependency.

Of course, if you are using maven, you can directly add the following code to your project’s pom.xml file.

<repositories> 

        <repository> 

            <id>com.e-iceblue</id> 

            <name>e-iceblue</name> 

            <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url> 

        </repository> 

</repositories> 

<dependencies> 

    <dependency> 

        <groupId>e-iceblue</groupId> 

        <artifactId>spire.pdf.free</artifactId> 

        <version>2.6.3</version> 

    </dependency> 

</dependencies>

Add Bookmarks

The first step of adding bookmarks is to loop through all pages in a PDF file, and then add bookmarks and childbookmarks for each page. At the same time, you can set text color and style for bookmarks by using setColor and setDisplayStyle methods.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.actions.PdfGoToAction;
import com.spire.pdf.bookmarks.PdfBookmark;
import com.spire.pdf.bookmarks.PdfTextStyle;
import com.spire.pdf.general.PdfDestination;
import com.spire.pdf.graphics.PdfRGBColor;
import java.awt.*;
import java.awt.geom.Point2D;

public class AddBookmark {
   
public static void main(String[] args) {
       
//Create a PdfDocument instance
       
PdfDocument pdf = new PdfDocument();
       
//Load a PDF file
       
pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pdf");
       
//Loop through the pages in the PDF file
       
for(int i = 0; i< pdf.getPages().getCount();i++) {
            PdfPageBase page = pdf.getPages().get(i);
           
//Add bookmark
           
PdfBookmark bookmark = pdf.getBookmarks().add(String.format("Bookmark-%s", i + 1));
           
//Set destination page and location
           
PdfDestination destination = new PdfDestination(page, new Point2D.Float(0, 50));
            bookmark.setAction(
new PdfGoToAction(destination));
           
//Set text color
           
bookmark.setColor(new PdfRGBColor(new Color(139, 7, 126)));
           
//Set text style
           
bookmark.setDisplayStyle(PdfTextStyle.Bold);

           
//Add child bookmark
           
PdfBookmark childBookmark = bookmark.add(String.format("ChildBookmark-%s", i + 1));
           
//Set destination page and location
           
PdfDestination childDestination = new PdfDestination(page, new Point2D.Float(0, 200));
            childBookmark.setAction(
new PdfGoToAction(childDestination));
           
//Set text color
           
childBookmark.setColor(new PdfRGBColor(new Color(255, 127, 80)));
           
//Set text style
           
childBookmark.setDisplayStyle(PdfTextStyle.Italic);
        }
       
//Save the result file
       
pdf.saveToFile("output/AddBookmarks.pdf");
    }
}

Output

Edit Bookmarks

Using setTitle, setColor and setDisplayStyle methods, you can change the title, color and style of bookmarks 
and childbookmarks in a PDF file.
import com.spire.pdf.PdfDocument;
import com.spire.pdf.bookmarks.PdfBookmark;
import com.spire.pdf.bookmarks.PdfTextStyle;
import com.spire.pdf.graphics.PdfRGBColor;
import java.awt.*;
public class EditBookmark {
   
public static void main(String[] args) {
       
//Create a PdfDocument instance
       
PdfDocument doc = new PdfDocument();
       
//Load the PDF file
       
doc.loadFromFile("C:\\Users\\Test1\\Desktop\\AddBookmarks.pdf");
       
//Get the first bookmark
       
PdfBookmark bookmark = doc.getBookmarks().get(0);
       
//Change the title of the bookmark
       
bookmark.setTitle("New Title");
       
//Change the font color of the bookmark
       
bookmark.setColor(new PdfRGBColor(new Color(2, 139, 2)));
       
//Change the outline text style of the bookmark
       
bookmark.setDisplayStyle(PdfTextStyle.Italic);
       
//Edit child bookmarks of the first bookmark
       
for (PdfBookmark childBookmark : (Iterable <PdfBookmark>) bookmark) {
            childBookmark.setColor(
new PdfRGBColor(new Color(255, 19, 24)));
            childBookmark.setDisplayStyle(PdfTextStyle.
Bold);
        }
       
//Save the result file
       
doc.saveToFile("output/EditBookmarks.pdf");
        doc.close();
    }
    }

Output

Read Bookmarks

To read bookmarks in a PDF file, you first get the bookmark collection by using pdf.getBookmarks() method,
and then create a .txt file and insert bookmarks in it.
import com.spire.pdf.*;
import com.spire.pdf.bookmarks.PdfBookmark;
import com.spire.pdf.bookmarks.PdfBookmarkCollection;
import java.io.FileWriter;
import java.io.IOException;
public class ReadBookmark {
   
public static void main(String[] args) {
       
//Create a PdfDocument instance
       
PdfDocument pdf = new PdfDocument();
       
//Load the PDF file
      
pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\AddBookmarks.pdf");
       
//Get bookmarkCollection
       
PdfBookmarkCollection bookmarkCollection = pdf.getBookmarks();
       
//Crate a StringBuilder instance
       
StringBuilder stringbuilder = new StringBuilder();
       
//Define a method to get bookmarks
       
GetBookmarkTitle(bookmarkCollection, stringbuilder);
       
//Create a .txt file,and write down bookmarks
       
FileWriter writer;
       
try {
            writer =
new FileWriter("output/ReadBookmark.txt");
            writer.write(stringbuilder.toString());
            writer.flush();
        }
catch (IOException e) {
            e.printStackTrace();
        }
        pdf.dispose();
    }
   
// Define a method to get the titles of bookmarks
   
static void GetBookmarkTitle(PdfBookmarkCollection bookmarkCollection, StringBuilder stringbuilder)
    {
       
if (bookmarkCollection.getCount()> 0)
        {
           
for(int i = 0 ; i< bookmarkCollection.getCount(); i++ )
            {
                PdfBookmark parentBookmark = bookmarkCollection.get(i);
                stringbuilder.append(parentBookmark.getTitle());
                GetBookmarkTitle(parentBookmark, stringbuilder);
            }
        }
    }
}

Output

Delete Bookmarks

You can easily delete a specific child bookmark, a parent bookmark along with its child bookmarks or all the bookmarks from a PDF file.

import com.spire.pdf.PdfDocument;
public class DeleteBookmark {

public static void main(String[] args) {
//Create a PdfDocument instance

PdfDocument pdf = new PdfDocument();

//Load the PDF file
pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\AddBookmarks.pdf");

//Delete the first child bookmark

//pdf.getBookmarks().get(0).removeAt(0);

//Delete the first bookmark along with its child bookmark
//pdf.getBookmarks().removeAt(0);

//Delete all the bookmarks
pdf.getBookmarks().clear();

//Save the result file

pdf.saveToFile("output/DeleteBookmarks.pdf");
    }
}





Change PDF Versions in Java

In daily work, you might need to change the version of a PDF document you have in order to ensure compatibility with another version which a...