Monday, 27 July 2020 06:52

Delete Bookmarks in PDF in Java

Spire.PDF for Java supports deleting a specific child bookmark, a parent bookmark along with its child bookmark(s) or delete all the bookmarks from a PDF file. In this article, you will learn how to delete PDF bookmarks using Spire.PDF for Java.

The input PDF file:

Delete Bookmarks in PDF in Java

import com.spire.pdf.PdfDocument;

public class DeleteBookmarks {
    public static void main(String[] args) {
        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();
        //Load the PDF file
        pdf.loadFromFile("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("DeleteBookmarks.pdf");
    }
}

The output PDF file after deleting the first child bookmark:

Delete Bookmarks in PDF in Java

Friday, 24 July 2020 05:43

How to Autofit a Word Table in Java

This article demonstrates how to auto fit a Word table to content or to window, as well as how to fix the cloumn widths, by using Spire.Doc for Java.

Autofit to content

import com.spire.doc.*;

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

        //Create a Document object
        Document document = new Document();

        //Add a section
        Section section = document.addSection();

        //Add a table
        Table table = section.addTable();
        table.resetCells(3, 2);

        //Add content to the cells
        table.get(0,0).addParagraph().appendText("Product Code");
        table.get(0,1).addParagraph().appendText("Description");
        table.get(1,0).addParagraph().appendText("T1052");
        table.get(1,1).addParagraph().appendText("AdvoCareSlim Tropical Swirl");
        table.get(2,0).addParagraph().appendText("T1062");
        table.get(2,1).addParagraph().appendText("AdvoCareSlim Caffeine Free Strawberry Kiwi");

        //Autofit column widths to contents
        table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents);

        //Save the document
        document.saveToFile("AutofitToContent.docx", FileFormat.Docx);
    }
}

How to Autofit a Word Table in Java

Autofit to window

import com.spire.doc.*;

public class AutofitToWindow {

    public static void main(String[] args) {

        //Create a Document object
        Document document = new Document();

        //Add a section
        Section section = document.addSection();

        //Add a table
        Table table = section.addTable();
        table.resetCells(3, 2);

        //Add content to the cells
        table.get(0,0).addParagraph().appendText("Product Code");
        table.get(0,1).addParagraph().appendText("Description");
        table.get(1,0).addParagraph().appendText("T1052");
        table.get(1,1).addParagraph().appendText("AdvoCareSlim Tropical Swirl");
        table.get(2,0).addParagraph().appendText("T1062");
        table.get(2,1).addParagraph().appendText("AdvoCareSlim Caffeine Free Strawberry Kiwi");

        //Autofit column widths to window
        table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Window);

        //Save the document
        document.saveToFile("AutofitToWindow.docx", FileFormat.Docx);
    }
}

How to Autofit a Word Table in Java

Fix column width

import com.spire.doc.*;

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

        //Create a Document object
        Document document = new Document();

        //Add a section
        Section section = document.addSection();

        //Add a table
        Table table = section.addTable();
        table.resetCells(3, 2);

        //Add content to the cells
        table.get(0, 0).addParagraph().appendText("Product Code");
        table.get(0, 1).addParagraph().appendText("Description");
        table.get(1, 0).addParagraph().appendText("T1052");
        table.get(1, 1).addParagraph().appendText("AdvoCareSlim Tropical Swirl");
        table.get(2, 0).addParagraph().appendText("T1062");
        table.get(2, 1).addParagraph().appendText("AdvoCareSlim Caffeine Free Strawberry Kiwi");

        //Set the column widths
        for (int i = 0; i < table.getRows().getCount(); i++) {

            table.get(i,0).setCellWidth(80f,CellWidthType.Point);
            table.get(i,1).setCellWidth(160f,CellWidthType.Point);
        }

        //Fix the column widths so that the column width does not increases when the content exceeds the width
        table.autoFit(AutoFitBehaviorType.Fixed_Column_Widths);

        //Save the document
        document.saveToFile("FixColumnWidths.docx", FileFormat.Docx);
    }
}

How to Autofit a Word Table in Java

This article demonstrates how to set the transparency of image on a PDF file using Spire.PDF for Java.

import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import java.awt.geom.*;
import java.awt.*;

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

        //Create a PDFDocument
        PdfDocument doc = new PdfDocument();
        //Add a section
        PdfSection section = doc.getSections().add();

        // Load image and set its width and height
        PdfImage image = PdfImage.fromFile("logo.png");
        double imageWidth = image.getPhysicalDimension().getWidth() / 3;
        double imageHeight = image.getPhysicalDimension().getHeight() / 3;

        //Add a page
        PdfPageBase page = section.getPages().add();
        float pageWidth = (float) page.getCanvas().getClientSize().getWidth();
        float y = 10;

        //Draw Title and set the font and format
        y = y + 5;
        PdfBrush brush = new PdfSolidBrush(new PdfRGBColor(new Color(255,69,0)));
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.BOLD,12));
        PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Center);
        String text = String.format(" Set image Transparency ");
        page.getCanvas().drawString(text, font, brush, pageWidth / 2, y, format);
        Dimension2D size = font.measureString(text, format);
        y = y + (float) size.getHeight() + 6;

        //Set image transparency
        page.getCanvas().setTransparency(0.2f, 0.2f, PdfBlendMode.Normal);

        //Add image to the page
        page.getCanvas().drawImage(image, 0, y, imageWidth, imageHeight);
        page.getCanvas().save();

        // Save pdf file.
        doc.saveToFile("output/Transparency.pdf");
        // Close pdf file
        doc.close();
    }
}

Effective screenshot after adding the image to PDF and set the image transparency:

Set image transparency on PDF file in Java

Monday, 20 July 2020 07:58

Edit Bookmarks in PDF in Java

This article demonstrates how to edit the existing bookmarks in a PDF file, for example, change the bookmark title, font color and text style using Spire.PDF for Java.

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 EditBookmarks {
    public static void main(String[] args) {
        //Create a PdfDocument instance
        PdfDocument doc = new PdfDocument();
        //Load the PDF file
        doc.loadFromFile("Bookmarks.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(255,0,0)));
        //Change the outline text style of the bookmark
        bookmark.setDisplayStyle(PdfTextStyle.Italic);

        //Edit child bookmarks of the first bookmark
        for (PdfBookmark childBookmark : (Iterable) bookmark) {
            childBookmark.setColor(new PdfRGBColor(new Color(0,0,255)));
            childBookmark.setDisplayStyle(PdfTextStyle.Bold);

            for (PdfBookmark childBookmark2 : (Iterable) childBookmark) {
                childBookmark2.setColor(new PdfRGBColor(new Color(160,160,122)) );
                childBookmark2.setDisplayStyle(PdfTextStyle.Bold);
            }
        }

        //Save the result file
        doc.saveToFile("EditBookmarks.pdf");
        doc.close();
    }
}

Output:

Edit Bookmarks in PDF in Java

This article will show you how to extract text from the specific area of a PDF page or a particular page of PDF.

Extract text from the defined area from one page of PDF:

import com.spire.pdf.*;
import java.awt.geom.Rectangle2D;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class ExtractText {
    public static void main(String[] args) throws Exception{
        //Load the PDF file
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("sample.pdf");

        //Create a new txt file to save the extracted text
        String result = "output/extractTextFromSpecificArea.txt";
        File file=new File(result);
        if(!file.exists()){
            file.delete();
        }
        file.createNewFile();
        FileWriter fw=new FileWriter(file,true);
        BufferedWriter bw=new BufferedWriter(fw);

        //Get the first page
        PdfPageBase page = pdf.getPages().get(0);

        //Extract text from a specific rectangular area within the page
        String text = page.extractText(new Rectangle2D.Float(80, 20, 500, 260));

        bw.write(text);

        bw.flush();
        bw.close();
        fw.close();
    }
}

Effective screenshot:

Java extract text from specific area or particular page of PDF

Extract text from a particular page of PDF:

import com.spire.pdf.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class ExtractText {
    public static void main(String[] args) throws Exception{
        //Load the PDF file
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("sample.pdf");

        //Create a new txt file to save the extracted text
        String result = "output/extractTextFromParticularPage.txt";
        File file=new File(result);
        if(!file.exists()){
            file.delete();
        }
        file.createNewFile();
        FileWriter fw=new FileWriter(file,true);
        BufferedWriter bw=new BufferedWriter(fw);

        //Get the third page
        PdfPageBase page = pdf.getPages().get(2);

        // Extract text from page keeping white space
        String text = page.extractText(true);

        // Extract text from page without keeping white space
        //String text = page.extractText(false);

        bw.write(text);

        bw.flush();
        bw.close();
        fw.close();
    }
}

Effective screenshot of the extract text from the third page:

Java extract text from specific area or particular page of PDF

Thursday, 16 July 2020 09:50

Add Bookmarks to PDF in Java

This article demonstrates how to add bookmarks and child bookmarks to a PDF file using Spire.PDF for Java.

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("Test.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, 0));
            bookmark.setAction(new PdfGoToAction(destination));
            //Set text color
            bookmark.setColor(new PdfRGBColor(new Color(139, 69, 19)));
            //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, 100));
            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("AddBookmarks.pdf");
    }
}

Output:

Add Bookmarks to PDF in Java

Thursday, 16 July 2020 07:13

Add Borders to Some Text in Word in Java

This article demonstrates how to apply a border around a set of charaters and how to apply a border around a whole paragraph, by using Spire.Doc for Java.

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.BorderStyle;
import com.spire.doc.documents.BreakType;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.TextRange;

import java.awt.*;

public class AddBorders {

    public static void main(String[] args) {

        //Create a Document instance
        Document doc = new Document();

        //Add a section
        Section section = doc.addSection();

        //Add a border to a set of characters
        Paragraph para = section.addParagraph();
        TextRange tr = para.appendText("Spire.Doc for Java");
        tr.getCharacterFormat().getBorder().setBorderType(BorderStyle.Single);
        tr.getCharacterFormat().getBorder().setColor(Color.BLACK);
        String text = " is a professional Java library specifically designed for developers to create, read, " +
                "write, convert and print Word document files on Java platform.";
        para.appendText(text);
        para.appendBreak(BreakType.Line_Break);

        //Add a border to a paragraph
        para = section.addParagraph();
        String text2 = "A plenty of Word document processing tasks can be performed by Spire.Doc for Java, such as " +
                "creating, reading, editing, converting and printing Word documents." ;
        para.appendText(text2);
        para.getFormat().getBorders().setBorderType(BorderStyle.Single);
        para.getFormat().getBorders().setColor(Color.BLACK);

        //Save the document
        doc.saveToFile("AddBorder.docx", FileFormat.Docx_2013);
    }
}

Add Borders to Some Text in Word in Java

Tuesday, 14 July 2020 09:35

Flatten Form Fields in PDF in Java

Flattening form fields is an efficient way to prevent other users from editing or deleting the information filled in PDF forms. After flattening, the filled in values will remain visible in the file but the form fields will no longer be editable. This article demonstrates how to flatten all the form fields in a PDF file by using Spire.PDF for Java.

Below is the screenshot of the input PDF file:

Flatten Form Fields in PDF in Java

import com.spire.pdf.PdfDocument;

public class FlattenFormFields {
    public static void main(String[] args) {
        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();
        //Load the PDF file
        pdf.loadFromFile("Form.pdf");

        //Flatten all the form fields in the PDF file
        pdf.getForm().isFlatten(true);

        //Save the result file
        pdf.saveToFile("Flatten.pdf");
        pdf.close();
    }
}

Output:

Flatten Form Fields in PDF in Java

This article demonstrates how to insert images to table cells in a Word document using Spire.Doc for Java.

import com.spire.doc.AutoFitBehaviorType;
import com.spire.doc.Document;
import com.spire.doc.Section;
import com.spire.doc.Table;
import com.spire.doc.fields.DocPicture;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class InsertImageToTableCell {

    public static void main(String[] args) throws FileNotFoundException {

        //Create a Document object
        Document document = new Document();

        //Add a section
        Section section  = document.addSection();

        //Add a table
        Table table = section.addTable(true);
        table.resetCells(2,2);
        table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents);

        //Load an image to InputStream
        InputStream inputStream = new FileInputStream("C:\\Users\\Administrator\\Desktop\\company-logo.png");
        
        //Insert the image to the cell(0,0)
        DocPicture picture = table.get(0,0).addParagraph().appendPicture(inputStream);
        
        //Set the width and height of the image
        picture.setWidth(100);
        picture.setHeight(100);

        //Insert another image to the cell(1,1)
        inputStream = new FileInputStream("C:\\Users\\Administrator\\Desktop\\intro.png");
        picture = table.get(1,1).addParagraph().appendPicture(inputStream);
        picture.setWidth(100);
        picture.setHeight(100);

        //Save the document
        document.saveToFile("InsertImgToCell.docx");
    }
}

Insert Images to a Table in Word in Java

Thursday, 09 July 2020 03:58

Convert PDF to Excel in C#, VB.NET

This article demonstrates how to convert a PDF file to Excel file format in C# and VB.NET by using Spire.PDF for .NET.

Below is the screenshot of the input PDF file:

Convert PDF to Excel in C#, VB.NET

Code Snippets:

C#
using Spire.Pdf;

namespace ConvertPDFToExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument instance
            PdfDocument pdf = new PdfDocument();
            //Load the PDF file
            pdf.LoadFromFile("Shopping list.pdf");

            //Save to Excel
            pdf.SaveToFile("PDFToExcel.xlsx", FileFormat.XLSX);
        }
    }
}
VB.NET
Imports Spire.Pdf

Namespace ConvertPDFToExcel
    Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a PdfDocument instance
            Dim pdf As PdfDocument = New PdfDocument()
            'Load the PDF file
pdf.LoadFromFile("Shopping list.pdf")
'Save to Excel	
            pdf.SaveToFile("PDFToExcel.xlsx", FileFormat.XLSX)
        End Sub
    End Class
End Namespace

Output:

Convert PDF to Excel in C#, VB.NET

Page 4 of 127