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.PdfDocument;
import com.spire.pdf.exporting.PdfImageInfo;

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");

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

			//get a 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 = 0; j < imageInfo.length; j++) {
				
				//delete image by its index
				page.deleteImage(imageInfo[j].getIndex());
			}
		}

		//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);            
        }
    }
}
Monday, 22 October 2018 03:00

Fill PDF Form Fields in Java

The tutorial shows you how to access the form fields in a PDF document and how to fill each form field with value by using Spire.PDF for Java.

Entire Code:

import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.fields.PdfField;
import com.spire.pdf.widget.*;


public class FillFormField{
    public static void main(String[] args){
    	
        //create a PdfDocument object
        PdfDocument doc = new PdfDocument();
        
        //load a sample PDF containing forms
        doc.loadFromFile("G:\\java-workspace\\Spire.Pdf\\Forms.pdf");

        //get the form fields from the document
        PdfFormWidget form = (PdfFormWidget) doc.getForm();
        
        //get the form widget collection
        PdfFormFieldWidgetCollection formWidgetCollection = form.getFieldsWidget();

        //loop through the widget collection and fill each field with value
        for (int i = 0; i < formWidgetCollection.getCount(); i++) {
        	
            PdfField field = formWidgetCollection.get(i);         
            if (field instanceof PdfTextBoxFieldWidget) {
                PdfTextBoxFieldWidget textBoxField = (PdfTextBoxFieldWidget) field;
                textBoxField.setText("Kaila Smith");
            }         
            if (field instanceof PdfRadioButtonListFieldWidget) {
                PdfRadioButtonListFieldWidget radioButtonListField = (PdfRadioButtonListFieldWidget) field;
                radioButtonListField.setSelectedIndex(1);
            }
            if (field instanceof PdfListBoxWidgetFieldWidget) {
                PdfListBoxWidgetFieldWidget listBox = (PdfListBoxWidgetFieldWidget) field;
                listBox.setSelectedIndex(0);
            }
            if (field instanceof PdfCheckBoxWidgetFieldWidget) {
                PdfCheckBoxWidgetFieldWidget checkBoxField = (PdfCheckBoxWidgetFieldWidget) field;
                switch(checkBoxField.getName()){
                case "checkbox1":
                	checkBoxField.setChecked(true);
                	break;
                case "checkbox2":
                	checkBoxField.setChecked(true);
                	break;
                }
            }
            if (field instanceof PdfComboBoxWidgetFieldWidget) {
                PdfComboBoxWidgetFieldWidget comboBoxField = (PdfComboBoxWidgetFieldWidget) field;
                comboBoxField.setSelectedIndex(1);
            }
        }
        
        //Save the file
        doc.saveToFile("FillFormFields.pdf", FileFormat.PDF);
    }

}

Output:

Fill PDF Form Fields in Java

Monday, 15 October 2018 08:37

Convert PDF to Image in Java

By using Spire.PDF for JAVA, we can easily convert any specific page of PDF document to BMP and Metafile image in JAVA applications. The following sample demonstrate how to convert PDF to image in JAVA. The supported images could be in Jpeg, Jpg, Png, Bmp, Tiff, Gif, EMF format etc. We will use PDF to .png image for example.

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import com.spire.pdf.PdfDocument;
import javax.imageio.ImageIO;

public class toImage {

        public static void main(String[] args) throws IOException {
            //load the sample PDF
            PdfDocument doc = new PdfDocument();
            doc.loadFromFile("Sample.pdf");

            //save every PDF to .png image
            BufferedImage image;
            for (int i = 0; i < doc.getPages().getCount(); i++) {
                image = doc.saveAsImage(i);
                File file = new File( String.format("ToImage-img-%d.png", i));
                ImageIO.write(image, "PNG", file);
            }

            doc.close();
        }

}

The sample PDF file:

Convert PDF to Image in Java

Effective screenshot of the resulted PNG image:

Convert PDF to Image in Java

Monday, 15 October 2018 07:57

Extract/Read Text from PDF in Java

This article is going to demonstrate how to extract/read text from a PDF file using Spire.PDF for JAVA.

The example PDF file:

Extract/Read Text from PDF in Java

Code snippets:

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

public class Extract_Text {

	public static void main(String[] args) {
		
		//Create a PdfDocument instance
		PdfDocument doc=new PdfDocument();
		//Load the PDF file
        doc.loadFromFile("test.pdf");
        
        //Create a StringBuilder instance        
        StringBuilder sb=new StringBuilder();
        
        PdfPageBase page;
        
        //Loop through PDF pages and get text of each page
        for(int i=0;i<doc.getPages().getCount();i++){
            page=doc.getPages().get(i);            
            sb.append(page.extractText(true));
        }
        FileWriter writer;
        try {
            //Write text into a .txt file
            writer = new FileWriter("ExtractText.txt");
            writer.write(sb.toString());
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

        doc.close();
	}
}

Output:

Extract/Read Text from PDF in Java

Monday, 15 October 2018 05:47

Draw Shapes in PDF in Java

This tutorial will show you how to use Spire. PDF for Java to draw shapes in a PDF document, as well as set shape border colors and fill colors.

Entire Code:

import java.awt.Color;
import java.awt.geom.Rectangle2D;

import com.spire.ms.System.Drawing.PointF;
import com.spire.pdf.graphics.*;


public class DrawShapes {

	public static void main(String[] args) {
		
		//create a PdfDocument object
        PdfDocument doc = new PdfDocument();
        
        //add a page
        PdfPageBase page = doc.getPages().add();      
        
        //draw a rectangle
        PdfPen pen =new PdfPen(new PdfRGBColor(Color.black),0.1);
        Rectangle2D.Float rect1 = new Rectangle2D.Float(0, 20, 120, 50);
        PdfLinearGradientBrush linearGradientBrush = new PdfLinearGradientBrush(rect1,new PdfRGBColor(Color.white),new PdfRGBColor(Color.blue),PdfLinearGradientMode.Horizontal);          
        page.getCanvas().drawRectangle(pen, linearGradientBrush, rect1);
        
        //draw an ellipse
        PointF centerStart= new PointF(205,45);
        PointF centerEnd= new PointF(205,45);
        PdfRadialGradientBrush radialGradientBrush = new PdfRadialGradientBrush(centerStart,0,centerEnd,25,new PdfRGBColor(Color.pink),new PdfRGBColor(Color.red));
        Rectangle2D.Float rect2= new Rectangle2D.Float(180, 20, 50, 50);
        page.getCanvas().drawEllipse(pen,radialGradientBrush,rect2);
        
        //draw a polygon
        PointF p1=new PointF(290,70);
        PointF p2=new PointF(310,45);
        PointF p3=new PointF(325,60);
        PointF p4=new PointF(340,20);
        PointF p5=new PointF(370,70);
        PointF[] points = {p1, p2, p3, p4, p5};
        PdfBrush brush= PdfBrushes.getGreenYellow();
        page.getCanvas().drawPolygon(pen,brush, points);
        
        //draw an arc
        float startAngle = 0;
        float sweepAngle = 270;
        Rectangle2D.Float rect3= new Rectangle2D.Float(0, 110, 50, 50);
        page.getCanvas().drawArc(pen, rect3, startAngle, sweepAngle);
        
        //draw a pie graph   
        Rectangle2D.Float rect4= new Rectangle2D.Float(70, 110, 50, 50);
        page.getCanvas().drawPie(pen, rect4, startAngle, sweepAngle);
        
        //draw a line
        PointF pStart=new PointF(205,110);
        PointF pEnd=new PointF(205,160);
        page.getCanvas().drawLine(pen, pStart, pEnd);
  
        //draw a Bezier curve
        PointF startPoint = new PointF(290, 135);
        PointF firstControlPoint = new PointF(330, 70);
        PointF secondControlPoint = new PointF(330, 200);
        PointF endPoint = new PointF(370, 135);
        page.getCanvas().drawBezier(pen, startPoint, firstControlPoint, secondControlPoint, endPoint);
        
        //save to file
        doc.saveToFile("DrawShapes.pdf", FileFormat.PDF);       
	}

}

Output:

Draw Shapes in PDF in Java

We have demonstrated how to use Spire.Presentation to add and get speaker notes in presentation slides. This article will show how to remove the speaker notes in presentation slides in C#.

Firstly, view the sample document contains the speaker notes.

How to remove speaker notes from a presentation slide in C#

Step 1: Create a presentation document and load the document from the file.

Presentation ppt = new Presentation();
ppt.LoadFromFile("Sample.pptx", FileFormat.Pptx2013);

Step 2: Get the first slide from the sample document.

ISlide slide = ppt.Slides[0];

Step 3: Remove the first speak notes:

slide.NotesSlide.NotesTextFrame.Paragraphs.RemoveAt(1);

Remove all the speak notes from the first slide:

slide.NotesSlide.NotesTextFrame.Paragraphs.Clear();

Step 4: Save the document to file.

ppt.SaveToFile("Result.pptx",FileFormat.Pptx2013);

Effective screenshot of removing the first note:

How to remove speaker notes from a presentation slide in C#

Effective screenshot of removing all the notes:

How to remove speaker notes from a presentation slide in C#

Full codes:

Remove the first note in presentation slide:

Presentation ppt = new Presentation();
ppt.LoadFromFile("Sample.pptx", FileFormat.Pptx2013);

ISlide slide = ppt.Slides[0];
           
slide.NotesSlide.NotesTextFrame.Paragraphs.RemoveAt(1);
ppt.SaveToFile("Result.pptx",FileFormat.Pptx2013);

Clear all notes in presentation slide:

Presentation ppt = new Presentation();
ppt.LoadFromFile("Sample.pptx", FileFormat.Pptx2013);

ISlide slide = ppt.Slides[0];
           
slide.NotesSlide.NotesTextFrame.Paragraphs.Clear();
ppt.SaveToFile("Result2.pptx",FileFormat.Pptx2013);