Java (481)
Adding a header to a PDF document is a useful way to display important information such as the document title, author, and page numbers. A header is a section of text or graphics that appears at the top of each page in a document and can be customized according to your needs. This feature is particularly helpful when creating reports, contracts, or other professional documents that require a consistent format. In this article, you will learn how to add a header to an existing PDF document in Java using Spire.PDF for Java.
Install Spire.PDF for Java
First of all, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf</artifactId>
<version>11.12.16</version>
</dependency>
</dependencies>
Background Knowledge
When an existing PDF document is manipulated by Spire.PDF for Java, the origin of the coordinate system is located at the top left corner of the page, with the x-axis extending to the right and the y-axis extending downward. Adding a header to a page means adding content, such as text, images, automatic fields and shapes, to a specified location in the upper blank area of the page.

If the blank area is not large enough to accommodate the content you want to add, you can consider increasing the PDF page margins.
Add a Header to an Existing PDF Document in Java
Spire.PDF for Java allows users to draw text, images and shapes on a PDF page using PdfCanvas.drawString() method, PdfCanvas.drawImage() method, PdfCanvas.drawLine() method and other similar methods. To add dynamic information to the header, such as page numbers, sections, dates, you need to resort to automatic fields. Spire.PDF for Java provides the PdfPageNumberField class, PdfSectionNumberField class, PdfCreationDateField class, etc. to achieve the dynamic addition of these data.
The following are the steps to add a header consisting of text, an image, a date, and a line to a PDF document using Spire.PDF for Java.
- Create a PdfDocument object.
- Load a PDF document using PdfDocument.loadFromFile() method.
- Create font, pen and brush objects that will be used to draw text or shapes.
- Draw text on the top blank area of a page using PdfPageBase.getCanvas().drawString() method.
- Draw a line on the top blank area of a page using PdfPageBase.getCanvas().drawLine() method.
- Load an image using PdfImage.fromFile() method.
- Draw the image on the top blank area of a page using PdfPageBase.getCanvas().drawImage() method.
- Create a PdfCreationDateField object that reflects the creation time of the document.
- Draw the creation time on the top blank area of a page using PdfCreationDateField.draw() method.
- Save the document to another PDF file using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.automaticfields.PdfCompositeField;
import com.spire.pdf.automaticfields.PdfCreationDateField;
import com.spire.pdf.graphics.*;
import java.awt.*;
public class AddHeaderToPdf {
public static void main(String[] args) {
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Load a PDF file
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\TargetMarket.pdf");
//Load an image for the header
PdfImage headerImage = PdfImage.fromFile("C:\\Users\\Administrator\\Desktop\\logo.png");
//Get image width in pixel
float width = headerImage.getWidth();
//Convert pixel to point
PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
float pointWidth = unitCvtr.convertUnits(width, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point);
//Specify text for the header
String headerText = "E-iceblue Tech\nwww.e-iceblue.com";
//Create a true type font
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", Font.BOLD, 12),true);
//Create a brush
PdfBrush brush = PdfBrushes.getPurple();
//Create a pen
PdfPen pen = new PdfPen(brush, 1.0f);
//Create a creation date field
PdfCreationDateField creationDateField = new PdfCreationDateField(font, brush);
creationDateField.setDateFormatString("yyyy-MM-dd");
//Create a composite field to combine static string and date field
PdfCompositeField compositeField = new PdfCompositeField(font, brush, "creation time: {0}", creationDateField);
compositeField.setLocation(new Point(55, 48));
//Loop through the pages in the document
for (int i = 0; i < doc.getPages().getCount(); i++)
{
//Get specific page
PdfPageBase page = doc.getPages().get(i);
//Draw the image on the top blank area
page.getCanvas().drawImage(headerImage, page.getActualSize().getWidth() - pointWidth - 55, 20);
//Draw text on the top blank area
page.getCanvas().drawString(headerText, font, brush, 55, 20);
//Draw a line on the top blank area
page.getCanvas().drawLine(pen, new Point(55, 70), new Point((int)page.getActualSize().getWidth() - 55, 70));
//Draw the composite field on the top blank area
compositeField.draw(page.getCanvas());
}
//Save to file
doc.saveToFile("output/AddHeader.pdf");
doc.dispose();
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Variables in Word documents are a type of field that is characterized by the ability of convenient and accurate text management, such as text replacement and deletion. Compared with the find-and-replace function, replacing text by assigning values to variables is faster and less error-prone. This article is going to show how to add or change variables in Word documents programmatically using Spire.Doc for Java.
Install Spire.Doc for Java
First, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc</artifactId>
<version>14.1.3</version>
</dependency>
</dependencies>
Insert Variables into Word Documents
As variables are a kind of Word fields, we can use the Paragraph.appendField(String fieldName, FieldType.Field_Doc_Variable) method to insert variables into Word documents, and then use the VariableCollection.add() method to assign values to the variables. It should be noted that after assigning values to variables, document fields need to be updated to display the assigned values. The detailed steps are as follows.
- Create an object of Document.
- Add a section to the document using Document.addSection() method.
- Add a paragraph to the section using Section.addParagraph() method.
- Add variable fields to the paragraph using Paragraph.appendField(String fieldName, FieldType.Field_Doc_Variable) method.
- Get the variable collection using Document.getVariables() method.
- Assign a value to the variable using VariableCollection.add() method.
- Update the fields in the document using Document.isUpdateFields() method.
- Save the document using Document.saveToFile() method.
- Java
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.formatting.CharacterFormat;
public class AddVariables {
public static void main(String[] args) {
//Create an object of Document
Document document = new Document();
//Add a section
Section section = document.addSection();
//Add a paragraph
Paragraph paragraph = section.addParagraph();
//Set text format
CharacterFormat characterFormat = paragraph.getStyle().getCharacterFormat();
characterFormat.setFontName("Times New Roman");
characterFormat.setFontSize(14);
//Set the page margin
section.getPageSetup().getMargins().setTop(80f);
//Add variable fields to the paragraph
paragraph.appendField("Term", FieldType.Field_Doc_Variable);
paragraph.appendText(" is an object.\r\n");
paragraph.appendField("Term", FieldType.Field_Doc_Variable);
paragraph.appendText(" is not a backdrop, an illusion, or an emergent phenomenon.\r\n");
paragraph.appendField("Term", FieldType.Field_Doc_Variable);
paragraph.appendText(" has a physical size that be measured in laboratories.");
//Get the variable collection
VariableCollection variableCollection = document.getVariables();
//Assign a value to the variable
variableCollection.add("Term", "Time");
//Update the fields in the document
document.isUpdateFields(true);
//Save the document
document.saveToFile("AddVariables.docx", FileFormat.Auto);
document.dispose();
}
}

Change the Value of Variables in Word Documents
Spire.Doc for Java provides the VariableCollection.set() method to change the values of variables. And after updating fields in the document, all the occurrences of the variables will display the newly assigned value, thus achieving fast and accurate text replacement. The detailed steps are as follows.
- Create an object of Document.
- Load a Word document using Document.loaFromFile() method.
- Get the variable collection using Document.getVariables() method.
- Assign a new value to a specific variable through its name using VariableCollection.set() method.
- Update the fields in the document using Document.isUpdateFields() method.
- Save the document using Document.saveToFile() method.
- Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.VariableCollection;
public class ChangeVariableValue {
public static void main(String[] args) {
//Create an object of Document
Document document = new Document();
//Load a Word document
document.loadFromFile("AddVariables.docx");
//Get the variable collection
VariableCollection variableCollection = document.getVariables();
//Assign a new value to a variable
variableCollection.set("Term", "The time");
//Update the fields in the document
document.isUpdateFields(true);
//Save the document
document.saveToFile("ChangeVariable.docx", FileFormat.Auto);
document.dispose();
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
A waterfall chart, also called a bridge chart or a cascade chart, is one of the most visually descriptive charts in Excel. It shows the cumulative effect of positive and negative contributions over a period of time, which is useful in many scenarios where quantitative analysis is required, such as visualizing profit and loss statements, showing budget changes in a project, or monitoring shop inventories. In this article, you will learn how to create a waterfall chart in Excel in Java using Spire.XLS for Java.
Install Spire.XLS for Java
First of all, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls</artifactId>
<version>15.12.15</version>
</dependency>
</dependencies>
Create a Waterfall Chart in Excel in Java
Waterfall charts are ideal for analyzing financial statements. To create a waterfall chart, you could first add a chart to a specified worksheet using Worksheet.getCharts().add() method, and then set the chart type to Waterfall using Chart.setChartType(ExcelChartType.WaterFall) method. The following are the detailed steps.
- Create a Workbook instance.
- Load a sample Excel document using Workbook.loadFromFile() method.
- Get a specified worksheet by its index using Workbook.getWorksheets().get() method.
- Add a chart to the worksheet Worksheet.getCharts().add() method, and then set the chart type to waterfall using Chart.setChartType(ExcelChartType.WaterFall) method.
- Set data range for the chart using Chart.setDataRange() method.
- Set position and title of the chart.
- Get a specified data series of the chart, and then set specific data points in the chart as totals or subtotals using ChartSerie.getDataPoints().get().setAsTotal() method.
- Show the connector lines between data points using ChartSerie.getFormat().showConnectorLines(true) method.
- Show data labels for data points, and set the legend position of the chart.
- Save the result document using Workbook.saveToFile() method.
- Java
import com.spire.xls.*;
public class WaterfallChart {
public static void main(String []args){
//Create a Workbook object
Workbook workbook=new Workbook();
//Load a sample Excel document
workbook.loadFromFile("data.xlsx");
//Get the first worksheet
Worksheet sheet=workbook.getWorksheets().get(0);
//Add a waterfall chart to the worksheet
Chart chart=sheet.getCharts().add();
chart.setChartType(ExcelChartType.WaterFall);
//Set data range for the chart
chart.setDataRange(sheet.getRange().get("A2:B11"));
//Set position of the chart
chart.setLeftColumn(4);
chart.setTopRow(2);
chart.setRightColumn(15);
chart.setBottomRow(23);
//Set chart title
chart.setChartTitle("Income Statement");
//Set specific data points in the chart as totals or subtotals
chart.getSeries().get(0).getDataPoints().get(2).setAsTotal(true);
chart.getSeries().get(0).getDataPoints().get(7).setAsTotal(true);
chart.getSeries().get(0).getDataPoints().get(9).setAsTotal(true);
//Show the connector lines between data points
chart.getSeries().get(0).getFormat().showConnectorLines(true);
//Show data labels for data points
chart.getSeries().get(0).getDataPoints().getDefaultDataPoint().getDataLabels().hasValue(true);
chart.getSeries().get(0).getDataPoints().getDefaultDataPoint().getDataLabels().setSize(8);
//Set the legend position of the chart
chart.getLegend().setPosition(LegendPositionType.Top);
//Save the result document
workbook.saveToFile("WaterfallChart.xlsx",FileFormat.Version2016);
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.