Program PDF headers and footers in Java

Program PDF headers and footers in Java Free Spire.PDF for Java, a class library that allows you to create PDF documents directly from Java programs without installing any additional software. You can easily create PDF files using this library. Simply create a PDFDocument object, create as many PDFabageBase objects as you need, draw strings, images, tables, lists, headers, footers and other elements on the page and save the document. This statement adds headers and pages when creating a Spire.PDF for Java PDF document.

Java


import java.awt.*;
import java.awt.geom.Dimension2D;
import com.spire.pdf.*;
import com.spire.pdf.automaticfields.PdfAutomaticField;
import com.spire.pdf.automaticfields.PdfCompositeField;
import com.spire.pdf.automaticfields.PdfPageCountField;
import com.spire.pdf.automaticfields.PdfPageNumberField;
import com.spire.pdf.graphics.*;

public class PDFHeaderFooter {
    public static void main(String[] args) throws Exception {

        //Create a PDFDocument object
        PdfDocument doc = new PdfDocument();
        //Set margins
        PdfMargins margin = new PdfMargins(60,60,40,40);
        //Method addheaderandfooter()To add headers and footers.
        addHeaderAndFooter(doc, PdfPageSize.A4, margin);
        //Add one page to your PDF document and draw a string.
        PdfPageBase page1 = doc.getPages().add();
        PdfPageBase page2 = doc.getPages().add();
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.PLAIN, 14));
        String text1 = "Demo of Spire.PDF";
        String text2 = "How to add header and footer to PDF in JAVA";
        page1.getCanvas().drawString(text1, font, PdfBrushes.getBlack(),0,0);
        page2.getCanvas().drawString(text2, font, PdfBrushes.getBlack(),0,0);
        //Save the document
        doc.saveToFile("output/headerFooter.pdf");
        doc.close();
    }
static void addHeaderAndFooter(PdfDocument doc, Dimension2D pageSize, PdfMargins margin) {

      PdfPageTemplateElement header = new PdfPageTemplateElement(margin.getLeft(), pageSize.getHeight());
      doc.getTemplate().setLeft(header);
      PdfPageTemplateElement topSpace = new PdfPageTemplateElement(pageSize.getWidth(), margin.getTop());
      topSpace.setForeground(true);
      doc.getTemplate().setTop(topSpace);

      //Drawing of header label
      PdfTrueTypeFont font= new PdfTrueTypeFont(new Font("Arial",Font.PLAIN,12));
      PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Left);
      String label = "E-iceblue Co.,Ltd";
      Dimension2D dimension2D = new Dimension();
      dimension2D.setSize(font.measureString(label, format));
      float y = topSpace.getHeight() - font.getHeight() - 1;
      PdfPen pen = new PdfPen(new PdfRGBColor(Color.black), 0.75f);
      topSpace.getGraphics().setTransparency(0.5f);
      topSpace.getGraphics().drawLine(pen, margin.getLeft(), y, pageSize.getWidth() - margin.getRight(), y);
      y = y - 1 - (float) dimension2D.getHeight();
      topSpace.getGraphics().drawString(label, font, PdfBrushes.getBlack(), margin.getLeft(), y, format);

      PdfPageTemplateElement rightSpace = new PdfPageTemplateElement(margin.getRight(), pageSize.getHeight());
      doc.getTemplate().setRight(rightSpace);

      //Draw a dynamic field as a footer
      PdfPageTemplateElement footer = new PdfPageTemplateElement(pageSize.getWidth(), margin.getBottom());
      footer.setForeground(true);
      doc.getTemplate().setBottom(footer);

      y = font.getHeight() + 1;
      footer.getGraphics().setTransparency(0.5f);
      footer.getGraphics().drawLine(pen, margin.getLeft(), y, pageSize.getWidth() - margin.getRight(), y);
      y = y + 1;
      PdfPageNumberField pageNumber = new PdfPageNumberField();
      PdfPageCountField pageCount = new PdfPageCountField();
      PdfCompositeField pageNumberLabel = new PdfCompositeField();
      pageNumberLabel.setAutomaticFields(new PdfAutomaticField[]{pageNumber, pageCount});
      pageNumberLabel.setBrush(PdfBrushes.getBlack());
      pageNumberLabel.setFont(font);
      format = new PdfStringFormat(PdfTextAlignment.Right);
      pageNumberLabel.setStringFormat(format);
      pageNumberLabel.setText("page {0} of {1}");
      pageNumberLabel.setBounds(footer.getBounds());
      pageNumberLabel.draw(footer.getGraphics(), pageSize.getWidth() - margin.getLeft(), y);
  }
}

Header Fotter.png

Recommended Posts

Program PDF headers and footers in Java
Create barcodes and QR codes in Java PDF
Save Java PDF in Excel
Java encryption and decryption PDF
Null-safe program in Java (Eclipse)
I created a PDF in Java.
StringBuffer and StringBuilder Class in Java
Output PDF and TIFF with Java 8
Understanding equals and hashCode in Java
Java draws shapes in PDF documents
Hello world in Java and Gradle
Difference between final and Immutable in Java
[Java] for Each and sorted in Lambda
Arrylist and linked list difference in java
Learn Flyweight patterns and ConcurrentHashMap in Java
Java Direction in C ++ Design and Evolution
Java to C and C to Java in Android Studio
Reading and writing gzip files in Java
Difference between int and Integer in Java
Discrimination of Enums in Java 7 and above
I made a primality test program in Java
Regarding the transient modifier and serialization in Java
Read a string in a PDF file with Java
Detect similar videos in Java and OpenCV rev.2
Partization in Java
Parallel and parallel processing in various languages (Java edition)
Difference between next () and nextLine () in Java Scanner
Changes in Java 11
Rock-paper-scissors in Java
Differences in writing Java, C # and Javascript classes
I wrote a primality test program in Java
Text extraction in Java from PDF with pdfbox-2.0.8
Capture and save from selenium installation in Java
Add, read, and delete Excel comments in Java
Check static and public behavior in Java methods
[Java] Understand in 10 minutes! Associative array and HashMap
Basics of threads and Callable in Java [Beginner]
Java and JavaScript
XXE and Java
Distinguish between positive and negative numbers in Java
Java adds and removes watermarks in word documents
Detect similar videos in Java and OpenCV rev.1
I wrote a prime factorization program in Java
Pi in Java
Represents "next day" and "previous day" in Java / Android
Questions in java exception handling throw and try-catch
Upload and download notes in java on S3
Encrypt / decrypt with AES256 in PHP and Java
Generate OffsetDateTime from Clock and LocalDateTime in Java
FizzBuzz in Java
Compare PDF output in Java for snapshot testing
Java enables extraction of PDF text and images
[LeJOS] Let's program mindstorm-EV3 in Java [Environment construction part 2]
[Android / Java] Screen transition and return processing in fragments
I tried Mastodon's Toot and Streaming API in Java
Write ABNF in Java and pass the email address
Organize builds in C ++ / Java and Win / Linux combinations
Vectorize and image MNIST handwritten digit image data in Java
Export pdf with a single program (Java / Perl / VBA)
Write a class in Kotlin and call it in Java
[Java] Difference between static final and final in member variables