Share & learn

Through Innovative Digital Library

How to create, write and read from a pdf file in Java?

Write a code in Java to perform following operations on a pdf file in Java. 1. Create a pdf File and write data to it 2. Read from an existing pdf file 3. Overwrite data to an existing pdf file
 



Answers

Posted by Paul on April 24th 2018 14:39 PM

PDF stands for Portable Document Format, which is used while representing the documents in a way, which is not dependent of any application software, hardware, and operating systems. In Java pdf file can be read using iText library. How to include iText in project (Eclipse) : 1. Download zip file from "https://pdfbox.apache.org/download.cgi#18x" 2. Extract .jar file from it. 3. Right click on current project in your IDE (eclipse). 4. Goto Build Path -> Configure Build Path 5. Move to Libraries tab 6. Click on Add External Jars 7. Select downloaded .jar file and click on OK Create new pdf file and write content to it :

// Java program to create pdf file and add contents to it

import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileOutputStream;

public class 
WritePDF {

    
// main method
    
public static void main(String[] args) {
        
        try {
            
            
// create new pdf
            
File file = new File("D:/Tyger.pdf");
            
FileOutputStream pdfFileout = new FileOutputStream(file);
            
Document doc = new Document();
            
            
// PdfWriter instance to add content to pdf file
            
PdfWriter.getInstance(docpdfFileout);

            
// add author of pdf file
            
doc.addAuthor("William Blake");
            
            
// add title of pdf file
            
doc.addTitle("Tyger Tyger");
            
            
// open pdf file
            
doc.open();

            
// add paragraphs
            
Paragraph para1 = new Paragraph();
            
para1.add("Tyger Tyger, burning bright,\n" "In the forests of the night;\n" 
                    
"What immortal hand or eye,\n"
                    
"Could frame thy fearful symmetry?");

            
Paragraph para2 = new Paragraph();
            
para2.add("\n\nIn what distant deeps or skies.\n" "Burnt the fire of thine eyes?\n"
                    
"On what wings dare he aspire?\n" "What the hand, dare seize the fire? ");

            
doc.add(para1);
            
doc.add(para2);

            
doc.close();
            
pdfFileout.close();

            
// print message for successful completion
            
System.out.println("Successfully Written in PDF File!");
        } catch (
Exception e) {
            
e.printStackTrace();
        }

    }

}

Posted by Paul on April 24th 2018 14:42 PM

Read pdf file in Java : iText library provides certain methods using which you can get number pages from a particular pdf file, print contents of file, and also check whether the pdf file has been tampered or not. getNumberOfPages() : This method returns, number of pages a pdf file has. getTextFromPage(obj, page_number) : This method returns contents from a particular page. isTampered() : This method checks whether a particular pdf file has been tempered or not. isEncrypted() : This method checks whether a particular pdf file has been encrypted or not. Here is the code to read pdf file in Java:

// Java program to read files in pdf

import java.io.IOException;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;

public class 
ReadPDF {

    
// main method
    
public static void main(String[] args) {
        try {

            
// create object of PdfReader object and provide location
            
PdfReader reader = new PdfReader("D:/testpdf.pdf");

            
// print number of pages from pdf
            
System.out.println("This PDF contain " reader.getNumberOfPages() + " pages\n");

            
// print contents of pdf
            
String page PdfTextExtractor.getTextFromPage(reader1);
            
System.out.println("Page Content :\n\n" page "\n\n");

            
// check whether pages are tampered or not
            
System.out.println("Is this document tampered: " reader.isTampered());

            
// check whether pages are encrypted or not
            
System.out.println("Is this document encrypted: " reader.isEncrypted());

        } catch (
IOException e) {
            
e.printStackTrace();
        }

    }

}

Posted by Paul on April 24th 2018 14:44 PM

Overwrite Data in a pdf file in Java : iText library provide certain methods to over write data in pdf file. Here is the code to overwrite data from a pdf file :

//Java program to overwrite content in pdf file

import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileOutputStream;

public class 
OverWritePDF {

    
// main method
    
public static void main(String[] args) {

        try {

            
// create new pdf
            
File file = new File("D:/Tyger.pdf");
            
FileOutputStream pdfFileout = new FileOutputStream(file);
            
Document doc = new Document();

            
// PdfWriter instance to add content to pdf file
            
PdfWriter.getInstance(docpdfFileout);

            
// open pdf file
            
doc.open();

            
// overwrite paragraphs
            
Paragraph para1 = new Paragraph();
            
para1.add("And what shoulder, & what art,\n" "Could twist the sinews of thy heart? \n"
                    
"And when thy heart began to beat, \n" "What dread hand? & what dread feet? ");

            
doc.add(para1);
            
            
doc.close();
            
pdfFileout.close();

            
// print message for successful completion
            
System.out.println("Successfully OverWritten in PDF File!");
            
        } catch (
Exception e) {
            
e.printStackTrace();
        }
    }

}

Posted by Paul on April 25th 2018 08:18 AM

Append Data in a pdf file in Java : iText library provide certain methods to append data in pdf file. Here is the code to append data to a pdf file :

// Java program to append data to pdf file

import java.io.FileOutputStream;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

public class 
AppendPDF {

    public static 
void main(String args[]) {
        
        try {
            
// create instance of PdfReader
            
PdfReader pdfReader = new PdfReader("D:\\Tyger.pdf");

            
// create instance of PdfStamper
            
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream("D:\\ModifiedTyger.pdf"));

            
// create instance of BaseFont
            // set font
            
BaseFont baseFont BaseFont.createFont(BaseFont.TIMES_ROMANBaseFont.CP1252BaseFont.NOT_EMBEDDED);

            
// get the number of pages in pdf.
            
int pages pdfReader.getNumberOfPages();

            
// iterate through the pdf pages
            
for (int i 1<= pagesi++) {
                
                
// contains the pdf data
                
PdfContentByte pageContentByte pdfStamper.getUnderContent(i);

                
pageContentByte.beginText();
                
                
// Set text font and size
                
pageContentByte.setFontAndSize(baseFont14);

                
pageContentByte.setTextMatrix(0620);

                
// append text
                
pageContentByte.showText("    This is the appended text");
                
                
pageContentByte.endText();
            }

            
pdfStamper.close();

            
System.out.println("Data appended to PDF ");
        } catch (
Exception e) {
            
e.printStackTrace();
        }
    }
}
Answer Question

Your email address will not be published. Required fields are marked *

  • Minimum 20 character
KROJ

related questions

Most liked questions

Most answered questions

Login
KROJ Refresh
Register
KROJ Refresh
Forgot password
Ask a Question
Minimum 20 character
Minimum 20 character
Reply
Minimum 20 character
KROJ Refresh