Convert Word to Password-Protected PDF in Java

During the conversion of a Word document to PDF, we may want to encrypt the PDF document to prevent unauthorized viewing. In this article, I will introduce how to achieve this task programmatically using Java.

Add Dependencies

To implement the conversion, I will be using Spire.Doc for Java, which is a powerful and easy-to-use API for creating, reading, editing, and converting Word documents.

You can either download the API’s jar from this link or install it from Maven by adding the following code to your maven-based 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.doc</artifactId>    
        <version>4.10.9</version>    
    </dependency>    
</dependencies>

Convert Word to Password-Protected PDF

Spire.Doc for Java allows developers to convert Word documents to password-protected PDF documents by using the Document.saveToFile(String, ToPdfParameterList) method. The ToPdfParameterList parameter controls how a Word document will be converted to PDF, for example, whether to encrypt the result PDF during the conversion.

1. Create a Document instance.
2. Load a Word document using Document.loadFromFile() method.
3. Create a ToPdfParameterList instance.
4. Set open password and permission password for PDF using ToPdfParameterList.getPdfSecurity().encrypt() method.
5. Save the Word document to PDF with password using Document.saveToFile(String, ToPdfParameterList) method.

import com.spire.doc.Document;
import com.spire.doc.ToPdfParameterList;
import com.spire.pdf.security.PdfEncryptionKeySize;
import com.spire.pdf.security.PdfPermissionsFlags;

public class ConvertWordToPasswordProtectedPDF {
    public static void main(String[] args){

        //Create a Document instance
        Document document = new Document();
        //Load a Word document
        document.loadFromFile("Sample.docx");

        //Create a ToPdfParameterList instance
        ToPdfParameterList toPdf = new ToPdfParameterList();
        //Set open password and permission password for PDF
        String password = "password";
        toPdf.getPdfSecurity().encrypt(password, password, PdfPermissionsFlags.None, PdfEncryptionKeySize.Key_128_Bit);

        //Save the Word document to PDF with password
        document.saveToFile("ToPdfWithPassword.pdf", toPdf);
    }
}

Output:

The converted PDF Document

Convert PDF to Word or Excel in Java

PDF is one of the most commonly used file formats, however it’s much more difficult to edit a PDF document comparing with editing Word or Excel documents. In some cases, we may need to convert PDF documents to Word or Excel. In this article, I am going to demonstrate how to achieve this task programmatically using Java.

Add Dependencies

In order to convert PDF to Word or Excel, I will use Spire.PDF for Java which is a powerful and multifunctional API for creating, manipulating and converting PDF documents.

You can either download the API’s jar from this link or install it from Maven by adding the following code to your maven-based project’s pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>4.10.2</version>
    </dependency>
</dependencies>

Convert PDF to Word or Excel

Converting PDF to Word or Excel is pretty easy with Spire.PDF for Java API. You just need to follow two steps below:

1. Load a PDF document using PdfDocument class.
2. Save the PDF document to Word or Excel using PdfDocument.saveToFile(String, FileFormat) method.

The following code example demonstrates how to convert a PDF document to Word and Excel:

import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;

public class ConvertPdfToWord {
    public static void main(String[] args) {
        //Load a sample PDF document
        PdfDocument pdf = new PdfDocument("Sample.pdf");

        //Save the PDF document as Word DOCX format
        pdf.saveToFile("ToWord.docx", FileFormat.DOCX);

        //Save the PDF document as Excel XLSX format
        pdf.saveToFile("ToExcel.xlsx", FileFormat.XLSX);
    }
}

The input PDF:

The Input PDF

The converted Word:

The Word Document Converted from PDF

The converted Excel:

The Excel document converted from PDF

C#/VB.NET: Generate QR Code with a Custom Logo Image

When you generate a QR code, you might want to add a custom image such as your company’s logo or your personal profile image to it.  In this article, I will describe how to achieve this task programmatically in C# and VB.NET.

Add Reference

In order to generate QR code and add logo image, I will use Spire.Barcode for .NET API which supports generating and reading up to 39 kinds of 1D and 2D barcodes.

You can either download the API from here or install it via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console and then adding the following code:

PM> Install-Package Spire.Barcode

Generate QR Code with a Custom Logo Image

The following are the steps to generate a QR code with a custom logo image:

1. Instantiate a BarcodeSettings object.
2. Specify barcode type, error correction level, barcode width and data etc. using BarcodeSettings.Type, BarcodeSettings.QRCodeECL, BarcodeSettings.X and BarcodeSetting.Data attributes etc.
3. Add a custom image to the QR code using BarcodeSettings.QRCodeLogoImage attribute.
4. Instantiate a BarCodeGenerator object.
5. Generate QR code image using BarCodeGenerator.GenerateImage() method.
6. Save the image using Image.Save() method.

C#

using Spire.Barcode;
using System.Drawing;

namespace GenerateQRCodeWithLogo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load a license file if you have one
            //Spire.License.LicenseProvider.SetLicenseFileFullPath("licensePath");

            //Instantiate a BarcodeSettings object
            BarcodeSettings settings = new BarcodeSettings();

            //Specify barcode type, data, etc.
            settings.Type = BarCodeType.QRCode;
            settings.QRCodeECL = QRCodeECL.M;
            settings.ShowText = false;
            settings.X = 2.5f;
            string data = "https://twitter.com";
            settings.Data = data;
            settings.Data2D = data;

            //Add an image to QR code
            settings.QRCodeLogoImage = Image.FromFile(@"C:\Users\Administrator\Desktop\Logo.png");

            //Instantiate a BarCodeGenerator object
            BarCodeGenerator generator = new BarCodeGenerator(settings);
            //Generate QR image
            Image image = generator.GenerateImage();
            //Save the image
            image.Save("QR.png", System.Drawing.Imaging.ImageFormat.Png);            
        }
    }
}

VB.NET

Imports Spire.Barcode

Namespace GenerateQRCodeWithLogo
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Load a license file if you have one
            'Spire.License.LicenseProvider.SetLicenseFileFullPath("licensePath")

            'Instantiate a BarcodeSettings object
            Dim settings As BarcodeSettings = New BarcodeSettings()

            'Specify barcode type, data, etc.
            settings.Type = BarCodeType.QRCode
            settings.QRCodeECL = QRCodeECL.M
            settings.ShowText = False
            settings.X = 2.5F
            Dim data As String = "https://twitter.com"
            settings.Data = data
            settings.Data2D = data

            'Add an image to QR code
            settings.QRCodeLogoImage = Image.FromFile("C:\Users\Administrator\Desktop\Logo.png")

            'Instantiate a BarCodeGenerator object
            Dim generator As BarCodeGenerator = New BarCodeGenerator(settings)
            'Generate QR image
            Dim image As Image = generator.GenerateImage()
            'Save the image
            image.Save("QR.png", Drawing.Imaging.ImageFormat.Png)
        End Sub
    End Class
End Namespace

The generated QR code with logo image:

QR code with Logo Image

Get a Free Trial License

The library will generate an evaluation watermark on the barcode image, you can request a free 30 days trial license to remove the watermark from the image.

Export Data from Database to Excel in Java

Introduction

Export data from database to Excel is always a common task for developers. In this article, I am going to describe how to achieve this task programmatically using Java.

Add Dependencies

MySql database is used in this example. In order to fetch the database data, I will use JDBC. To save data to Excel, I will use Spire.XLS for Java API.

To begin with, you need to add the following configurations to your maven project’s pom.xml file for MySql JDBC Driver and Spire.XLS for Java API.

<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</artifactId>
            <version>4.9.0</version>
        </dependency>
 
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>
    </dependencies>

Export data from Database to Excel

To export data from database to Excel, you can follow the following steps:

  • Connect to the database.
  • Fetch the desired data in database into a ResultSet object using Statement.executeQuery() method.
  • Instantiate a DataTable object.
  • Instantiate a JdbcAdapter object and call JdbcAdapter.fillDataTable() method to fill data in ResultSet into the DataTable.
  • Instantiate a Workbook object and get the first worksheet using WorksheetsCollection.get(int sheetIndex) method.
  • Insert data from DataTable to the worksheet using Worksheet.insertDataTable() method.
  • Save the result file using Workbook.saveToFile() method.

The following are the import statements that need to be added before compiling the code:

import com.spire.data.table.DataTable;
import com.spire.data.table.common.JdbcAdapter;
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
 
import java.sql.*;

The following code shows how to export data from Database to Excel:

String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/pcb";
String userName = "root";
String password = "123456";


try {
    //Connect to the database
    Class.forName(driverName);
    Connection connection = DriverManager.getConnection(url, userName, password);
    Statement statement = connection.createStatement();
    String sql = "select * from employees";
    //Fetch the desired data into a ResultSet object
    ResultSet resultSet = statement.executeQuery(sql);

    //Instantiate a DataTable object
    DataTable datatable = new DataTable();
    //Instantiate a JdbcAdapter object
    JdbcAdapter jdbcAdapter = new JdbcAdapter();
    //Fill data into DataTable
    jdbcAdapter.fillDataTable(datatable, resultSet);

    //Instantiate a Workbook object
    Workbook workbook = new Workbook();
    //Get the first worksheet
    Worksheet sheet = workbook.getWorksheets().get(0);
    //Export data from DatTable to the worksheet
    sheet.insertDataTable(datatable, true, 1, 1);

    //Save the result file
    workbook.saveToFile("test.xlsx", ExcelVersion.Version2013);
    resultSet.close();
    statement.close();
    connection.close();
} catch (SQLException e) {
    e.printStackTrace();
} catch (Exception e) {
    e.printStackTrace();
}

The “employees” data table in MySql database:

The output Excel file:

Extract Table Data from PDF in Java

PDF invoices often contain tabular data, in some circumstance, you may want to extract the tabular data to perform data analysis. In this article, you will learn how to achieve this task programmatically using Java.

Install Spire.PDF for Java

In order to extract PDF table data, I will use Spire.PDF for Java which is a powerful and multifunctional API for creating, manipulating, converting and printing PDF documents.

You can either download the API’s jar from this link or install it from Maven by adding the following code to your maven-based project’s pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>4.10.2</version>
    </dependency>
</dependencies>

Extract Table Data from PDF Document

Spire.PDF for Java uses the PdfTableExtractor.extractTable(int pageIndex) method to detect and extract tables from a desired PDF page.

The following are the steps to extract table data from a PDF file:

1. Load a sample PDF document using PdfDocument class.
2. Create a StringBuilder instance and a PdfTableExtractor instance.
3. Loop through the pages in the PDF, extract tables from each page into a PdfTable array using PdfTableExtractor.extractTable(int pageIndex) method.
4. Loop through the tables in the array.
5. Loop through the rows and columns in each table, after that extract data from each table cell using PdfTable.getText(int rowIndex, int columnIndex) method, then append the data to the StringBuilder instance using StringBuilder.append() method.
6. Write the extracted data to a txt document using Writer.write() method.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.utilities.PdfTable;
import com.spire.pdf.utilities.PdfTableExtractor;

import java.io.FileWriter;

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

        //Load a sample PDF document
        PdfDocument pdf = new PdfDocument("Table.pdf");

        //Create a StringBuilder instance
        StringBuilder builder = new StringBuilder();
        //Create a PdfTableExtractor instance
        PdfTableExtractor extractor = new PdfTableExtractor(pdf);

        //Loop through the pages in the PDF
        for (int pageIndex = 0; pageIndex < pdf.getPages().getCount(); pageIndex++) {
            //Extract tables from the current page into a PdfTable array
            PdfTable[] tableLists = extractor.extractTable(pageIndex);
            
            //If any tables are found
            if (tableLists != null && tableLists.length > 0) {
                //Loop through the tables in the array
                for (PdfTable table : tableLists) {
                    //Loop through the rows in the current table
                    for (int i = 0; i < table.getRowCount(); i++) {
                        //Loop through the columns in the current table
                        for (int j = 0; j < table.getColumnCount(); j++) {
                            //Extract data from the current table cell and append to the StringBuilder 
                            String text = table.getText(i, j);
                            builder.append(text + " | ");
                        }
                        builder.append("\r\n");
                    }
                }
            }
        }

        //Write data into a .txt document
        FileWriter fw = new FileWriter("ExtractTable.txt");
        fw.write(builder.toString());
        fw.flush();
        fw.close();
    }
}

The input PDF:

The Input PDF with Table

The output .txt document with extracted table data:

The TXT Document with Data Extracted from PDF Table

See Also

C#/VB.NET: Read or Extract Table Data from PDF File

C#/VB.NET: Read or Extract Table Data from PDF File

Extracting table data is required if you have some PDF invoices with tabular data and you want to extract data from them to perform data analysis. In this article, I will demonstrate how to achieve this task programmatically using C# and VB.NET.

Installation

To extract PDF table data, I will use Spire.PDF for .NET which is a powerful and multifunctional API for creating, manipulating, converting and printing PDF documents.

You can either download Spire.PDF for .NET API from here or install it via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console and then adding the following code:

PM> Install-Package Spire.PDF

Read or Extract Table Data from PDF File

Spire.PDF for .NET uses the PdfTableExtractor.ExtractTable(int pageIndex) method to detect and extract tables from a desired PDF page.

The following are the steps to extract table data from a PDF file:

1. Load a PDF document using PdfDocument class.
2. Create a StringBuilder instance.
3. Loop through the pages in the PDF, create a PdfTableExtractor instance, and extract table(s) from each page into a PdfTable array using PdfTableExtractor.ExtractTable(int pageIndex) method.
4. Loop through the tables in the array, then loop through the rows and columns in each table using PdfTable.GetRowCount() and PdfTable.GetColumnCount() methods.
5. Extract data from each table cell using PdfTable.GetText(int rowIndex, int columnIndex) method, then append the data to the StringBuilder instance using StringBuilder.Append(string) method.
6. Write the extracted data to a txt document using File.WriteAllText(string, string) method.

C# Code

using Spire.Pdf;
using Spire.Pdf.Utilities;
using System.IO;
using System.Text;

namespace ExtractTableData
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load a PDF document using PdfDocument class
            PdfDocument pdf = new PdfDocument("Sample.pdf");

            //Create a StringBuilder instance
            StringBuilder builder = new StringBuilder();

            //Loop through the pages in the PDF document
            for (int pageIndex = 0; pageIndex < pdf.Pages.Count; pageIndex++)
            {
                //Create a PdfTableExtractor instance
                PdfTableExtractor extractor = new PdfTableExtractor(pdf);

                //Extract table(s) from each page into a PdfTable array
                PdfTable[] tableLists = extractor.ExtractTable(pageIndex);

                if (tableLists != null && tableLists.Length > 0)
                {
                    //Loop through tables in the PdfTable array
                    foreach (PdfTable table in tableLists)
                    {
                        //Loop through each table row
                        for (int i = 0; i < table.GetRowCount(); i++)
                        {
                            //Loop through each table column
                            for (int j = 0; j < table.GetColumnCount(); j++)
                            {
                                //Extract data from each table cell
                                string text = table.GetText(i, j);
                                //Append data to the StringBuilder instance
                                builder.Append(text + "  |  ");
                            }
                            builder.Append("\r\n");
                        }
                    }
                }
            }

            //Write data into a .txt document
            File.WriteAllText("ExtractTable.txt", builder.ToString());
        }
    }
}

VB.NET code

Imports Spire.Pdf
Imports Spire.Pdf.Utilities
Imports System.IO
Imports System.Text

Namespace ExtractTableData
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Load a PDF document using PdfDocument class
            Dim pdf As PdfDocument = New PdfDocument("Sample.pdf")

            'Create a StringBuilder instance
            Dim builder As StringBuilder = New StringBuilder()

            'Loop through the pages in the PDF document
            For pageIndex As Integer = 0 To pdf.Pages.Count - 1
                'Create a PdfTableExtractor instance
                Dim extractor As PdfTableExtractor = New PdfTableExtractor(pdf)

                'Extract table(s) from each page into a PdfTable array
                Dim tableLists As PdfTable() = extractor.ExtractTable(pageIndex)

                If tableLists IsNot Nothing AndAlso tableLists.Length > 0 Then

                    'Loop through tables in the PdfTable array
                    For Each table As PdfTable In tableLists

                        'Loop through each table row
                        For i As Integer = 0 To table.GetRowCount() - 1

                            'Loop through each table column
                            For j As Integer = 0 To table.GetColumnCount() - 1
                                'Extract data from each table cell
                                Dim text As String = table.GetText(i, j)
                                'Append data to the StringBuilder instance
                                builder.Append(text & "  |  ")
                            Next

                            builder.Append(vbCrLf)
                        Next
                    Next
                End If
            Next

            'Write data into a .txt document
            Call File.WriteAllText("ExtractTable.txt", builder.ToString())
        End Sub
    End Class
End Namespace

The input PDF:

The Input PDF Document

The txt document with extracted data:

The TXT Document with Data Extracted from PDF Table

Conclusion

This article demonstrated how to extract table data from PDF using Spire.PDF for .NET library. Apart from extracting table data, the library can also be used to extract text and images from PDF documents. You can explore more about it by visiting the documentation. If you have any question, you can post it on the forum.

Convert PowerPoint PPT/PPTX to PDF in Java

PowerPoint PPT or PPTX is the most popular file format for presentations, but viewing a PowerPoint document requires Microsoft PowerPoint or other equivalents to be installed on system. For users who don’t have PowerPoint, converting PowerPoint document to PDF might be a good choice. In this article, I will describe how to achieve this task programmatically using Java.

Add Dependencies

To convert PowerPoint PPT/PPTX to PDF, this article uses Spire.Presentation for Java, which is a multi-functional and easy-to-use third-party API for creating, converting and manipulating PowerPoint documents.

You can either download the API’s jar from here or install it from maven by adding the following configurations to your maven-based 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.presentation </artifactId>    
        <version>4.9.2</version>    
    </dependency>    
</dependencies>

Convert PowerPoint PPT/PPTX to PDF

There are two options to save your PowerPoint PPT/PPTX document to PDF:

1. Convert the whole PowerPoint PPT/PPTX document to PDF.
2. Convert specific slide(s) of the PowerPoint PPT/PPTX to PDF.

Convert the whole PowerPoint PPT/PPTX Document to PDF

The following are the steps to convert a PowerPoint PPT or PPTX document to PDF format:

1. Create a Presentation instance.
2. Load a PowerPoint PPT/PPTX document using Presentation.loadFromFile() method.
3. Save the document to PDF using Presentation.saveToFile() method with specified file path and FileFormat.

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

public class ConvertPowerPointToPDF {
    public static void main(String []args) throws Exception {
        //Create a Presentation instance
        Presentation ppt = new Presentation();
        //Load a PPT document
        //ppt.loadFromFile("Sample.ppt");
        //Load a PPTX document
        ppt.loadFromFile("Sample.pptx");
        
        //Save the document as PDF
        ppt.saveToFile("ToPDF.pdf", FileFormat.PDF);
    }
}

The input PowerPoint PPTX document:

Figure 1. Sample PPTX Document

The converted PDF:

Figure 2. Converted PDF from PPTX Document

Convert Specified Slide(s) of the PowerPoint PPT/PPTX to PDF

The following are the steps to convert a specific slide to PDF format:

1. Create a Presentation instance.
2. Load a PowerPoint PPT/PPTX document using Presentation.loadFromFile() method.
3. Get the desired slide by using its index.
4. Save the document to PDF using ISlide.saveToFile() method with specified file path and FileFormat.

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

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

        //Create a Presentation instance
        Presentation ppt = new Presentation();
       //Load a PPT document
        //ppt.loadFromFile("Sample.ppt");
        //Load a PPTX document
        ppt.loadFromFile("Sample.pptx");

        //Get the second slide
        ISlide slide= ppt.getSlides().get(1);
        
        //Save the slide as PDF
        slide.SaveToFile("SpecificSlideToPDF.pdf", FileFormat.PDF);
    }
}

The second slide:

Figure 3. The Specific Slide

The converted PDF:

Figure 4. Converted PDF from Specific Slide

Java: Shrink Text to Fit in Shape or Resize Shape to Fit Text in PowerPoint

When inserting text into a PowerPoint shape, we may discover that sometimes the text is so long that it overflows the shape, or the shape is too large for the text. For such case, Microsoft PowerPoint provides the following autofit options which allows us to automatically shrink text to fit in a shape, or to resize a shape to fit text:

MS PowerPoint Autofit Options

In this article, I will describe how to achieve this task programmatically using Java.

Add Dependencies

To shrink text or resize shape in PowerPoint, this article uses Free Spire.Presentation for Java, which is a free and multi-functional third-party API for creating, converting and manipulating PowerPoint documents.

You can either download the API’s jar from here or install it from maven by adding the following configurations to your maven-based 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.presentation.free</artifactId>    
        <version>3.9.0</version>    
    </dependency>    
</dependencies>

Implementation

Free Spire.Presentation for Java API provides a ITextFrameProperties.setAutofitType() method which can be used to shrink text to fit in a shape or resize a shape to fit text. This method accepts the following parameter:

TextAutofitType: specifies the autofit type of a shape.

To shrink text to fit in a shape or to resize a shape to fit text, you can follow the below steps:

1. Create a Presentation instance.
2. Get the first slide by using its index (zero-based).
3. Add a shape to the slide using ShapeList.appendShape() method.
4. Add text to the shape using ITextFrameProperties.setText() method.
5. Call ITextFrameProperties.setAutofitType() method to set the autofit option of the shape. For shrinking text, set the AutofitType as TextAutofitType.NORMAL. For resizing shape to fit text, set the AutofitType as TextAutofitType.SHAPE.
6. Save the result document using Presentation.saveToFile() method.

import com.spire.presentation.*;
import com.spire.presentation.drawing.FillFormatType;

import java.awt.*;

public class ShrinkTextOrResizeShape {
    public static void main(String []args) throws Exception {
        //Create a Presentation instance
        Presentation ppt = new Presentation();
        //If you want to load an existing document, use loadFromFile method
        //ppt.loadFromFile("Input.pptx");

        //Get the first slide
        ISlide slide = ppt.getSlides().get(0);

        //Add a shape to the slide
        //If you want to get an existing shape, use slide.getShapes.get(shapeIndex) method
        IAutoShape shape = slide.getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle(100, 100, 150, 80));
        shape.getFill().setFillType(FillFormatType.NONE);
        ITextFrameProperties textFrame = shape.getTextFrame();
        //Add text to the shape
        textFrame.setText("Shrink text to fit in shape. Shrink text to fit in shape. Shrink text to fit in shape. Shrink text to fit in shape.");
        textFrame.getTextRange().getFill().setFillType(FillFormatType.SOLID);
        textFrame.getTextRange().getFill().getSolidColor().setColor(Color.BLACK);
        //Shrink text to fit in the shape by setting the AutofitType as normal
        textFrame.setAutofitType(TextAutofitType.NORMAL);

        //Add a shape to the slide
        shape = slide.getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle(350, 100, 150, 80));
        shape.getFill().setFillType(FillFormatType.NONE);
        textFrame = shape.getTextFrame();
        //Add text to the shape
        textFrame.setText("Resize shape to fit text.");
        textFrame.getTextRange().getFill().setFillType(FillFormatType.SOLID);
        textFrame.getTextRange().getFill().getSolidColor().setColor(Color.BLACK);
        //Resize shape to fit text by setting the AutofitType as shape
        textFrame.setAutofitType(TextAutofitType.SHAPE);

        //Save the document
        String result = "ShrinkTextOrResizeShape.pptx";
        ppt.saveToFile(result, FileFormat.PPTX_2013);
    }
}

Output:

Figure 1. Shrink Text to Fit in a Shape
Figure 2. Resize a shape to fit text

Convert PDF to Images (JPG, PNG, TIFF, SVG) in Java

Images are used almost everywhere in our daily life. In some circumstances, you may need to convert documents in other format like PDF to images. In this article, I am going to describe how to convert PDF document to image formats such as PNG, JPG, TIFF and SVG programmatically using Java.

Add Dependencies

To convert PDF to Images, this article uses Spire.PDF for Java, which is a multi-functional third-party API for creating, manipulating and converting PDF documents.

You can either download the API’s jar from here or install it from maven by adding the following configurations to your maven-based 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</artifactId>    
        <version>4.9.5</version>    
    </dependency>    
</dependencies>

Convert PDF to PNG/JPG

Spire.PDF for Java uses the PdfDocument.saveAsImage() method to convert PDF document to PNG/JPG images. This method accepts an int parameter which specifies the index of a desired PDF page.

To convert a PDF document to PNG/JPG images, you can follow the following steps:

1. Create a PdfDocument instance.
2. Load a PDF document using PdfDocument.loadFromFile() method.
3. Traverse through the pages in the PDF, and then save every page to image using PdfDocument.saveAsImage() method.

import com.spire.pdf.PdfDocument;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ConvertPdfToPngOrJpg {
    public static void main(String[] args) throws IOException {

        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();
        //Load a PDF document
        pdf.loadFromFile("sample.pdf");
        
        BufferedImage image;
        //Traverse through the pages in the PDF
        for (int i = 0; i < pdf.getPages().getCount(); i++) {
            //Save every page as PNG image
            image = pdf.saveAsImage(i);
            File file = new File( "output/" + String.format(("ToImage-img-%d.png"), i));
            ImageIO.write(image, "PNG", file);
        }
        pdf.close();
    }
}

The input PDF:

The input PDF

Converted PNG images:

PNG images converted from PDF

Convert PDF to TIFF

Spire.PDF for Java provides the ability to convert PDF document to multi-page TIFF by using the PdfDocument.saveToTiff() method. You can convert particular PDF page(s) to TIFF or convert a whole PDF document to TIFF, furthermore, you can also specify the resolution of the TIFF when performing conversion.

The following example shows how to convert all pages in a PDF document to TIFF with specified resolution.

import com.spire.pdf.PdfDocument;

public class ConvertPdfToTiff {
    public static void main(String[] args) {

        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();
        //Load a PDF document
        pdf.loadFromFile("sample.pdf");
        
        //Save the document to Tiff
        //pdf.saveToTiff("output/page1toTiff.tiff");
        
        //Save all PDF pages to Tiff with specified resolution
        pdf.saveToTiff("output/page2toTiff.tiff", 0, pdf.getPages().getCount() - 1,200, 200);
    }
}

The converted TIFF:

Converted TIFF from PDF

Convert PDF to SVG

To convert PDF to SVG, you can use the PdfDocument.saveToFile method. This method accepts the following parameters:

String: specifies the file path of the converted SVG.

FileFormat: Specifies the desired file format that the PDF document will be saved to.

import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;

public class ConvertPdfToSvg {
    public static void main(String[] args) {

        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();
        //Load a PDF document
        pdf.loadFromFile("sample.pdf");

        //Save the document to Svg
        pdf.saveToFile("output/toSVG_result.svg", FileFormat.SVG);
        pdf.close();
    }
}

The converted SVG:

Converted SVG from PDF
Design a site like this with WordPress.com
Get started