CRL88 CRL88 - 5 months ago 19
Java Question

I want to add a Line into a PDF document using java

I am currently using PDFBox and reading from within a.pdf which is found in folder 1

I first list all the Pdf files found within the folder.
Then I check the number of pages that each file has.
Now i want to go to the very end of the file below the footer to add an image that can be recognised by the printer to staple the pages since it will realise it has reached end of file.

I have arrived till getting list of files and the number of pages.

What command do i use to go to the end of the last page and write there.

Should i transform the .pdf file into text or
Should i be able to use PDPageContentStream

This is the code I am currently using I am trying to test and see if a AAA string will be insterted into my last page of the pdf file. the project is executing with no errors but for some reason it is not being inserted into the pdf.

package pdfviewer;

import java.io.*;
import java.util.*;
import java.util.List;
import java.io.IOException;

import org.apache.pdfbox.PDFReader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;





public class Main {

/**
* @param args the command line arguments
*/

public static List flist()
{
List listfile = new ArrayList();
String path = "C:/1";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();

for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
if (files.endsWith(".pdf") || files.endsWith(".PDF"))
{
listfile.add(listOfFiles[i]);


}
}
}
System.out.println(listfile);
return listfile;

}

public static void CheckPages(List a)
{
String dir = null;

Object[] arraydir = a.toArray(new Object[0]);

for (int i=0; i< arraydir.length; i++)
{
int pages = 0;
PDFont font = PDType1Font.HELVETICA_BOLD;
float fontSize = 12.0f;
dir = arraydir[i].toString();
System.out.println(dir);

try {

PDDocument pdoc = PDDocument.load(dir);
List allPages = pdoc.getDocumentCatalog().getAllPages();

pages = pdoc.getNumberOfPages();
System.out.println(allPages);
int f = pages;
System.out.println(pages);

PDPage page = (PDPage) allPages.get(i);
//System.out.println(page);
PDRectangle pageSize = page.findMediaBox();
float stringWidth = font.getStringWidth( "AAA" );
float centeredPosition = (pageSize.getWidth() - (stringWidth*fontSize)/1000f)/2f;

PDPageContentStream contentStream = new PDPageContentStream(pdoc,page,true,true);
//System.out.println(contentStream);

contentStream.beginText();
contentStream.setFont( font, fontSize );
contentStream.moveTextPositionByAmount( centeredPosition, 30 );
contentStream.drawString( "AAA" );
contentStream.endText();
contentStream.close();


pdoc.close();

}
catch (Exception e)
{
System.err.println("An exception occured in parsing the PDF Document."+ e.getMessage());
}
}

}
public static void main(String[] args)
{
List l = new ArrayList();
l = pdfviewer.Main.flist();
pdfviewer.Main.CheckPages(l);


}

}


Thanks for your attention




The code I was using above is correct.
The problem is that the PDF files being generated are version 1.2, that is the reason why I am not being allowed to Edit the pdf document.

Does anyone know what I should do if i'm using a version 1.2, since I can't really upgrade it.

Answer

you can look at the examples supplied with the library. there are two files that are of interest to you:

1- AddImageToPDF.java AddImageToPDF.java on google code search

2- AddMessageToEachPage.java AddMessageToEachPage.java on google code search

the second one adds a message to every page but you can modify it to work with the last page only. according to the PDFBox user guide document, they should be found under the folder: src/main/java/org/apache/pdfbox/examples I have added links on google code search in case you have trouble locating the files.

I have not worked with the library or tried the examples and I am quite sure you will need to modify the code a little to suit your needs for the location of the added line/image. In any case, if this helps you and you get a working solution, you can add the solution so that others can benefit from it.

EDIT: After seeing the code posted by the question author, I add a modification to make it work. I allowed myself also to make few changes for clarity.

import java.io.File;
import java.io.FileFilter;
import java.util.List;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

public class Main {

    /**
     * @param args the command line arguments
     */
    public static final FileFilter pdfFileFilter = new FileFilter() {

        public boolean accept(File file) {
            return file.isFile() && file.getName().toLowerCase().endsWith(".pdf");
        }
    };

    public static void closeQuietly(PDDocument doc) {
        if (doc != null) {
            try {
                doc.close();
            } catch (Exception exception) {
                //do something here if you wish like logging 
            }
        }
    }

    public static void CheckPages(File[] sourcePdfFiles,String textToInsert, String prefix) {

        for (File sourcePdfFile : sourcePdfFiles) {
            PDFont font = PDType1Font.HELVETICA_BOLD;
            float fontSize = 12.0f;
            PDDocument pdoc = null;
            try {

                pdoc = PDDocument.load(sourcePdfFile);
                List allPages = pdoc.getDocumentCatalog().getAllPages();
                PDPage lastPage = (PDPage) allPages.get(allPages.size() - 1);
                PDRectangle pageSize = lastPage.findMediaBox();
                float stringWidth = font.getStringWidth(textToInsert);
                float centeredPosition = (pageSize.getWidth() - (stringWidth * fontSize) / 1000f) / 2f;

                PDPageContentStream contentStream = new PDPageContentStream(pdoc, lastPage, true, true);

                contentStream.beginText();
                contentStream.setFont(font, fontSize);
                contentStream.moveTextPositionByAmount(centeredPosition, 30);
                contentStream.drawString(textToInsert);
                contentStream.endText();
                contentStream.close();

                File resultFile = new File(sourcePdfFile.getParentFile(), prefix + sourcePdfFile.getName());
                pdoc.save(resultFile.getAbsolutePath());


            } catch (Exception e) {
                System.err.println("An exception occured in parsing the PDF Document." + e.getMessage());
            } finally {
                closeQuietly(pdoc);
            }
        }
    }

    public static void main(String[] args) {
        File pdfFilesFolder = new File("C:\\1");
        File[] pdfFiles = pdfFilesFolder.listFiles(pdfFileFilter);
        //when a file is processed, the result will be saved in a new file having the location of the source file 
        //and the same name of source file prefixed with this
        String modifiedFilePrefix = "modified-";
        CheckPages(pdfFiles,"AAA", modifiedFilePrefix);
    }
}
Comments