Monday, 25 January 2021

Add an image stamp or a text stamp to a PDF document in Java

Adding an image stamp (such as Paid, Reviewed, and Approved) to a PDF document can give readers a simple meaning to indicate the status of the file. Besides, you can add a dynamic stamp which usually consists of some dynamic information, such as company name, “Approved By” and system date. This tutorial will introduce how to add an image stamp or a dynamic stamp to a PDF document using Java codes.

Dependency

Before running codes, we need to insert a Jar file into IDEA. You can download it from the website or directly reference it using the following Maven configurations.

<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.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

Using the code

Add an image stamp

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
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\\Test1\\Desktop\\Sample.pdf");

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

//load an image file
PdfImage image = PdfImage.fromFile("C:\\Users\\Test1\\Desktop\\Image.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 - 30), 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("output/ImageStamp.pdf");
doc.close();
}
}

Output


Add a dynamic stamp

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
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\\Test1\\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 = "APPROVED\n";
String s2 = "By Tony 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("output/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



Monday, 18 January 2021

Add and Remove Bookmarks in Word Documents using Java

The bookmark feature in a Word document is similar to a bookmark we used while reading a book. When you have a long document and need to return to specific locations in the document later for reviewing or editing, you can use the Bookmark feature in Microsoft Word. In this article, I’ll use Java codes to manipulate bookmarks including add and remove them in a Word document without installing Microsoft Office.

Kindly note that you need a third-party library while using Java codes to finish the actions above. Here I recommend a free library called Free Spire.Doc for Java. The first thing you need to do is adding the jar file to IDEA. You can download the package from the link or directly reference it using the following Maven configurations.

<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.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

Add a Bookmark for the specified paragraph in a Word document

Free Spire.Doc for Java supports adding a bookmark to the specified paragraph through two provides which are

appendBookmarkStart (string name) and appendBookmarkEnd (string name). BookmarkStart represents the start

point of the bookmark, while BookmarkEnd represents the end point of the bookmark.

import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
public class AddBookmark {
public static void main(String[] args) {
//create a Document object
Document doc = new Document();

//load a Word file to test
doc.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.docx");

//get the paragraph where you want to insert bookmark
Paragraph paragraph = doc.getSections().get(0).getParagraphs().get(4);

//Create a start bookmark and move it to the beginning of the paragraph
BookmarkStart start = paragraph.appendBookmarkStart("Bookmark1");
paragraph.getItems().insert(0,start);

//append a end bookmark at the end of the paragraph
paragraph.appendBookmarkEnd("Bookmark1");

//save the resulting file
doc.saveToFile("output/AddBookmark.docx", FileFormat.Docx_2013);
}
}

Output

Add a bookmark for the specified String in a Word document

At the same time, Free Spire.Doc for Java provides the findString () method to find the specified words where

we want to add a bookmark. And then use BookmarkStart and BookmarkEnd methods to locate the start point

and end point of the bookmark.

import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.TextRange;

public class AddBookmarkToCharacter {
public static void main(String[] args) {
//Load a Word document to test
Document doc = new Document();
doc.loadFromFile("C:\\Users\\Test1\\Desktop\\AddBookmark.docx");

//Find the specified string
TextSelection textSelection = doc.findString("Before you fret too much over this",false,false);
TextRange range = textSelection.getAsOneRange();
Paragraph para = range.getOwnerParagraph();
int index = para.getChildObjects().indexOf(range);

//Add a bookmark to the specified string
BookmarkStart start = new BookmarkStart(doc,"Bookmark2");
BookmarkEnd end = new BookmarkEnd(doc, "Bookmark2");
para.getChildObjects().insert(index, start);
para.getChildObjects().insert(index + 2, end);

//Save the resulting document
doc.saveToFile("output/AppendBookmarkToCharacter.docx",FileFormat.Docx_2013);
doc.dispose();
}
}

Output


Remove a specified bookmark in a Word document

Every Word document contains a collection of bookmarks, which are accessible through the Bookmarks property

of Document class. We can find a specified bookmark by its index and remove it using the Bookmarks property.

import com.spire.doc.Bookmark;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class RemoveBookmark {
public static void main(String[] args) {
//create a Document object
Document doc = new Document();

//load a Word file to test
doc.loadFromFile("C:\\Users\\Test1\\Desktop\\AppendBookmarkToCharacter.docx");

//get the first bookmark by its index
Bookmark bookmark = doc.getBookmarks().get(1);

//remove the bookmark
doc.getBookmarks().remove(bookmark);

//save the resulting file
doc.saveToFile("output/RemoveBookmark.docx", FileFormat.Docx);
}
}

Output





Friday, 15 January 2021

[Java] Add, Read and Delete Trendlines in Excel documents

Data Analysis is used to gain an understanding for the development trend of data in the future, which can ensure that plans can be made reasonably at present. The development trend of data can be visually found by adding a trend line to a chart in an Excel document. This article will demonstrate how to add a trend line to a specified chart in an Excel document, and also introduce the methods of reading and deleting the trend line. All actions will be done in Java program by using a free third-party library called FreeSpire.XLS for Java.

Dependency

Before running codes, we need to insert a Jar file into IDEA. You can download it from the website or directly reference it using the following Maven configurations.

<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.free</artifactId>
<version>3.9.1</version>
</dependency>
</dependencies>
The following screenshot is shown what it looks like finally.


Add Trendline

Here is a screenshot of the Excel file used to test. I’ll add a Trendline for the second data series in the chart below.

The types of Trendline which Free Spire.XLS for Java supports adding to Excel charts includes Linear, Exponential Logarithmic, Moving_Average, Polynomial,Power and so on. In the process of adding a trend line, you can set its type and color, and whether display the equation and R-Squared value. 

import com.spire.xls.*;
import com.spire.xls.core.IChartTrendLine;
import java.awt.*;

public class AddTrendLine {
public static void main(String[] args) {
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load the Excel file
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.xlsx");

//Get the first chart in the first worksheet
Chart chart = workbook.getWorksheets().get(0).getCharts().get(0);

//Add a Trendline to the second series of the chart
IChartTrendLine trendLine = chart.getSeries().get(1).getTrendLines().add(TrendLineType.Linear);

//Set Trendline name
trendLine.setName("Linear(Product 2)");
//Set line type and color
trendLine.getBorder().setPattern(ChartLinePatternType.DashDot);
trendLine.getBorder().setColor(Color.blue);
//Set forward and backward value
trendLine.setForward(0.5);
trendLine.setBackward(0.5);
//Set intercept value
trendLine.setIntercept(5);

//Display equation on chart
trendLine.setDisplayEquation(true);
//Display R-Squared value on chart
trendLine.setDisplayRSquared(true);

//Save the result file
workbook.saveToFile("output/AddTrendline.xlsx", ExcelVersion.Version2013);
}
}

Output


Read Trendline

Free Spire.XLS for Java supports reading the type, name and equation of the Trendline.

import com.spire.xls.*;
import com.spire.xls.core.IChartTrendLine;

public class ReadTrendLine {
public static void main(String[] args) {
//Load the excel file used to test
Workbook workbook = new Workbook();
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\AddTrendline.xlsx");

//Get the first chart in the first worksheet
Chart chart = workbook.getWorksheets().get(0).getCharts().get(0);

//Get Trendline in the second data series of the chart
IChartTrendLine trendLine = chart.getSeries().get(1).getTrendLines().get(0);
String type = trendLine.getType().toString();
String name = trendLine.getName();
String equation = trendLine.getFormula();
System.out.println("The type of Trendline: "+ type + "\n"
+ "The name of Trendline:" + name + "\n"
+ "The equation of Trendline:" + equation);
}
}

Output


Delete Trendline

import com.spire.xls.*;

public class DeleteTrendLine {
public static void main(String[] args) {
//Load the excel file used to test
Workbook workbook = new Workbook();
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\AddTrendline.xlsx");

//Get the first chart in the first worksheet
Chart chart = workbook.getWorksheets().get(0).getCharts().get(0);

//Delete the Trendline of the chart
chart.getSeries().get(1).getTrendLines().removeAt(0);

//Save the resulting document
workbook.saveToFile("output/DeleteTrendLine.xlsx",FileFormat.Version2013);
workbook.dispose();
}
}



Monday, 11 January 2021

Add or Remove Watermarks in PowerPoint documents using Java

Requires

In the following document, I want to add an image watermark to the first slide, and add a text watermark to the second slide. Meanwhile, I would like to know whether the watermarks can be removed at one time or not.

Note: I need to finish the functions in Java programmatically without using Microsoft PowerPoint.

Solution

Through researching many kinds of third-party libraries, I found a free API called Free Spire.Presentation for Java. It is a professional API that enables developers to create, read, write, convert and print PowerPoint documents in Java Applications without installing Microsoft PowerPoint.

Therefore, I’ll use the API to demonstrate the following demo samples. Before running codes, you need to download the product’s package and then insert Spire.Presentation.jar to IDEA. Or directly reference it by writing the following configurations in the Maven’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>

Using the code

Add Image Watermark

import com.spire.presentation.*;
import com.spire.presentation.drawing.*;
import javax.imageio.ImageIO;
import java.io.File;
public class ImageWatermark {
public static void main(String[] args) throws Exception {
//Create a PowerPoint document.
Presentation presentation = new Presentation();

//Load the file from disk.
presentation.loadFromFile("C:\\Users\\Test1\\Desktop\\Test.pptx");

//Get the image you want to add as image watermark.
File file =new File("C:\\Users\\Test1\\Desktop\\pic.jpg");
IImageData image = presentation.getImages().append(ImageIO.read(file));

//Set the properties of SlideBackground, and then fill the image as watermark.
presentation.getSlides().get(0).getSlideBackground().setType(BackgroundType.CUSTOM);
presentation.getSlides().get(0).getSlideBackground().getFill().setFillType(FillFormatType.PICTURE);
presentation.getSlides().get(0).getSlideBackground().getFill().getPictureFill().setFillType(PictureFillType.STRETCH);
presentation.getSlides().get(0).getSlideBackground().getFill().getPictureFill().getPicture().setEmbedImage(image);

String result = "output/addImageWatermark.pptx";
//Save to file.
presentation.saveToFile(result, FileFormat.PPTX_2013);
}
}

Output


Add Text Watermark

In the process of adding text watermark, Free Spire.Presentation for Java supports setting the width,

height, color and rotation of the text watermark.

import com.spire.presentation.*;
import com.spire.presentation.drawing.FillFormatType;
import java.awt.*;
import java.awt.geom.Rectangle2D;
public class AddWatermark {
public static void main(String[] args) throws Exception {
//Load a PDF document for testing
Presentation presentation = new Presentation();
presentation.loadFromFile("C:\\Users\\Test1\\Desktop\\AddTextWatermark.pptx");

//Set the width and height of watermark string
int width= 400;
int height= 300;
//Define a rectangle range
Rectangle2D.Double rect = new Rectangle2D.Double((presentation.getSlideSize().getSize().getWidth() - width) / 4,
(presentation.getSlideSize().getSize().getHeight() - height) / 2, width, height);

//Add a rectangle shape with a defined range
IAutoShape shape = presentation.getSlides().get(1).getShapes().appendShape(ShapeType.RECTANGLE, rect);

//Set the style of shape
shape.getFill().setFillType(FillFormatType.NONE);
shape.getShapeStyle().getLineColor().setColor(Color.white);
shape.setRotation(-45);
shape.getLocking().setSelectionProtection(true);
shape.getLine().setFillType(FillFormatType.NONE);

//Add text to shape
shape.getTextFrame().setText("Draft");
PortionEx textRange = shape.getTextFrame().getTextRange();

//Set the style of the text range
textRange.getFill().setFillType(FillFormatType.SOLID);
textRange.getFill().getSolidColor().setColor(Color.red);
textRange.setFontHeight(50);

//Save the document
presentation.saveToFile("output/addWatermark.pptx", FileFormat.PPTX_2010);
}
}

Output


Delete text or image watermark

import com.spire.presentation.*;
import com.spire.presentation.drawing.*;
public class DeleteWatermark {
public static void main(String[] args) throws Exception {
//Load the sample document
Presentation presentation = new Presentation();
presentation.loadFromFile("C:\\Users\\Test1\\Desktop\\DeleteAllWatermark.pptx");

//Remove text watermark by removing the shape which contains the string "Draft".
for (int i = 0; i < presentation.getSlides().getCount(); i++)
{
for (int j = 0; j < presentation.getSlides().get(i).getShapes().getCount(); j++)
{
if (presentation.getSlides().get(i).getShapes().get(j) instanceof IAutoShape)
{
IAutoShape shape = (IAutoShape)presentation.getSlides().get(i).getShapes().get(j);
if (shape.getTextFrame().getText().contains("Draft"))
{
presentation.getSlides().get(i).getShapes().remove(shape);
}
}
}
}

//Remove image watermark
for (int i = 0; i < presentation.getSlides().getCount(); i++)
{
presentation.getSlides().get(i).getSlideBackground().getFill().setFillType(FillFormatType.NONE);
}

//Save to file.
presentation.saveToFile("output/deleteWatermark.pptx", FileFormat.PPTX_2013);
}
}

Conclusion

After running the code snippets below, we can successfully add or delete text or image watermarks in

PowerPoint documents. If there is any problem while installing the jar file or running codes, you can take notes on Forum.

Thursday, 7 January 2021

Add, Extract and Remove Attachments in a PDF document using Java

This article will introduce how to add, extract and remove attachments in a PDF document using Java codes programmatically. Before beginning, we should create a test environment using a free third-party library called FreeSpire.PDF for Java. You can either download the API’s JAR or install it within your maven-based applications using the following configurations.

<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.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

Add Attachments to PDF in Java

Free Spire.PDF for Java supports adding a file attachment or annotation attachment to PDF. In the

process of adding an annotation attachment, it supports drawing a label on PDF, and set the label’s font

size or location. Besides, Flag, icon or text can be also set.

The following code sample shows how to add a file attachment and an annotation attachment.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.annotations.*;
import com.spire.pdf.attachments.PdfAttachment;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.Dimension2D;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class AddAttachment {
public static void main(String[] args) throws IOException {
//create a PdfDocument object
PdfDocument doc = new PdfDocument();

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

//add an attachment to pdf
PdfAttachment attachment = new PdfAttachment("C:\\Users\\Test1\\Desktop\\Country list.xlsx");
doc.getAttachments().add(attachment);

//draw a label on pdf
String label = "Report.docx";
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.BOLD, 14));
double x = 30;
double y = doc.getPages().get(2).getActualSize().getHeight() - 80;
doc.getPages().get(2).getCanvas().drawString(label, font, PdfBrushes.getOrange(), x, y);

//add an attachment annotation to pdf
String filePath = "C:\\Users\\Test1\\Desktop\\Report.docx";
byte[] data = toByteArray(filePath);
Dimension2D size = font.measureString(label);
Rectangle2D bound = new Rectangle2D.Float((float) (x + size.getWidth() + 2), (float) y, 10, 15);
PdfAttachmentAnnotation annotation = new PdfAttachmentAnnotation(bound, filePath, data);
annotation.setColor(new PdfRGBColor(new Color(128, 13, 119)));
annotation.setFlags(PdfAnnotationFlags.Default);
annotation.setIcon(PdfAttachmentIcon.Graph);
annotation.setText("Click to open Report.docx");
doc.getPages().get(2).getAnnotationsWidget().add(annotation);

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

//read file to byte array
public static byte[] toByteArray(String filePath) throws IOException {

File file = new File(filePath);
long fileSize = file.length();
if (fileSize > Integer.MAX_VALUE) {
System.out.println("file too big...");
return null;
}
FileInputStream fi = new FileInputStream(file);
byte[] buffer = new byte[(int) fileSize];
int offset = 0;
int numRead = 0;
while (offset < buffer.length
&& (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
offset += numRead;
}

if (offset != buffer.length) {
throw new IOException("Could not completely read file "
+ file.getName());
}
fi.close();
return buffer;
}
}

Output


Extract
Attachments from PDF

We just need to load the sample file, get and loop through the attachment collection to extract each

attachment in PDF.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.attachments.PdfAttachmentCollection;
import java.io.*;

public class ExtractAttachment {
public static void main(String[] args) throws IOException {
//Load the PDF document
PdfDocument pdf = new PdfDocument();
pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\AddAttachments.pdf");

//Get the attachment collection of the PDF document
PdfAttachmentCollection attachments = pdf.getAttachments();

//Loop through the collection and extract each attachment in the PDF document
for (int i = 0; i < attachments.getCount(); i++) {
File file = new File("output/ExtractAttachments/"+attachments.get(i).getFileName());
OutputStream output = new FileOutputStream(file);

BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);

bufferedOutput.write(attachments.get(i).getData());
bufferedOutput.close();
}
}
}
Delete Attachments in PDF

We can separately delete a file attachment or an annotation attachment from the following two code

samples.

l  Delete a file attachment

Free Spire.PDF for Java supports delete all attachments or a specific attachment in PDF.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.attachments.PdfAttachmentCollection;
public class DeleteAttachment {
public static void main(String[] args) {
//load a PDF document
PdfDocument doc = new PdfDocument();
doc.loadFromFile("C:\\Users\\Test1\\Desktop\\AddAttachments.pdf");

//get the attachments collection, not containing annotation attachments
PdfAttachmentCollection attachments = doc.getAttachments();

//remove all attachments
attachments.clear();

//remove a specific attachment
//attachments.removeAt(0);

//save to file
doc.saveToFile("output/DeleteAttachments.pdf");
doc.close();
}
}

l  Delete an annotation attachment

We can delete the annotation attachment by determining if it is an instance of PdfAttachmentAnnotationWidget in the following code sample.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.annotations.PdfAnnotation;
import com.spire.pdf.annotations.PdfAnnotationCollection;
import com.spire.pdf.annotations.PdfAttachmentAnnotationWidget;
public class DeleteAnnotationAttachment {
public static void main(String[] args) {
//load a PDF document
PdfDocument doc = new PdfDocument();
doc.loadFromFile("C:\\Users\\Test1\\Desktop\\AddAttachments.pdf");

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

//get the annotations collection
PdfAnnotationCollection annotationCollection = doc.getPages().get(i).getAnnotationsWidget();

//loop through the annotations
for (Object annotation: annotationCollection) {

//determine if an annotation is an instance of PdfAttachmentAnnotationWidget
if (annotation instanceof PdfAttachmentAnnotationWidget){

//remove the attachment annotation
annotationCollection.remove((PdfAnnotation) annotation);
}
}
}
//save to file
doc.saveToFile("output/DeleteAnnotationAttachments.pdf");
doc.close();
}
}

Change PDF Versions in Java

In daily work, you might need to change the version of a PDF document you have in order to ensure compatibility with another version which a...