Monday, 26 November 2018 07:02

Find and Highlight Text in PDF in Java

This article is going to demonstrate how to find and highlight text using Spire.PDF for Java.

The example PDF file:

Find and Highlight Text in PDF in Java

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.general.find.PdfTextFind;

import java.awt.*;

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

        PdfTextFind[] result;
        //Find and highlight the string “New Zealand” in every PDF page
        for(PdfPageBase page:(Iterable)pdf.getPages())
        {
            result = page.findText("New Zealand").getFinds();
            for (PdfTextFind find:result) 
            {
                find.applyHighLight(Color.yellow);
            }
        }

        //Save the file
        pdf.saveToFile("HighlightText.pdf");
    }
}

Output:

Find and Highlight Text in PDF in Java

Monday, 26 November 2018 03:39

Add Image Stamps to PDF in Java

This tutorial introduces how to add an image stamp to a PDF document using Spire.PDF for Java.

import com.spire.pdf.annotations.PdfRubberStampAnnotation;
import com.spire.pdf.annotations.appearance.PdfAppearance;
import com.spire.pdf.graphics.PdfImage;
import com.spire.pdf.graphics.PdfTemplate;

import java.awt.geom.Rectangle2D;

public class ImageStamp {

    public static void main(String[] args) {

        //create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        //load a PDF document
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");

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

        //load an image file
        PdfImage image = PdfImage.fromFile("C:\\Users\\Administrator\\Desktop\\quality-control-stamp.png");

        //get the width and height of the image
        int width = image.getWidth();
        int height = image.getHeight();

        //create a PdfTemplate object based on the size of the image
        PdfTemplate template = new PdfTemplate(width, height);

        //draw image on the template
        template.getGraphics().drawImage(image, 0, 0, width, height);

        //create a rubber stamp annotation, specifying its location and position
        Rectangle2D rect = new Rectangle2D.Float((float) (page.getActualSize().getWidth() - width - 50), (float) (page.getActualSize().getHeight() - height - 80), width, height);
        PdfRubberStampAnnotation stamp = new PdfRubberStampAnnotation(rect);

        //create a PdfAppearance object
        PdfAppearance pdfAppearance = new PdfAppearance(stamp);

        //set the template as the normal state of the appearance
        pdfAppearance.setNormal(template);

        //apply the appearance to the stamp
        stamp.setAppearance(pdfAppearance);

        //add the stamp annotation to PDF
        page.getAnnotationsWidget().add(stamp);

        //save the file
        doc.saveToFile("ImageStamp.pdf");
        doc.close();
    }
}

Output:

Add Image Stamps to PDF in Java

Friday, 23 November 2018 08:17

Split PDF Files in Java

Spire.PDF for Java allows splitting a pdf file by the following ways:

  • Split every page of the PDF into a separate file
  • Split the PDF into multiple files by a range of pages

Below code examples demonstrate how to use Spire.PDF for Java to split a PDF file.

The original PDF file:

Split PDF Files in Java

Split every page of the PDF into a separate file

import com.spire.pdf.*;

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

        //Load the PDF file
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("sample.pdf");

        //Split every page of the PDF into a separate file
        doc.split("output/splitDocument-{0}.pdf", 0);
        doc.close();
    }
}

Split PDF Files in Java

Split the PDF into multiple files by a range of pages

import com.spire.pdf.*;
import com.spire.pdf.graphics.PdfMargins;

import java.awt.geom.Point2D;

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

        //Load the PDF file
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("sample.pdf");

        //Create a new PDF file
        PdfDocument newDoc1 = new PdfDocument();

        PdfPageBase page;

        //Add 2 pages to the new PDF, and draw the content of page 1-2 of the original PDF to the new added pages 
        for(int i = 0;i<2;i++)
        {
            page = newDoc1.getPages().add(doc.getPages().get(i).getSize(), new PdfMargins(0));
            doc.getPages().get(i).createTemplate().draw(page, new Point2D.Float(0,0));
        }

        //Save the result file
        newDoc1.saveToFile("split/Doc1.pdf");

        //Create a new PDF file
        PdfDocument newDoc2 = new PdfDocument();

        //Add 3 pages to the new PDF, and draw the content of page 3-5 of the original PDF to the new added pages
        for(int i = 2;i<5;i++)
        {
            page = newDoc2.getPages().add(doc.getPages().get(i).getSize(), new PdfMargins(0));
            doc.getPages().get(i).createTemplate().draw(page, new Point2D.Float(0,0));
        }

        //Save the result file
        newDoc2.saveToFile("split/Doc2.pdf");
    }
}

Split PDF Files in Java

This article is going to demonstrate how to set background color and background image for a PDF file using Spire.PDF for Java.

The original PDF file:

Set Background Color and Background Image for PDF in Java

Set background color

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;

import java.awt.*;

public class SetBackgroundColor {
    public static void main(String[] args) {
        
        //Load PDF file
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("original.pdf");

        PdfPageBase page;
        int pageCount = doc.getPages().getCount();

        //Set Background color
        for(int i = 0; i < pageCount; i ++) {
            page = doc.getPages().get(i);
            page.setBackgroundColor(Color.yellow);
        }

        //Save the file
        doc.saveToFile("BackgroundColor.pdf");
    }
}

Output:

Set Background Color and Background Image for PDF in Java

Set background image

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;

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

        //Load PDF file
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("original.pdf");
        
        PdfPageBase page;
        int pageCount = doc.getPages().getCount();

        //Set background image
        for(int i = 0; i < pageCount; i ++) {
            page = doc.getPages().get(i);
            page.setBackgroundImage("Background.jpg");
        }

        //Save the file
        doc.saveToFile("BackgroundImage.pdf");
    }
}

Output:

Set Background Color and Background Image for PDF in Java

Wednesday, 21 November 2018 08:48

JAVA add image watermark to PDF

This article will demonstrate how to use Spire.PDF for Java to add image watermark to PDF.

We need to load the image by the method loadFromFile() and then, set the PDF background image to be the image watermark and then set the background region for the image.

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

public class watermark {

    public static void main(String[] args) {

        //Create a pdf document and load the sample document from file
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.pdf");
        
        //Get the first page
        PdfPageBase page = doc.getPages().get(0);  

        //Load the image and set it as background image
        page.setBackgroundImage("C:\\Users\\Administrator\\Desktop\\logo.png");

        //Set the background region
        Rectangle2D.Float rect = new Rectangle2D.Float();
        rect.setRect(280, 300, 150, 150);
        page.setBackgroundRegion(rect);

        //Save pdf file
        doc.saveToFile("output/imageWaterMark.pdf");
        doc.close();

    }
}

JAVA add image watermark to PDF

Tuesday, 20 November 2018 09:08

Add Dynamic Stamps to PDF in Java

A dynamic PDF stamp usually consists of some dynamic information, such as system date and time, and other information like company name, “Approved By” and so on. This article will introduce how to add a dynamic rubber stamp to PDF by using Spire.PDF for Java.

import com.spire.pdf.annotations.PdfRubberStampAnnotation;
import com.spire.pdf.annotations.appearance.PdfAppearance;
import com.spire.pdf.graphics.*;

import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.text.SimpleDateFormat;

public class DynamicStamp {

    public static void main(String[] args) {

        //create a PdfDocument object
        PdfDocument document = new PdfDocument();

        //load a PDF file
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.pdf");

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

        //create a pdf template
        PdfTemplate template = new PdfTemplate(185, 50);

        //create two fonts
        PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Elephant", Font.ITALIC,16), true);
        PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", Font.ITALIC  ,10), true);

        //create a solid brush and a gradient brush
        PdfSolidBrush solidBrush = new PdfSolidBrush(new PdfRGBColor(Color.blue));
        Rectangle2D rect1 = new Rectangle2D.Float();
        rect1.setFrame(new Point2D.Float(0,0),template.getSize());
        PdfLinearGradientBrush linearGradientBrush = new PdfLinearGradientBrush(rect1,new PdfRGBColor(Color.white),new PdfRGBColor(Color.orange),PdfLinearGradientMode.Horizontal);

        //create rounded rectangle path
        int CornerRadius = 20;
        PdfPath path = new PdfPath();
        path.addArc(template.getBounds().getX(), template.getBounds().getY(), CornerRadius, CornerRadius, 180, 90);
        path.addArc(template.getBounds().getX() + template.getWidth() - CornerRadius,template.getBounds().getY(), CornerRadius, CornerRadius, 270, 90);
        path.addArc(template.getBounds().getX() + template.getWidth() - CornerRadius, template.getBounds().getY()+ template.getHeight() - CornerRadius, CornerRadius, CornerRadius, 0, 90);
        path.addArc(template.getBounds().getX(), template.getBounds().getY() + template.getHeight() - CornerRadius, CornerRadius, CornerRadius, 90, 90);
        path.addLine( template.getBounds().getX(), template.getBounds().getY() + template.getHeight() - CornerRadius, template.getBounds().getX(), template.getBounds().getY() + CornerRadius / 2);

        //draw path on the template
        template.getGraphics().drawPath(linearGradientBrush, path);
        template.getGraphics().drawPath(PdfPens.getRed(), path);

        //draw dynamic text on the template
        String s1 = "REVISED\n";
        String s2 = "By E-iceblue at " + dateToString(new java.util.Date(),"yyyy-MM-dd HH:mm:ss");
        template.getGraphics().drawString(s1, font1, solidBrush, new Point2D.Float(5, 5));
        template.getGraphics().drawString(s2, font2, solidBrush, new Point2D.Float(2, 28));

        //create a rubber stamp, specifying its size and location
        Rectangle2D rect2= new Rectangle2D.Float();
        rect2.setFrame(new Point2D.Float((float)(page.getActualSize().getWidth()-250),(float)(page.getActualSize().getHeight()-120)),  template.getSize());
        PdfRubberStampAnnotation stamp = new PdfRubberStampAnnotation(rect2);

        //create a PdfAppearance object and apply the template as its normal state
        PdfAppearance appearance = new PdfAppearance(stamp);
        appearance.setNormal(template);

        //apply the appearance to stamp
        stamp.setAppearance(appearance);

        //add the stamp annotation to annotation collection
        page.getAnnotationsWidget().add(stamp);

        //save the file
        document.saveToFile("DynamicStamp.pdf");
        document.close();
    }

    //convert date to string
    public static String dateToString(java.util.Date date,String dateFormat) {
        SimpleDateFormat format = new SimpleDateFormat(dateFormat);
        return format.format(date);
    }
}

Output:

Add Dynamic Stamps to PDF in Java

Monday, 19 November 2018 08:31

Align Text in PDF in Java

When drawing text on PDF page, you can align text horizontally and vertically. This tutorial will show you how to align text in a line and a rectangle by using Spire.PDF for Java.

Align Text in Line

import com.spire.pdf.graphics.*;

import java.awt.*;

public class AlignTextInLine {

    public static void main(String[] args) {

        //create a PdfDocument object 
        PdfDocument doc = new PdfDocument();

        //add a page 
        PdfPageBase page = doc.getPages().add();

        //create a true type font
        PdfTrueTypeFont font= new PdfTrueTypeFont(new Font("Times New Roman",Font.PLAIN,15));

        //create a brush 
        PdfSolidBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.black));

        //create a PdfStringFormat object, specifying PdfTextAlignment to Left
        PdfStringFormat leftAlignment = new PdfStringFormat(PdfTextAlignment.Left);

        //draw text at left 
        page.getCanvas().drawString("Left", font , brush, 0, 20, leftAlignment);

        //draw text at right 
        PdfStringFormat rightAlignment = new PdfStringFormat(PdfTextAlignment.Right);
        page.getCanvas().drawString("Right", font , brush, page.getCanvas().getClientSize().getWidth(), 20, rightAlignment);

        //draw text in center 
        PdfStringFormat centerAlignment = new PdfStringFormat(PdfTextAlignment.Center);
        page.getCanvas().drawString("Center", font , brush, page.getCanvas().getClientSize().getWidth() / 2, 20, centerAlignment);

        //save the file 
        doc.saveToFile("AlignTextInLine.pdf");
    }
}

Output:

Align Text on PDF in Java

Align Text in Rectangle

import com.spire.pdf.graphics.*;

import java.awt.*;
import java.awt.geom.Rectangle2D;

public class AlignTextInRectangle {

    public static void main(String[] args) {

        //create a PdfDocument object 
        PdfDocument doc = new PdfDocument();

        //add a page 
        PdfPageBase page = doc.getPages().add();

        //create a true type font
        PdfTrueTypeFont font= new PdfTrueTypeFont(new Font("Times New Roman",Font.PLAIN,15));

        //craete a pen 
        PdfPen pen = new PdfPen(new PdfRGBColor(Color.black));

        //create a brush 
        PdfSolidBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.black));

        //draw a rectangle 
        Rectangle2D.Float rect = new Rectangle2D.Float();
        rect.setRect(0, 20, page.getCanvas().getClientSize().getWidth() / 2, 100);
        page.getCanvas().drawRectangle(pen, rect);

        //create a PdfStringFormat object, specifying PdfTextAlignment to Top and Left
        PdfStringFormat topLeft = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Top);

        //draw text at top left
        page.getCanvas().drawString("TopLeft", font, brush, rect, topLeft);

        //draw text at top right 
        PdfStringFormat topRight = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Top);
        page.getCanvas().drawString("TopRight", font, brush, rect, topRight);

        //draw text in center 
        PdfStringFormat center = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
        page.getCanvas().drawString("Center", font, brush, rect, center);

        //draw text at bottom left 
        PdfStringFormat bottomLeft = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Bottom);
        page.getCanvas().drawString("BottomLeft", font, brush, rect, bottomLeft);

        //draw text at bottom right 
        PdfStringFormat bottomRight = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Bottom);
        page.getCanvas().drawString("BottomRight", font, brush, rect, bottomRight);

        //save the file 
        doc.saveToFile("AlignTextInRectangle.pdf");
    }
}

Output:

Align Text on PDF in Java

Wednesday, 14 November 2018 07:17

Create Table in PDF in Java

This article is going to show you how to create a table in a PDF file using Spire.PDF for Java.

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

public class CreateTable {
    public static void main(String[] args)
    {
        //Create a PdfDocument instance
        PdfDocument doc = new PdfDocument();

        //Set margins
        PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
        PdfMargins margin = new PdfMargins();
        margin.setTop(unitCvtr.convertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point));
        margin.setBottom(margin.getTop());
        margin.setLeft(unitCvtr.convertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point));
        margin.setRight(margin.getLeft());

        //Add one page
        PdfPageBase page = doc.getPages().add(PdfPageSize.A4, margin);

        float y = 10;

        //Draw title
        PdfBrush brush1 = PdfBrushes.getBlack();
        PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial",Font.BOLD ,16));
        PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);
        page.getCanvas().drawString("Country List", font1, brush1, page.getCanvas().getClientSize().getWidth() / 2, y, format1);
        y = y + (float) font1.measureString("Country List", format1).getHeight();
        y = y + 5;

        //Data source to create table
        String[] data = {"Name;Capital;Continent;Area;Population", "Argentina;Buenos Aires;South America;2777815;32300003", "Bolivia;La Paz;South America;1098575;7300000", "Brazil;Brasilia;South America;8511196;150400000", "Canada;Ottawa;North America;9976147;26500000", "Chile;Santiago;South America;756943;13200000", "Colombia;Bagota;South America;1138907;33000000", "Cuba;Havana;North America;114524;10600000", "Ecuador;Quito;South America;455502;10600000", "El Salvador;San Salvador;North America;20865;5300000", "Guyana;Georgetown;South America;214969;800000", "Jamaica;Kingston;North America;11424;2500000", "Mexico;Mexico City;North America;1967180;88600000", "Nicaragua;Managua;North America;139000;3900000", "Paraguay;Asuncion;South America;406576;4660000", "Peru;Lima;South America;1285215;21600000", "United States of America;Washington;North America;9363130;249200000", "Uruguay;Montevideo;South America;176140;3002000", "Venezuela;Caracas;South America;912047;19700000"};

        String[][] dataSource = new String[data.length][];
        for (int i = 0; i < data.length; i++) {
            dataSource[i] = data[i].split("[;]", -1);
        }

        //Create a PdfTable instance and set data source
        PdfTable table = new PdfTable();
        table.getStyle().setCellPadding(2);
        table.getStyle().setHeaderSource(PdfHeaderSource.Rows);
        table.getStyle().setHeaderRowCount(1);
        table.getStyle().setShowHeader(true);
        table.setDataSource(dataSource);

        //Draw table to the page
        PdfLayoutResult result = table.draw(page, new Point2D.Float(0, y));

        y = y + (float) result.getBounds().getHeight() + 5;

        //Draw string below table
        PdfBrush brush2 = PdfBrushes.getGray();
        PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 0,9));
        page.getCanvas().drawString(String.format("* %1$s countries in the list.", data.length - 1), font2, brush2, 5, y);

        //Save the file
        doc.saveToFile("output/Table.pdf");
    }
}

Output:

Create Table in PDF in Java

Tuesday, 13 November 2018 07:47

Merge PDF documents in JAVA

This article demonstrates how to merge PDF documents by using Spire.PDF for Java. We can merge the PDF documents by using the following two method on JAVA applications.

We use three PDF document for example. We load the PDF documents from file and select the first PdfDocument for the purpose of merging the second and third PDF file to it.

import com.spire.pdf.PdfDocument;
public class MergePDF {
    public static void main(String[] args) {
        //Pdf document list
        String[] files = new String[]
                {
                        "C:\\Users\\Administrator\\Desktop\\Sample01.pdf",
                        "C:\\Users\\Administrator\\Desktop\\Sample02.pdf",
                        "C:\\Users\\Administrator\\Desktop\\Sample03.pdf",
                };
        String outputFile = "output/MergeDocument.pdf";

        //Open pdf documents
        PdfDocument[] docs = new PdfDocument[files.length];
        PdfDocument doc = new PdfDocument();
        for (int i = 0; i < files.length; i++) {
            docs[i] = new PdfDocument();
            docs[i].loadFromFile(files[i]);
        }
        //Append document
        docs[0].appendPage(docs[1]);

        //import pages
        for (int i = 0; i < docs[2].getPages().getCount(); i = i + 2) {
            docs[0].insertPage(docs[2], i);
        }

        // Save pdf file.
        docs[0].saveToFile(outputFile);
        doc.close();
    }
}

Merge PDF documents in JAVA

Merge PDF document by stream. Input the three PDF documents by stream and then use mergeFiles(streams)methods to merge the PDF documents into one PDF document.

import com.spire.pdf.*;
import java.io.*;

public class MergePDF {

        public static void main(String[] args) throws Exception {
            String outputFile = "output/mergeFilesByStream.pdf";

            FileInputStream stream1 = new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\Sample01.pdf"));
            FileInputStream stream2 = new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\Sample02.pdf"));
            FileInputStream stream3 = new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\Sample03.pdf"));

            InputStream[] streams = new FileInputStream[]{stream1, stream2, stream3};

            //Merge files by stream
            PdfDocumentBase doc = PdfDocument.mergeFiles(streams);

            //Save the file
            doc.save(outputFile);
            doc.close();

        }
    }

Merge PDF documents in JAVA

Monday, 12 November 2018 07:34

Spire.PDF Program Guide Content for Java

Spire.PDF for Java is a PDF API that enables Java applications to read, write and save PDF documents without using Adobe Acrobat. Using this Java PDF component, developers and programmers can implement rich capabilities to create PDF files from scratch or process existing PDF documents entirely on Java applications (J2SE and J2EE).

Many rich features can be supported by Spire.PDF for Java, such as security settings, extract text/image from the PDF, merge/split PDF, draw text/image/shape/barcode to the PDF, create and fill in form fields, add and delete PDF layers, overlay PDF, insert text/image watermark to the PDF, add/update/delete PDF bookmarks, add tables to the PDF, compress PDF document etc. Besides, Spire.PDF for Java can be applied easily to convert PDF to XPS, XPS to PDF, PDF to SVG, and PDF to PDF/A in high quality.

Bookmark

Link

Attachments

Action

Page 2 of 100