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 library, 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.

Monday, 12 November 2018 06:52

Draw Barcode on PDF in Java

Spire.PDF for Java supports the creation of Codebar, Code11, Code128A, Code128B, Code32, Code39, Code39 Extended, Code93 and Code93 Extended barcodes in PDF. This tutorial give you an example of how to add Codebar, Code128A and Code39 in PDF.

import com.spire.pdf.barcode.*;
import com.spire.pdf.graphics.*;
import static com.spire.pdf.graphics.PdfFontStyle.Bold;

import java.awt.*;
import java.awt.geom.Point2D;
import java.util.EnumSet;

public class DrawBarcode {

    public static void main(String[] args) {

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

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

        //declare a double variable 
        double y = 15;

        //create font 
        PdfFont font= new PdfFont(PdfFontFamily.Helvetica, 12, EnumSet.of(Bold));

        //draw text "Codebar:" on PDF 
        PdfTextWidget text = new PdfTextWidget();
        text.setFont(font);
        text.setText("Codebar:");
        PdfLayoutResult result = text.draw(page, 0, y);
        y =(float)(result.getBounds().getY()+ result.getBounds().getHeight() + 2);

        //draw Codebar barcode on PDF 
        PdfCodabarBarcode codebar= new PdfCodabarBarcode("00:12-3456/7890");
        codebar.setBarcodeToTextGapHeight(1f);
        codebar.setBarHeight(50f);
        codebar.setEnableCheckDigit(true);
        codebar.setShowCheckDigit(true);
        codebar.setTextDisplayLocation(TextLocation.Bottom);
        PdfRGBColor blue = new PdfRGBColor(Color.blue);
        codebar.setTextColor(blue);
        Point2D.Float point = new Point2D.Float();
        point.setLocation(0,y);
        codebar.draw(page,point);
        y = codebar.getBounds().getY()+ codebar.getBounds().getHeight() + 5;

        //draw text "Code128-A:" on PDF 
        text.setText("Code128-A:");
        result = text.draw(page, 0, y);
        page = result.getPage();
        y =result.getBounds().getY()+ result.getBounds().getHeight() + 2;

        //draw Code128 barcode on PDF 
        PdfCode128ABarcode code128 = new PdfCode128ABarcode("HELLO 00-123");
        code128.setBarcodeToTextGapHeight(1f);
        code128.setBarHeight(50f);
        code128.setTextDisplayLocation(TextLocation.Bottom);
        code128.setTextColor(blue);
        point.setLocation(point.x,y);
        code128.draw(page, point);
        y =code128.getBounds().getY()+ code128.getBounds().getHeight() + 5;

        //draw text "Code39:" on PDF 
        text.setText("Code39:");
        result = text.draw(page, 0, y);
        page = result.getPage();
        y =result.getBounds().getY()+ result.getBounds().getHeight() + 2;

        //draw Code39 barcode on PDF 
        PdfCode39Barcode code39 = new PdfCode39Barcode("16-273849");
        code39.setBarcodeToTextGapHeight(1f);
        code39.setBarHeight(50f);
        code39.setTextDisplayLocation(TextLocation.Bottom);
        code39.setTextColor(blue);
        point.setLocation(point.x,y);
        code39.draw(page, point);

        //save to file 
        doc.saveToFile("DrawBarcode.pdf");
    }
}

Draw Barcode in PDF in Java

Friday, 02 November 2018 07:04

Encrypt and Decrypt PDF in Java

With Spire.PDF for Java, you can encrypt and decrypt pdf file in your Java application. The following examples demonstrate how to encrypt and decrypt a PDF file using Spire.PDF for Java.

Encrypt PDF

import java.util.EnumSet;

import com.spire.pdf.PdfDocument;
import com.spire.pdf.security.PdfEncryptionKeySize;
import com.spire.pdf.security.PdfPermissionsFlags;

public class EncryptPDF {

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

        //Encrypt the file
        PdfEncryptionKeySize keySize = PdfEncryptionKeySize.Key_128_Bit;
        String openPassword = "e-iceblue";
        String permissionPassword = "test";
        EnumSet flags = EnumSet.of(PdfPermissionsFlags.Print, PdfPermissionsFlags.Fill_Fields);
        doc.getSecurity().encrypt(openPassword, permissionPassword, flags, keySize);

        //Save and close
        doc.saveToFile("Encrypt.pdf");
        doc.close();		
      
	}

}

Encrypt and Decrypt PDF in Java

Decrypt PDF

import com.spire.pdf.PdfDocument;
import com.spire.pdf.security.PdfEncryptionKeySize;
import com.spire.pdf.security.PdfPermissionsFlags;

public class DecryptPDF {

	public static void main(String[] args) throws Exception {
		
        //Create a PdfDocument instance
        PdfDocument doc = new PdfDocument();
        //Load the PDF file
        doc.loadFromFile("Encrypt.pdf", "test");

        //Decrypt the file
        doc.getSecurity().encrypt("", "", PdfPermissionsFlags.getDefaultPermissions(), PdfEncryptionKeySize.Key_256_Bit, "test");
        
        //Save and close
        doc.saveToFile("Decrypt.pdf");
        doc.close();
	}

}

Encrypt and Decrypt PDF in Java

Thursday, 01 November 2018 07:02

JAVA insert text watermark to PDF

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

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


public class Textwatermark {
    public static void main(String[] args) {
        //create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();

        //load the sample document
        pdf.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.pdf");
        //get the first page of the PDF
        PdfPageBase page = pdf.getPages().get(0);

        //use insertWatermark()to insert the watermark 
        insertWatermark(page, "E-ICEBLUE");
      //save the document to file
        pdf.saveToFile("out/textWaterMark.pdf");
    }

    static void insertWatermark(PdfPageBase page, String watermark) {
        Dimension2D dimension2D = new Dimension();
        dimension2D.setSize(page.getCanvas().getClientSize().getWidth() / 2, page.getCanvas().getClientSize().getHeight() / 3);
        PdfTilingBrush brush = new PdfTilingBrush(dimension2D);
        brush.getGraphics().setTransparency(0.3F);
        brush.getGraphics().save();
        brush.getGraphics().translateTransform((float) brush.getSize().getWidth() / 2, (float) brush.getSize().getHeight() / 2);
        brush.getGraphics().rotateTransform(-45);
        brush.getGraphics().drawString(watermark, new PdfFont(PdfFontFamily.Helvetica, 24), PdfBrushes.getViolet(), 0, 0, new PdfStringFormat(PdfTextAlignment.Center));
        brush.getGraphics().restore();
        brush.getGraphics().setTransparency(1);
        Rectangle2D loRect = new Rectangle2D.Float();
        loRect.setFrame(new Point2D.Float(0, 0), page.getCanvas().getClientSize());
        page.getCanvas().drawRectangle(brush, loRect);
    }
}

JAVA insert text watermark to PDF

Tuesday, 30 October 2018 00:52

Delete Images in PDF in Java

This article shows how to delete a particular picture on a PDF page and how to delete all pictures of the entire document by using Spire.PDF for Java.

Delete a particular image

import com.spire.pdf.PdfDocument;

public class DeleteImage {

	public static void main(String[] args) {

		//create a PdfDocument object
		PdfDocument doc = new PdfDocument();
		
		//load a sample PDF file
		doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Images.pdf");

		//get the specified page
		PdfPageBase page = doc.getPages().get(0);
		
		//delete a particular image by its index
		page.deleteImage(1);

		//save the file
		doc.saveToFile("DeleteSpecificImage.pdf", FileFormat.PDF);
	}

}

Delete all images

import com.spire.pdf.exporting.PdfImageInfo;

public class DeleteAllImages {

    public static void main(String[] args) {

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

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

        //loop through the pages
        for (int i = 0; i < doc.getPages().getCount(); i++) {

            //get the specific page
            PdfPageBase page = doc.getPages().get(i);

            //get the image information of the page
            PdfImageInfo[] imageInfo = page.getImagesInfo();

            //loop through the image information collection
            for (int j = imageInfo.length; j > 0; j--) {

                //delete image by its index
                page.deleteImage(j - 1);
            }
        }

        //save the file
        doc.saveToFile("DeleteAllImages.pdf", FileFormat.PDF);
    }
}
Wednesday, 24 October 2018 08:56

How to save Excel chart sheet to SVG in C#

A ChartSheet represents a chart sheet. It is a worksheet that contains only a chart. This article will demonstrate how to convert a chart sheet to SVG stream by using Spire.XLS.

Firstly, view the sample Excel worksheets with two chart sheets.

How to save Excel chart sheet to SVG in C#

Convert all the chart sheets to SVG stream:

//load the document from file
Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");

//call ToSVGStream(Stream stream) method to save each chart sheet to SVG stream 
for (int i = 0; i < workbook.Chartsheets.Count; i++)
{
    FileStream fs = new FileStream(string.Format("chartsheet-{0}.svg", i), FileMode.Create);
    workbook.Chartsheets[i].ToSVGStream(fs);
    fs.Flush();
    fs.Close();
}

Effective screenshot of the two chart sheets to SVG.

How to save Excel chart sheet to SVG in C#

//load the document from file
Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");

//get the second chartsheet by name
ChartSheet cs = workbook.GetChartSheetByName("Chart2");

//save to SVG stream
FileStream fs = new FileStream(string.Format("chart2.svg"), FileMode.Create);
cs.ToSVGStream(fs);
fs.Flush();
fs.Close();

How to save Excel chart sheet to SVG in C#

Alternative text (alt text) can help people with screen readers understand the content of our table. This article is going to demonstrate how to add or get the alternative text of a table in a word document using Spire.Doc.

In Spire.Doc, we can set or get the alternative text of a table using the Table.Title and Table.TableDescription properties. The following example shows how to add alternative text to a table.

Detail steps:

Step 1: Instantiate a Document object and load a word document.

Document doc = new Document();
doc.LoadFromFile("Input.docx");

Step 2: Get the first section.

Section section = doc.Sections[0];

Step 3: Get the first table in the section.

Table table = section.Tables[0] as Table;

Step 4: Add alt text to the table.

//Add title
table.Title = "Table 1";
//Add description
table.TableDescription = "Description Text";

Step 5: Save the document.

doc.SaveToFile("output.docx", FileFormat.Docx2013);

Screenshot:

Add/Get Alternative Text of Table in Word in C#

Full code:

using Spire.Doc;

namespace Add_Alt_Text_To_Word_Table
{
    class Program
    {
        static void Main(string[] args)
        {
            //Instantiate a Document object
            Document doc = new Document();
            //Load a word document
            doc.LoadFromFile("Input.docx");

            //Get the first section
            Section section = doc.Sections[0];

            //Get the first table in the section
            Table table = section.Tables[0] as Table;
 
            //Add alt text

            //Add tile
            table.Title = "Table 1";
            //Add description
            table.TableDescription = "Description Text";

            //Save the document
            doc.SaveToFile("output.docx", FileFormat.Docx2013);            
        }
    }
}